【matplotlib】动态绘图、动态记录loss值

内容描述

Matplotlib动态图绘制

代码

import matplotlib.pyplot as plt

import math


class Dynamic_Plot_Process_Data():
    def __init__(self) -> None:
        plt.ion()

        self.__array_list = []

    def create_list(self, list_name):
        setattr(self, list_name, [])
        self.__array_list.append(list_name)

    def append_data(self, list_name, data):
        if hasattr(self, list_name):
            getattr(self, list_name).append(data)
        else:
            raise ValueError('类中不含有“{}”属性,请先用create_list函数创建对应列表属性')

    def plot_loss(self):

        color_list = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w']
        line_style = ['-', '--', '-.', ':']

        for i in range(len(self.__array_list)):
            plt.plot(getattr(self, self.__array_list[i]), color=color_list[i], linestyle=line_style[i % len(line_style)])

        plt.legend(self.__array_list)
        plt.pause(0.1)


if __name__ == '__main__':

    # 初始化绘图函数
    init = Dynamic_Plot_Process_Data()
    # 初始化待存储数据的列表信息
    init.create_list('store_y1')
    init.create_list('store_y2')
    init.create_list('store_y3')

    x = 1
    while True:
        y1 = math.sin(x)
        init.append_data('store_y1', y1)

        y2 = math.sin(x) + math.cos(x)
        init.append_data('store_y2', y2)

        y3 = math.sin(x) + math.tan(x)
        init.append_data('store_y3', y3)

        x += 1

        init.plot_loss()

结果

loss

动态绘制准确率和损失的图表,可以使用第三方库如 `matplotlib.animation` 来实现。以下是一个示例: ```python import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation # 创建空的列表来保存准确率和损失 train_accuracy = [] train_loss = [] # 创建图表和子图 fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5)) # 定义更新函数,用于更新图表数据 def update(epoch): # 清空子图内容 ax1.cla() ax2.cla() # 绘制准确率图 ax1.plot(range(epoch+1), train_accuracy[:epoch+1], label='Train Accuracy') ax1.set_xlabel('Epochs') ax1.set_ylabel('Accuracy') ax1.set_title('Training Accuracy') ax1.legend() # 绘制损失图 ax2.plot(range(epoch+1), train_loss[:epoch+1], label='Train Loss') ax2.set_xlabel('Epochs') ax2.set_ylabel('Loss') ax2.set_title('Training Loss') ax2.legend() # 创建动画对象,并指定更新函数和帧数 animation = FuncAnimation(fig, update, frames=num_epochs, interval=200) # 显示动画 plt.show() ``` 在这段代码中,我们创建了一个 `FuncAnimation` 对象,并指定了更新函数 `update` 和帧数 `num_epochs`。在每一帧中,我们清空子图内容,然后根据当前的 epoch 数组绘制准确率和损失图。最后,我们使用 `plt.show()` 显示动画。您可以根据自己的训练代码和需求进行相应的修改。请注意,这段代码仅展示了一个简单的动态绘图示例,实际使用时可能需要根据情况进行适当的调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值