如何同时打印重量和损失?

时间:2018-10-17 23:18:30

标签: python tensorflow placeholder

我刚刚开始研究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和损失。结果如下:

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"]()]]

所以,这是我的问题:

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

为什么会有这个错误?

1 个答案:

答案 0 :(得分:1)

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

顺便说一句,您可以尝试tf.summary在训练过程中可视化重量,这非常直观。