python画损失函数曲线_利用Tensorboard绘制网络识别准确率和loss曲线实例

本文展示了如何使用Tensorboard在Python中绘制神经网络的识别准确率和损失函数曲线。通过示例代码,详细解释了从数据加载到网络训练,再到结果可视化的过程。读者将了解到如何监控和理解模型的训练进度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

废话不多说,直接上代码看吧!

import tensorflow as tf

from tensorflow.examples.tutorials.mnist import input_data

#载入数据集

mnist = input_data.read_data_sets("MNIST_data",one_hot=True)

#每个批次的大小和总共有多少个批次

batch_size = 100

n_batch = mnist.train.num_examples // batch_size

#定义函数

def variable_summaries(var):

with tf.name_scope('summaries'):

mean = tf.reduce_mean(var)

tf.summary.scalar('mean', mean) #平均值

with tf.name_scope('stddev'):

stddev = tf.sqrt(tf.reduce_mean(tf.square(var-mean)))

tf.summary.scalar('stddev', stddev) #标准差

tf.summary.scalar('max', tf.reduce_max(var))

tf.summary.scalar('min', tf.reduce_min(var))

tf.summary.histogram('histogram', var) #直方图

#命名空间

with tf.name_scope("input"):

#定义两个placeholder

x = tf.placeholder(tf.float32,[None,784], name = "x_input")

y = tf.placeholder(tf.float32

### 绘制准确率损失率 为了在同一张表中展示机器学习模型的准确率损失率,可以利用Python中的`matplotlib`库。下面是一个具体的例子,该实例基于Keras框架训练后的模型历史记录对象来进行绘。 ```python import matplotlib.pyplot as plt # 假设 history 是通过 model.fit(...) 方法返回的对象 history = ... # 创建一个新的形窗口 plt.figure(figsize=(12, 5)) # 准确率曲线 plt.subplot(1, 2, 1) plt.plot(history.history['accuracy'], label='Train Accuracy') plt.plot(history.history['val_accuracy'], label='Validation Accuracy') plt.title('Model accuracy over epochs') plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend(loc='best') # 损失曲线 plt.subplot(1, 2, 2) plt.plot(history.history['loss'], label='Train Loss') plt.plot(history.history['val_loss'], label='Validation Loss') plt.title('Model loss over epochs') plt.ylabel('Loss') plt.xlabel('Epoch') plt.legend(loc='best') # 显示像 plt.tight_layout() plt.show() ``` 上述代码创建了一个包含两个子表:左侧显示的是训练集验证集上的准确率变化情况;右侧则展示了对应的损失值的变化趋势[^3]。 如果希望将这两个指标放在同一个坐标系内以便更直观对比,则可以通过设置不同的Y轴来实现: ```python fig, ax1 = plt.subplots() color = 'tab:red' ax1.set_xlabel('Epochs') ax1.set_ylabel('Loss', color=color) ax1.plot(history.history['loss'], color=color, label='Train Loss') ax1.tick_params(axis='y', labelcolor=color) ax2 = ax1.twinx() color = 'tab:blue' ax2.set_ylabel('Accuracy', color=color) ax2.plot(history.history['accuracy'], color=color, linestyle='dashed', label='Train Accuracy') ax2.tick_params(axis='y', labelcolor=color) fig.tight_layout() plt.title("Training Loss and Accuracy Over Epochs") lines_labels = [ax.get_legend_handles_labels() for ax in fig.axes] lines, labels = [sum(lol, []) for lol in zip(*lines_labels)] fig.legend(lines, labels, loc='upper right') plt.show() ``` 这段脚本会生成一张具有双Y轴的表,在左Y轴上表示损失值而在右Y轴上代表准确率,两者共享相同的X轴即epoch数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值