Tensorboard 可视化(二)画训练过程

本文深入探讨如何使用 Tensorboard 进行深度学习训练过程的可视化,包括损失曲线、学习率变化等关键指标的展示,帮助优化模型性能。
# -*- coding:UTF-8 -*-

"""
Please note, this code is only for python 3+. If you are using python 2+, please modify the code accordingly.
"""
import tensorflow as tf
import numpy as np


def add_layer(inputs, in_size, out_size, n_layer, activation_function=None):
    # add one more layer and return the output of this layer
    layer_name = 'layer%s' % n_layer
    with tf.name_scope(layer_name):
        with tf.name_scope('weights'):
            Weights = tf.Variable(tf.random_normal([in_size, out_size]), name='W')
            tf.summary.histogram(layer_name + '/weights', Weights)
        with tf.name_scope('biases'):
            biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name='b')
            tf.summary.histogram(layer_name + '/biases', biases)
        with tf.name_scope('Wx_plus_b'):
            Wx_plus_b = tf.add(tf.matmul(inputs, Weights), biases)
        if activation_function is None:
            outputs = Wx_plus_b
        else:
            outputs = activation_function(Wx_plus_b, )
            tf.summary.histogram(layer_name + '/outputs', outputs)
        return outputs


# Make up some real data
x_data = np.linspace(-1, 1, 300)[:, np.newaxis]
noise = np.random.normal(0, 0.05, x_data.shape)
y_data = np.square(x_data) - 0.5 + noise

# define placeholder for inputs to network
with tf.name_scope('inputs'):
    xs = tf.placeholder(tf.float32, [None, 1], name='x_input')
    ys = tf.placeholder(tf.float32, [None, 1], name='y_input')

# add hidden layer
l1 = add_layer(xs, 1, 10, n_layer=1, activation_function=tf.nn.relu)#1代表第一层神经
# add output layer
prediction = add_layer(l1, 10, 1, n_layer=2, activation_function=None)#2代表第二层神经

# the error between prediciton and real data
with tf.name_scope('loss'):
    loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),
                                        reduction_indices=[1]))
    tf.summary.scalar('loss', loss)#新版本tf.summary.scalar()

with tf.name_scope('train'):
    train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

sess = tf.Session()
merged = tf.summary.merge_all()
writer = tf.summary.FileWriter("logs/", sess.graph)
# important step
sess.run(tf.global_variables_initializer())

for i in range(1000):
    sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
    if i % 50 == 0:#每50步记录一个点
        result = sess.run(merged,
                          feed_dict={xs: x_data, ys: y_data})
        writer.add_summary(result, i)

 

 

 

### 可视化神经网络训练过程 为了有效地可视化神经网络的训练过程,可以采用多种工具和技术来监控和理解模型的行为。以下是几种常用的方法及其对应的工具: #### 1. 使用TensorBoard进行实时监控 TensorFlow提供了内置的日志记录器以及配套的Web应用程序——TensorBoard。通过配置日志文件路径并启动TensorBoard服务器,可以在浏览器中查看损失函数的变化趋势、权重分布以及其他重要指标。 ```python from tensorflow.keras.callbacks import TensorBoard import datetime log_dir = "logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S") tensorboard_callback = TensorBoard(log_dir=log_dir, histogram_freq=1) model.fit(x_train, y_train, epochs=50, validation_data=(x_test, y_test), callbacks=[tensorboard_callback]) ``` 此代码片段展示了如何设置`TensorBoard`回调以便在训练期间收集统计数据[^1]。 #### 2. 利用Matplotlib绘制图表 对于那些更倾向于自定义绘图的人来说,Python中的matplotlib库是一个不错的选择。它可以用来创建静态图像或动形式的表现方式,比如折线图显示每轮迭代后的性能改进情况;热力图呈现各层参数更新幅度等。 ```python import matplotlib.pyplot as plt plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('Model accuracy') plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend(['Train', 'Test'], loc='upper left') plt.show() ``` 这段脚本说明了怎样利用历史对象中的准确性数据制作简单的折线图[^2]。 #### 3. 应用Netron探索架构细节 除了关注数值上的变化外,有时也需要直观地看到整个网络拓扑结构。此时可借助开源项目Netron加载已保存好的Keras/PaddlePaddle/TensorFlow Lite等格式的模型文件(.h5,.pb),从而获得清晰易懂的层次关系展示。 ![netron](https://raw.githubusercontent.com/lutzroeder/netron/master/resources/screenshot.png?sanitize=true)[^4] 上述链接指向了一张截图,它代表了一个典型的Netron界面布局样例,在这里可以看到节点之间的连接模式及属性信息。 #### 工具选择建议 当涉及到具体的实现平台时,如果是在MATLAB环境下工作,则应该考虑官方提供的Deep Learning Toolbox™ 中集成的功能,如`analyzeNetwork()` 函数用于分析给定的深层学习网络架构,并提供有关其组成部分的信息;还有 `trainingProgressMonitor` 对象能够跟踪多个度量随时间的发展状况。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值