这里先说一下 tf.Variable 和 tf.placeholder的区别,两者都可以盛放变量,但在启动会话前,tf.Variable必须先被赋值和初始化,而tf.placeholder是需要在启动会话的时候传入值的;从直观上讲,tf.placeholder更加接近函数的形参。
import tensorflow as tf
w1 = tf.Variable(tf.truncated_normal([2,3],seed=1))
w2 = tf.Variable(tf.truncated_normal([3,1],seed=1))
x = tf.placeholder(dtype=tf.float32,shape=[1,2]) #在placeholder中,必须先指定dtype的数据类型。
a = tf.matmul(x,w1)
y = tf.matmul(a,w2)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print (sess.run(y,feed_dict={x:[[1,1]]})) #由于x的结构为1*2的矩阵,所以应当传入[[1,1]];而不能传入[1,1]
print (w1) # 这里可以看出,w1的数据类型默认为 tf.float32,因此x的数据类型也应当为float32,若两者数据类型不同,则会有 TypeError报错。