【问题标题】:TensorFlow: How to print error value being used in GradientDescentOptimizer?TensorFlow:如何打印 GradientDescentOptimizer 中使用的错误值?
【发布时间】:2019-03-01 15:51:55
【问题描述】:

我是 TensorFlow 新手。

我想在 tf.Session 块中打印错误变量以查看错误变量是如何变化的。

我在网上找到了这个基本示例,我想打印这些变量以更好地了解正在发生的事情。

感谢您的帮助!

import tensorflow as tf
import numpy as np

# x and y are placeholders for our training data
x = tf.placeholder("float")
y = tf.placeholder("float")
# w is the variable storing our values. It is initialised with starting "guesses"
# w[0] is the "a" in our equation, w[1] is the "b"
w = tf.Variable([1.0, 2.0], name="w")
# Our model of y = a*x + b
y_model = tf.multiply(x, w[0]) + w[1]

# Our error is defined as the square of the differences
error = tf.square(y - y_model)
# The Gradient Descent Optimizer does the heavy lifting
train_op = tf.train.GradientDescentOptimizer(0.01).minimize(error)

# Normal TensorFlow - initialize values, create a session and run the 
model
model = tf.global_variables_initializer()

with tf.Session() as session:
    session.run(model)
    for i in range(100):
        x_value = np.random.rand()
        y_value = x_value * 2 + 6
        session.run(train_op, feed_dict={x: x_value, y: y_value})
        e = session.run(error)
        #****PRINT ERROR VARIABLE?*****

    w_value = session.run(w)
    print("Predicted model: {a:.3f}x + {b:.3f}".format(a=w_value[0], 
b=w_value[1]))

【问题讨论】:

    标签: python-3.x tensorflow


    【解决方案1】:

    您必须提供模型以获得错误值:

    e = session.run(error, feed_dict={x: x_value, y: y_value})
    print(e)
    

    但是如果占位符像这样工作,我更喜欢这个:

    import tensorflow as tf
    import numpy as np
    
    # x and y are placeholders for our training data
    x = tf.placeholder(tf.float32,())
    y = tf.placeholder(tf.float32,())
    # w is the variable storing our values. It is initialised with starting "guesses"
    # w[0] is the "a" in our equation, w[1] is the "b"
    w = tf.Variable([1.0, 2.0], name="w")
    # Our model of y = a*x + b
    y_model = tf.multiply(x, w[0]) + w[1]
    
    # Our error is defined as the square of the differences
    error = tf.square(y - y_model)
    # The Gradient Descent Optimizer does the heavy lifting
    train_op = tf.train.GradientDescentOptimizer(0.01).minimize(error)
    
    # Normal TensorFlow - initialize values, create a session and run the 
    init = tf.global_variables_initializer()
    
    with tf.Session() as sess:
        sess.run(init)
        for i in range(100):
            x_value = np.random.rand()
            y_value = x_value * 2 + 6
            _,e=sess.run([train_op,error], feed_dict={x: x_value, y: y_value})
            print(e)
    
    w_value = sess.run(w)
    print("Predicted model: {a:.3f}x + {b:.3f}".format(a=w_value[0], 
    

    b=w_value[1]))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-05
      • 2016-09-01
      • 2017-10-08
      • 2017-12-27
      • 2018-09-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多