TensorFlow编程入门

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

一个30010300*10的矩阵和一个1101*10的向量相加。和直觉相悖。 其实是在tensorflow中允许矩阵和向量相加,即 Ci,j=Ai,j+bjC_{i,j}=A_{i,j}+b_j,也就是给矩阵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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章