《TensorFlow-实战Google深度学习框架》3.4.4通过tensorflow训练神经网络模型

Tensorflow提供了placeholder机制用于提供输入数据。placeholder相当于定义了一个位置,这个位置的数据在程序运行时再指定。

import tensorflow as tf

w1 = tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1))
w2 = tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1))

#定义placeholder作为存放输入数据的地方,其维度不一定要定义
#如果维度是确定的,给出维度,可以减少出错的概率
x = tf.placeholder(tf.float32, shape=(1, 2), name='input')

a = tf.matmul(x, w1)
y = tf.matmul(a, w2)

with tf.Session() as sess:
    init_op = tf.global_variables_initializer()
    sess.run(init_op)
    print(sess.run(y, feed_dict={x:[[0.7, 0.9]]}))

运行结果:


在实践这个程序中,踩过的几个坑如下

1.     print(sess.run(y, feed_dict={x:[0.7, 0.9]}))


此处报错是placeholder定义的维度是1*2,feed_dict提供的x的维度却不对,应该是

print(sess.run(y, feed_dict={x:[[0.7, 0.9]]}))
注意是[[0.7, 0.9]],而不是[0.7, 0.9]。因为对python不熟悉,所以容易出这种错误。还是应该把python的教程快速学习一遍。

placeholder的维度可以不指定,但是如果事先知道,最好指定,减少出错的概率

2.    print(sess.run(y, feed_dict={input:[[0.7, 0.9]]}))


错误类型:不能将feed_dict的key值作为张量:不能将一个内建函数或者方法转化成一个张量。

修改成:

print(sess.run(y, feed_dict={x:[[0.7, 0.9]]}))

就可以了。具体原因不是很了解,先记录下来。后面也许就明白了

猜你喜欢

转载自blog.csdn.net/weixin_42142612/article/details/80891037