首页 > 解决方案 > 如何同时打印重量和损失?

问题描述

我刚开始学习 TensorFlow。现在我对如何同时打印重量和损失感到困惑。

在这段代码中:

x_data=np.random.rand(100)
y_data=x_data*0.1+0.2
b=tf.Variable(0.)  #must be 0.  not 0
k=tf.Variable(0.)
y=k*x_data+b
loss=tf.reduce_mean(tf.square(y_data-y))
optimizer=tf.train.GradientDescentOptimizer(0.2)
train=optimizer.minimize(loss)
init=tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    for step in range(501):
        sess.run(train)
        if step%20==0:
            print(step,sess.run([k,b,loss]))

我可以同时打印参数 k、b 和 loss。结果如下所示:

0 [0.056439728, 0.10114789, 0.014995859]
20 [0.105686955, 0.19681107, 2.4290184e-06]
40 [0.10358144, 0.19799174, 9.633536e-07]
60 [0.10225546, 0.19873528, 3.8206556e-07]
80 [0.10142042, 0.19920352, 1.515299e-07]
......

但在我尝试过的另一个代码中:

x_data = np.linspace(-0.5, 0.5, 200)[:, np.newaxis]  
noise = np.random.normal(0, 0.02, x_data.shape)
y_data = np.square(x_data) + noise
x = tf.placeholder(tf.float32, [None, 1])
y = tf.placeholder(tf.float32, [None, 1])
Weights_L1 = tf.Variable(tf.random_normal([1, 10]))  # 1 row 10 column
biases_L1 = tf.Variable(tf.zeros([1, 10]))
Wx_plus_b_L1 = tf.matmul(x, Weights_L1) + biases_L1
L1 = tf.nn.tanh(Wx_plus_b_L1)
Weights_L2 = tf.Variable(tf.random_normal([10, 1]))  # 10 row 1 column
biases_L2 = tf.Variable(tf.zeros([1, 1]))
Wx_plus_b_L2 = tf.matmul(L1, Weights_L2) + biases_L2
prediction = tf.nn.tanh(Wx_plus_b_L2)
loss = tf.reduce_mean(tf.square(y - prediction))
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for step in range(2000):
        sess.run(train_step, feed_dict={x: x_data, y: y_data})
        if step % 200 == 0:
            print(step, sess.run([Weights_L1]))
            print(step,sess.run([loss]))
    prediction_value=sess.run(prediction,feed_dict={x:x_data})

在这里,我想使用两个打印件分别显示重量和损失。但我有错误:

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder_4' with dtype float and shape [?,1]
 [[Node: Placeholder_4 = Placeholder[dtype=DT_FLOAT, shape=[?,1], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

所以,这是我的问题:

如何同时打印重量和损失?如果我想打印更多参数怎么办?

为什么我有这个错误?

标签: pythontensorflowplaceholder

解决方案


取决于loss输入占位符xy,因此print(step,sess.run([loss]))应修改为print(step, sess.run([loss], feed_dict={x: x_data, y: y_data}))

顺便说一句,您可以尝试tf.summary在训练期间将权重可视化,这非常直观。


推荐阅读