尝试使用matplotlib更新一个简单的Tensorflow项目的图

时间:2018-12-19 13:47:06

标签: python tensorflow matplotlib

我正在研究一个通过机器学习进行三次回归的项目。我认为显示这条线的演变会很有趣,所以我决定着手研究如何在大约第100步左右显示这条线。

最初,我使用线程来重复关闭图,然后每100步重新绘制一次图,但这显然不是理想的选择。对于我如何每100步更新一次绘图,我将深表感谢。

下面是我的代码:

import tensorflow as tf
import matplotlib.pyplot as plt
import threading
import time
import random
tf.reset_default_graph()
input_data = tf.placeholder(dtype=tf.float32, shape=None)
output_data = tf.placeholder(dtype=tf.float32, shape=None)
avalue = tf.Variable(random.randint(-1000,1000), dtype=tf.float32)
bvalue = tf.Variable(random.randint(-1000,1000), dtype=tf.float32)
cvalue = tf.Variable(random.randint(-1000,1000), dtype=tf.float32)
dvalue = tf.Variable(random.randint(-1000,1000), dtype=tf.float32)
model_operation = avalue *(input_data * input_data * input_data) + bvalue * (input_data * input_data) + (cvalue * input_data) + dvalue
error = model_operation - output_data
squared_error = tf.square(error)
loss = tf.reduce_mean(squared_error)
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.00005)
train = optimizer.minimize(loss)
init = tf.global_variables_initializer()
x_values = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
y_values = [-268, -126, -46, -10, 0, 2, 14, 54, 140, 290, 522]
with tf.Session() as sess:
    sess.run(init)
    for i in range(10000):
        sess.run(train, feed_dict={input_data: x_values, output_data: y_values})
        if i % 100 == 0:
            print(*sess.run([avalue, bvalue, cvalue, dvalue]))
            plt.plot(x_values, sess.run(model_operation, feed_dict={input_data: x_values}))
            plt.plot(x_values, y_values, 'ro', 'Training Data')
            ## trying to make the function here
    print('loss value = ' + str(sess.run(loss, feed_dict={input_data: x_values, output_data: y_values})))
    plt.plot(x_values, y_values, 'ro', 'Training Data')
    plt.plot(x_values, sess.run(model_operation, feed_dict={input_data: x_values}))
    plt.show()

0 个答案:

没有答案