Tensorflow调试或打印语句

时间:2017-09-14 19:08:32

标签: debugging printing tensorflow

我对TensorFlow很新,并试图学习它。我从教程网站复制了一个程序。当我修改它时,程序存在问题,我必须调试。我正在寻求帮助,以了解如何打印某些值,如成本和优化程序。我必须弄清楚每次迭代中要更新的值。我知道笔记不能打印,但我认为成本和优化器是输入应该是可打印的,对吗?

plt.ion()
n_observations = 100
xs = np.linspace(-3, 3, n_observations)
ys = np.sin(xs) + np.random.uniform(-0.5, 0.5, n_observations)

X = tf.placeholder(tf.float32)

Y = tf.placeholder(tf.float32)

Y_pred = tf.Variable(tf.random_normal([1]), name='bias')
for pow_i in range(1, 5):

    W = tf.Variable(tf.random_normal([1]), name='weight_%d' % pow_i)
    Y_pred = tf.add(tf.multiply(tf.pow(X, pow_i), W), Y_pred)

cost = tf.reduce_sum(tf.pow(Y_pred - Y, 2)) / (n_observations - 1)
d = tf.Print(cost, [cost, 2.0], message="Value of cost id:")

learning_rate = 0.01
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

n_epochs = 10
with tf.Session() as sess:

    sess.run(tf.global_variables_initializer())
    prev_training_cost = 0.0
    for epoch_i in range(n_epochs):


    for (x, y) in zip(xs, ys):
    print("Msg2 x, y ", x, y, cost);
    sess.run(optimizer, feed_dict={X: x, Y: y})
    sess.run(d)
    print("Msg3 x, y ttt ", x, y, optimizer);

        training_cost = sess.run(
            cost, feed_dict={X: xs, Y: ys})
        print(training_cost)
        print("Msg3 cost, xs ys", cost, xs, ys);

        if epoch_i % 100 == 0:
            ax.plot(xs, Y_pred.eval(
                feed_dict={X: xs}, session=sess),
                'k', alpha=epoch_i / n_epochs)
        fig.show()
        #plt.draw()
    # Allow the training to quit if we've reached a minimum
    if np.abs(prev_training_cost - training_cost) < 0.001:
        break
    prev_training_cost = training_cost

ax.set_ylim([-3, 3])
fig.show()
plt.waitforbuttonpress()

1 个答案:

答案 0 :(得分:1)

在您的示例中,costoptimizer引用图表中的张量,而不是图表的输入。需要在session.run调用中获取以便能够打印其python值。例如,在您的示例中,打印training_cost应该打印成本。同样,如果您从optimizer返回session.run(optimizer, ...)的值,则应返回正确的可打印值。

如果您对调试和打印值感兴趣,请查看:

希望有所帮助!