tensorflow: session開始對前tensor做一些處理
阿新 • • 發佈:2018-12-08
tf.boolean_mask
這個操作可以用於留下指定的元素,類似於numpy的操作。
import numpy as np
tensor = tf.range(4)
mask = np.array([True, False, True, False])
bool_mask = tf.boolean_mask(tensor, mask)
print sess.run(bool_mask)
[0 2]
tf.greater
首先張量x和張量y的尺寸要相同,輸出的tf.greater(x, y)也是一個和x,y尺寸相同的張量。如果x的某個元素比y中對應位置的元素大,則tf.greater(x, y)對應位置返回True,否則返回False。
import tensorflow as tf x = tf.Variable([[1,2,3], [6,7,8], [11,12,13]]) y = tf.Variable([[0,1,2], [5,6,7], [10,11,12]]) x1 = tf.Variable([[1,2,3], [6,7,8], [11,12,13]]) y1 = tf.Variable([[10,1,2], [15,6,7], [10,21,12]]) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print(sess.run(tf.greater(x, y))) print(sess.run(tf.greater(x1, y1))) [[ True True True] [ True True True] [ True True True]] [[False True True] [False True True] [ True False True]]
tf.py_func
py_func(
func,
inp,
Tout,
stateful=True,
name=None
)
引數:
func: 一個 Python 函式, 它接受 NumPy 陣列作為輸入和輸出,並且陣列的型別和大小必須和輸入和輸出用來銜接的 Tensor 大小和資料型別相匹配.
inp: 輸入的 Tensor 列表.
Tout: 輸出 Tensor 資料型別的列表或元祖.
stateful: 狀態,布林值.
name: 節點 OP 的名稱.
i = tf.constant([[0,1,2,3,4], [9,8,0,3,0]]) a = tf.cast(i,tf.bool) b = tf.gather(i,1) c = tf.not_equal(b,0) neg_c = tf.logical_not(c) indices = tf.where(c) neg_indices = tf.where(neg_c) def choose(x): return np.random.choice(np.ravel(x)) d = tf.py_func(choose,[indices],tf.int64) with tf.Session() as sess: print(sess.run(a)) print(sess.run(b)) print(sess.run(c)) print("neg_c:",sess.run(neg_c)) print("indices:",sess.run(indices)) print("neg_indices:",sess.run(neg_indices)) print("....",sess.run(d)) [[False True True True True] [ True True False True False]] [9 8 0 3 0] [ True True False True False] neg_c: [False False True False True] indices: [[0] [1] [3]] neg_indices: [[2] [4]] .... 1
tf.cond
tf.cond(pred, true_fn=None, false_fn=None, strict=False, name=None, fn1=None, fn2=None)
Return true_fn()
if the predicate pred
is true else false_fn()
import tensorflow as tf
a = tf.placeholder(tf.bool) #placeholder for a single boolean value
b = tf.cond(tf.equal(a, tf.constant(True)), lambda: tf.constant(10), lambda: tf.constant(0))
sess = tf.InteractiveSession()
res = sess.run(b, feed_dict = {a: True})
sess.close()
print(res)
10
tf.while_loop
tf.while_loop(
cond,
body,
loop_vars,
shape_invariants=None,
parallel_iterations=10,
back_prop=True,
swap_memory=False,
name=None,
maximum_iterations=None,
return_same_structure=False
)
作用:Repeat body
while the condition cond
is true
注意的是:loop_vars
是一個傳遞進去cond
與body
的 tuple, namedtuple or list of tensors . cond
與 body
同時接受 both與 loop_vars
一樣多的引數。
例子:
def body(x):
a = tf.random_uniform(shape=[2, 2], dtype=tf.int32, maxval=100)
b = tf.constant(np.array([[1, 2], [3, 4]]), dtype=tf.int32)
c = a + b
return tf.nn.relu(x + c)
def condition(x):
return tf.reduce_sum(x) < 100x = tf.Variable(tf.constant(0, shape=[2, 2]))with tf.Session():
tf.initialize_all_variables().run()
result = tf.while_loop(condition, body, [x])
print(result.eval())