【问题标题】:Tensorflow cost function placeholder errorTensorFlow 成本函数占位符错误
【发布时间】:2018-05-14 02:34:12
【问题描述】:

我有以下代码试图优化具有两个输入和三个参数(m_1、m_2 和 b)的线性模型。最初,我在以 feed_dict 接受它们的方式导入数据时遇到问题,我通过将其放入一个 numpy 数组来解决。

现在优化器函数将顺利运行(并且输出看起来大致像是在优化参数),但是一旦我尝试用最后的行返回成本:

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)

【问题讨论】:

    标签: python tensorflow placeholder


    【解决方案1】:

    cost 张量是占位符张量的函数,这要求它们有一个值。由于对 sess.run(cost) 的调用没有提供这些占位符,因此您会看到错误。 (换一种说法 - 你想计算 xy_ 的哪些值?)

    所以你想换行:

        cost_val = sess.run(cost)
    

    到:

        cost_val = sess.run(cost, feed_dict=feed)
    

    希望对您有所帮助。

    【讨论】:

    • facepalm 如此简单,但我可能永远也想不通。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-20
    • 2016-08-19
    • 2017-11-12
    • 2016-04-20
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多