Tensorflow常用函式
tf.concat
把一組向量從某一維上拼接起來,很向numpy中的Concatenate,官網例子:
t1 = [[1, 2, 3], [4, 5, 6]]
t2 = [[7, 8, 9], [10, 11, 12]]
tf.concat([t1, t2], 0) ==> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
tf.concat([t1, t2], 1) ==> [[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]]
# tensor t3 with shape [2, 3]
# tensor t4 with shape [2, 3]
tf.shape(tf.concat([t3, t4], 0)) ==> [4, 3]
tf.shape(tf.concat([t3, t4], 1)) ==> [2, 6]
其實,如果是list型別的話也是可以的,只要是形似Tensor,最後tf.concat返回的還是Tensor型別
tf.gather
類似於陣列的索引,可以把向量中某些索引值提取出來,得到新的向量,適用於要提取的索引為不連續的情況。這個函式似乎只適合在一維的情況下使用。
import tensorflow as tf
a = tf.Variable([[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15]])
index_a = tf.Variable([0,2])
b = tf.Variable([1,2,3,4,5,6,7,8,9,10])
index_b = tf.Variable([2,4,6,8])
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(sess.run(tf.gather(a, index_a)))
print(sess.run(tf.gather(b, index_b)))
# [[ 1 2 3 4 5]
# [11 12 13 14 15]]
# [3 5 7 9]
tf.gather_nd
同上,但允許在多維上進行索引,例子只展示了一種很簡單的用法,更復雜的用法可見官網。
import tensorflow as tf
a = tf.Variable([[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15]])
index_a = tf.Variable([[0,2], [0,4], [2,2]])
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(sess.run(tf.gather_nd(a, index_a)))
# [ 3 5 13]
tf.greater
判斷函式。首先張量x和張量y的尺寸要相同,輸出的tf.greater(x, y)也是一個和x,y尺寸相同的張量。如果x的某個元素比y中對應位置的元素大,則tf.greater(x, y)對應位置返回True,否則返回False。與此類似的函式還有tf.greater_equal。
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.cast
轉換資料型別。
a = tf.constant([0, 2, 0, 4, 2, 2], dtype='int32')
print(a)
# <tf.Tensor 'Const_1:0' shape=(6,) dtype=int32>
b = tf.cast(a, 'float32')
print(b)
# <tf.Tensor 'Cast:0' shape=(6,) dtype=float32>
tf.expand_dims & tf.squeeze
增加 / 壓縮張量的維度。
a = tf.constant([0, 2, 0, 4, 2, 2], dtype='int32')
print(a)
# <tf.Tensor 'Const_1:0' shape=(6,) dtype=int32>
b = tf.expand_dims(a, 0)
print(b)
# <tf.Tensor 'ExpandDims:0' shape=(1, 6) dtype=int32>
print(tf.squeeze(b, 0))
# <tf.Tensor 'Squeeze:0' shape=(6,) dtype=int32>