2.tensorflow:使用tensorboard记录loss变化,模型结构

#coding:utf-8
'''
a liner regression by tenosrflow.
input dimension: 1, output dimension: 1.
显示每个epoch的loss
保存模型图,使用tensorboard

'''
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.python.tools.inspect_checkpoint import print_tensors_in_checkpoint_file


# data
x_train = np.linspace(-1, 1, 100)
y_train = 10 * x_train + np.random.randn(x_train.shape[0])
# plt.plot(x_train, y_train, "ro", label="data")
# plt.legend()
# plt.show()

epochs = 30
display_step = 2
# input, output
x = tf.placeholder(dtype="float", name="input")
y = tf.placeholder(dtype="float", name="label")
# w, b
w = tf.Variable(initial_value=tf.random_normal([1]), name="weight")
b = tf.Variable(initial_value=tf.zeros([1]), name="bias")
# model
z = tf.multiply(x, w) + b
tf.summary.histogram("z", z)  # 把z的值以直方图显示

# loss functon
cost = tf.reduce_mean(tf.square(y - z))
tf.summary.scalar("cost functon", cost)  # 把loss函数以标量显示
# optimizer
optim = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost)
saver = tf.train.Saver(max_to_keep=2)  # save 2 model
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    summary_merge = tf.summary.merge_all()  # 合并所有summary
    f_summary = tf.summary.FileWriter(logdir="log", graph=sess.graph)
    for epoch in range(epochs):
        for x_batch, y_batch in zip(x_train, y_train):  # batch is 1 there
            sess.run(optim, feed_dict={x:x_batch, y:y_batch})
            summary_tmp = sess.run(summary_merge, feed_dict={x:x_batch, y:y_batch})  # 计算summary
            f_summary.add_summary(summary=summary_tmp, global_step=epoch)  # 写入summary
        if epoch % display_step ==0:
            loss = sess.run(cost, feed_dict={x:x_train, y:y_train})
            print("epoch: %d, loss: %d" %(epoch, loss))
            # 保存训练过程中的模型
            saver.save(sess, "line_regression_model/regress.cpkt", global_step=epoch)
    print("train finished...")
    # 保存最终的模型
    saver.save(sess, "line_regression_model/regress.cpkt")
    print("final loss:", sess.run(cost, feed_dict={x:x_train, y:y_train}))
    print("weight:", sess.run(w))
    print("bias:", sess.run(b))

    # show train data and predict data
    plt.plot(x_train, y_train, "ro", label="train")
    predict = sess.run(w) * x_train + sess.run(b)
    plt.plot(x_train, predict, "b", label="predict")
    plt.legend()
    plt.show()

运行完毕发现多了一个log文件夹,里面文件为events.out.tfevents.1542444510.mingzhangdeMacBook-Pro.local

在macbook中执行:tensorboard --logdir=log

提示:TensorBoard 1.8.0 at http://mingzhangdeMacBook-Pro.local:6006 (Press CTRL+C to quit)

然而在macbook中这个网址并不能打开(在Ubuntu中可以打开生成多网址),而是在浏览器中输入这个才能打开:http://localhost:6006/

2.tensorflow:使用tensorboard记录loss变化,模型结构_第1张图片

 

你可能感兴趣的:(tensorflow)