feed_dict 使用
1.輸出 Hello World
Str = tf.placeholder(tf.string)
with tf.Session() as sess:
output = sess.run(Str, feed_dict={Str: 'Hello World !'})
print(output)
Hello World !
2.字符串拼接
Str1 = tf.placeholder(tf.string)
Str2 = tf.placeholder(tf.string)
Str3 = tf.placeholder(tf.string)
Str = tf.string_join([Str1, Str2, Str3], separator=" ")
with tf.Session() as sess:
output = sess.run(Str, feed_dict={Str1: 'I', Str2: 'like', Str3: 'TensorFlow !'})
print(output.decode())
I like TensorFlow !
3.浮點數乘積
4.不用佔位符,而用常量,也可完成
5.矩陣乘法;使用 feed_dict完成矩陣乘法
broadcasting機制
xs = tf.placeholder(tf.float32, [None, 1])
Weight = tf.Variable(tf.random_normal([1, 10]))
biases = tf.Variable(tf.zeros([1, 10]) + 0.1)
tf.matmul(xs, Weight) + biases
一個的矩陣和一個的向量相加。和直覺相悖。 其實是在tensorflow中允許矩陣和向量相加,即 ,也就是給矩陣A的每一行都加上向量b。 那麼這至少要求矩陣的列數和向量的元素個數對齊。 這種隱式的複製向量b到很多位置的辦法,叫做broadcasting。廣播機制。
reduce_sum函數
reduce_sum() 就是求和,由於求和的對象是tensor,所以是沿着tensor的某些維度求和。函數名中加了reduce是表示求和後會降維,當然可以通過設置參數來保證不降維,但是默認就是要降維的。
reduce_sum(input_tensor,axis=None,keep_dims=False,name=None,reduction_indices=None)
1)input_tensor:輸入的張量。
2)axis:沿着哪個維度求和。
對於二維的input_tensor張量,0表示按列求和,1表示按行求和,[0, 1]表示先按列求和再按行求和。
3)keep_dims:默認值爲Flase,表示默認要降維。若設爲True,則不降維。
4)name:名字。
5)reduction_indices:默認值是None,即把input_tensor降到 0維,也就是一個數。
對於2維input_tensor,reduction_indices=0時,按列;reduction_indices=1時,按行。
注意,reduction_indices與axis不能同時設置。
# 'x' is [[1, 1, 1]
# [1, 1, 1]]
#求和
tf.reduce_sum(x) ==> 6
#按列求和
tf.reduce_sum(x, 0) ==> [2, 2, 2]
#按行求和
tf.reduce_sum(x, 1) ==> [3, 3]
#按照行的維度求和
tf.reduce_sum(x, 1, keep_dims=True) ==> [[3], [3]]
#行列求和
tf.reduce_sum(x, [0, 1]) ==> 6