Python Tensorflow成本函数占位符错误
我有下面的代码试图优化一个具有两个输入和三个参数(m_1、m_2和b)的线性模型。最初,我在导入数据时遇到了一些问题,比如feed_dict会接受这些数据,我将其放在一个numpy数组中解决了这个问题 现在optimizer函数将平稳运行(输出看起来大致像是在优化参数),但一旦我尝试返回最后一行的成本:Python Tensorflow成本函数占位符错误,python,tensorflow,placeholder,Python,Tensorflow,Placeholder,我有下面的代码试图优化一个具有两个输入和三个参数(m_1、m_2和b)的线性模型。最初,我在导入数据时遇到了一些问题,比如feed_dict会接受这些数据,我将其放在一个numpy数组中解决了这个问题 现在optimizer函数将平稳运行(输出看起来大致像是在优化参数),但一旦我尝试返回最后一行的成本: cost_val = sess.run(cost) 它返回以下错误: tensorflow.python.framework.errors_impl.InvalidArgumentError:
cost_val = sess.run(cost)
它返回以下错误:
tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder_2' with dtype float and shape [?,1]
[[Node: Placeholder_2 = Placeholder[dtype=DT_FLOAT, shape=[?,1], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
如果我单独评论这句话,一切都会顺利进行
我尝试将成本函数从我使用的更复杂的函数更改为更简单的函数,但错误仍然存在。我知道这可能与数据输入形状(?)有关,但无法计算数据如何用于优化器,而不是成本函数
# reading in data
filename = tf.train.string_input_producer(["file.csv"])
reader = tf.TextLineReader(skip_header_lines=1)
key, value = reader.read(filename)
rec_def = [[1], [1], [1]]
input_1, input_2, col3 = tf.decode_csv(value, record_defaults=rec_def)
# parameters
learning_rate = 0.001
training_steps = 300
x = tf.placeholder(tf.float32, [None,1])
x2 = tf.placeholder(tf.float32, [None,1])
m = tf.Variable(tf.zeros([1,1]))
m2 = tf.Variable(tf.zeros([1,1]))
b = tf.Variable(tf.zeros([1]))
y_ = tf.placeholder(tf.float32, [None,1])
y = tf.matmul(x,m) + tf.matmul(x2,m2) + b
# cost function
# cost = tf.reduce_mean(tf.log(1+tf.exp(-y_*y)))
cost = tf.reduce_sum(tf.pow((y_-y),2))
# Gradient descent optimizer
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
# initializing variables
init = tf.global_variables_initializer()
with tf.Session() as sess:
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
sess.run(init)
for i in range(training_steps):
xs = np.array([[sess.run(input_1)]])
ys = np.array([[sess.run(input_2)]])
label = np.array([[sess.run(col3)]])
feed = {x:xs, x2:ys, y_:label}
sess.run(optimizer, feed_dict=feed)
cost_val = sess.run(cost)
coord.request_stop()
coord.join(threads)
cost
张量是占位符张量的函数,这要求它们有一个值。由于对sess.run(cost)的调用没有提供这些占位符,因此您看到了错误。(换言之,您想计算成本的x
和y
值是多少?)
因此,您要更改行:
cost_val = sess.run(cost)
致:
希望这能有所帮助。facepalm很简单,但我可能永远也不会明白。谢谢!
cost_val = sess.run(cost, feed_dict=feed)