我试图将数组以批次的形式输入到TensorFlow的占位符中。但即使提供了正确的形状,我仍然收到一个InvalidArgumentError
错误。
这是我代码的一部分:
import tensorflow as tf
import numpy as np
xdata = np.linspace(1,50, 10000)
noise = np.random.rand(len(xdata))
y_true = (1.5*xdata) + 5 + noise #m = 1.5 and c = 5
m = tf.Variable(0.1) #initial values
c = tf.Variable(0.2)
batch_size = 10
x = tf.placeholder(tf.float32, [batch_size])
y = tf.placeholder(tf.float32, [batch_size])
y_hat = (m*x) + c
error = tf.reduce_sum(tf.square(y-y_hat))
optimizer = tf.train.GradientDescentOptimizer(learning_rate= 0.01)
train = optimizer.minimize(error)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
n_batches = 1000
for i in range(n_batches):
rand_int = np.random.randint(len(xdata), size =batch_size)
feed_dict = {x:xdata[rand_int], y: y_true[rand_int]}
sess.run(train, feed_dict = feed_dict)
print('Batch:',i, ' loss: ', sess.run(error))
m_final, slope_final = sess.run([m , c])
错误信息如下:
InvalidArgumentError: You must feed a value for placeholder tensor ‘Placeholder’ with dtype float and shape [10]
为什么会发生这种情况?
回答:
错误发生在这一行:
print('Batch:', i, ' loss: ', sess.run(error))
为了计算张量error
的值,你必须为占位符x
和y
提供值:
sess.run(error, feed_dict)