Tensorflow成本函数占位符错误

Tensorflow cost function placeholder error

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

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

cost_val = sess.run(cost)

它 return 出现以下错误:

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) 的调用没有提供这些占位符,因此您会看到错误。 (换句话说 - 您要计算成本的 xy_ 是什么值?)

所以你想换行:

    cost_val = sess.run(cost)

至:

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

希望对您有所帮助。