在线性回归中添加变量显示
在 TensorBoard 中观察损失模型的参数,损失值等变量的变化。
一、实现步骤
- 1.创建事件文件
file_writer = tf.summary.FileWrite('e:/events/test',graph=sess.graph)
- 2.收集变量
收集对于损失函数和准确率等单值变量使用 tf.summary.scalar(name=’’,tensor),收集高维 度变量参数使用 tf.summary.histogram(name=’’,tensor),收集输入的图片张量能显示图片使用 tf.summary.image(name=’’,tensor),其中 name 为变量的名字,tensor 为值。使用示例如下:
tf.summary.scalar(‘error’,error)
tf.summary.histogram('weights',weight)
tf.summary.histogram('bias',bias)
- 3.合并变量
merged = tf.summary.merge_all()
- 4.运行合并变量
summary = sess.run(merged)
- 5.将 summary 写入事件文件
file_writer.add_summary(summary,i)
二、实例代码
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
def linear_regression():
# 1.Prepare data
X = tf.random_normal(shape=[100,1])
y_true = tf.matmul(X,[[0.8]]) + 0.7
# Construct weights and bias, use variables to create
weight = tf.Variable(initial_value=tf.random_normal(shape=[1,1]))
bias = tf.Variable(initial_value=tf.random_normal(shape=[1,1]))
y_predict = tf.matmul(X,weight) + bias
# 2.Construct loss function
error = tf.reduce_mean(tf.square(y_predict-y_true))
# 3.Optimization loss
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(error)
# (2)Increase variable display, collect variables
tf.summary.scalar('error',error)
tf.summary.histogram('weights',weight)
tf.summary.histogram('bias',bias)
# (3)Increase variable display, merge variables
merged = tf.summary.merge_all()
# Initialize variables
init = tf.global_variables_initializer()
# Start conversation
with tf.Session() as sess:
# Run initialization variables
sess.run(init)
print('View model parameters before training: weight: %f, partial amount: %f, loss: %f'%(weight.eval(),bias.eval(),error.eval()))
# (1)Add variable display, create text events
file_Writer = tf.summary.FileWriter('e:/events/test',graph=sess.graph)
# Start training
for i in range(100):
sess.run(optimizer)
print('View model parameters after training %d times: weight: %f, partial amount: %f, loss: %f'%((i+1), weight.eval(), bias.eval(), error.eval()))
# (4)Increase variable display, run merge variable
summary = sess.run(merged)
# (5)Write variables to event file
file_Writer.add_summary(summary,i)
if __name__ == '__main__':
linear_regression()
三、运行结果
四、变量可视化
- 1.打开 CMD ,输入命令:
tensorboard --logdir="e:/events/test"
,结果如下:
- 2.打开浏览器,输入
http://localhost:6006/
,结果如下:
正是江南好风景