当前位置: 首页 > news >正文

李沐-第六章-LeNet训练中的pycharm jupyter-notebook Animator类的显示问题

问题

系统: win11
显卡:5060
CUDA:12.8
pytorch:2.7.1+cu128
pycharm:2025.2

使用d2l中的动图显示Animator类和train_ch6训练函数,在浏览器的jupyter notebook中可以正常显示动图,但是在Pycharm的集成jupyter中,开始训练时动图显示一闪而过,只有在训练结束时才显示。
原Animator类:

class Animator:"""For plotting data in animation."""def __init__(self, xlabel=None, ylabel=None, legend=None, xlim=None,ylim=None, xscale='linear', yscale='linear',fmts=('-', 'm--', 'g-.', 'r:'), nrows=1, ncols=1,figsize=(3.5, 2.5)):"""Defined in :numref:`sec_utils`"""# Incrementally plot multiple linesif legend is None:legend = []d2l.use_svg_display()self.fig, self.axes = d2l.plt.subplots(nrows, ncols, figsize=figsize)if nrows * ncols == 1:self.axes = [self.axes, ]# Use a lambda function to capture argumentsself.config_axes = lambda: d2l.set_axes(self.axes[0], xlabel, ylabel, xlim, ylim, xscale, yscale, legend)self.X, self.Y, self.fmts = None, None, fmtsdef add(self, x, y):# Add multiple data points into the figureif not hasattr(y, "__len__"):y = [y]n = len(y)if not hasattr(x, "__len__"):x = [x] * nif not self.X:self.X = [[] for _ in range(n)]if not self.Y:self.Y = [[] for _ in range(n)]for i, (a, b) in enumerate(zip(x, y)):if a is not None and b is not None:self.X[i].append(a)self.Y[i].append(b)self.axes[0].cla()for x, y, fmt in zip(self.X, self.Y, self.fmts):self.axes[0].plot(x, y, fmt)self.config_axes()display.display(self.fig)display.clear_output(wait=True) # 需要改的就是这里!

原train_ch6函数:

def train_ch6(net, train_iter, test_iter, num_epochs, lr, device):"""Train a model with a GPU (defined in Chapter 6).Defined in :numref:`sec_utils`"""def init_weights(m):if type(m) == nn.Linear or type(m) == nn.Conv2d:nn.init.xavier_uniform_(m.weight)net.apply(init_weights)print('training on', device)net.to(device)optimizer = torch.optim.SGD(net.parameters(), lr=lr)loss = nn.CrossEntropyLoss()animator = d2l.Animator(xlabel='epoch', xlim=[1, num_epochs],legend=['train loss', 'train acc', 'test acc'])timer, num_batches = d2l.Timer(), len(train_iter)for epoch in range(num_epochs):# Sum of training loss, sum of training accuracy, no. of examplesmetric = d2l.Accumulator(3)net.train()for i, (X, y) in enumerate(train_iter):timer.start()optimizer.zero_grad()X, y = X.to(device), y.to(device)y_hat = net(X)l = loss(y_hat, y)l.backward()optimizer.step()with torch.no_grad():metric.add(l * X.shape[0], d2l.accuracy(y_hat, y), X.shape[0])timer.stop()train_l = metric[0] / metric[2]train_acc = metric[1] / metric[2]if (i + 1) % (num_batches // 5) == 0 or i == num_batches - 1:animator.add(epoch + (i + 1) / num_batches,(train_l, train_acc, None))test_acc = evaluate_accuracy_gpu(net, test_iter)animator.add(epoch + 1, (None, None, test_acc))print(f'loss {train_l:.3f}, train acc {train_acc:.3f}, 'f'test acc {test_acc:.3f}')print(f'{metric[2] * num_epochs / timer.sum():.1f} examples/sec 'f'on {str(device)}')

解决方法

在Animator类的add函数中,将最后一行的:

display.clear_output(wait=True)

改为:

display.clear_output(wait=False)

这是为了不用等图像内容刷新就显示。解决显示图像一闪而过的问题。

在train_ch6函数里,在最后两行print函数前,加入:

display.clear_output(wait=False)

这是为了解决最终输出会有两张图的问题。

效果

动态图正常显示。
这个方法只是解决了pycharm的问题,如果在浏览器中使用jupyter则会出现图像闪的问题。所以,为了避免和其他部分冲突,可以自己定义新函数,不修改d2l库代码。

pycharm jupyter中图像正常显示不会一闪而过

http://www.lryc.cn/news/620590.html

相关文章:

  • 【LeetCode 热题 100】295. 数据流的中位数——最大堆和最小堆
  • 基于Django的福建省旅游数据分析与可视化系统【城市可换】
  • AI 编程实践:用 Trae 快速开发 HTML 贪吃蛇游戏
  • 【经验分享】如何在Vscode的Jupyter Notebook中设置默认显示行号
  • vscode的wsl环境,ESP32驱动0.96寸oled屏幕
  • 【面板数据】各省及市省级非物质文化遗产数据合集(2005-2024年)
  • 【JavaEE】多线程 -- 初识线程
  • Java应用快速部署Tomcat指南
  • **超融合架构中的发散创新:探索现代编程语言的挑战与机遇**一、引言随着数字化时代的快速发展,超融合架构已成为IT领域的一种重要趋势
  • ts概念讲解
  • 网络原理-HTTP
  • 一致性哈希Consistent Hashing
  • 【代码随想录day 20】 力扣 669. 修剪二叉搜索树
  • 力扣-64.最小路径和
  • 玩转Docker | 使用Docker部署JSON格式化工具ZJSON
  • iOS Sqlite3
  • 磁盘瓶颈现形记 - iostat让I/O压力无所遁形
  • 「iOS」————设计架构
  • iOS 26 一键登录失效:三大运营商 SDK 无法正常获取手机号
  • iOS性能监控新方法多版本对比与趋势分析实战指南
  • iOS混淆工具有哪些?游戏 App 防护下的混淆与加固全攻略
  • 网络通信---Axios
  • iOS App TestFlight 上架全流程案例,从 0 到 1 完成内测分发
  • Docker 部署:Web SSH、RDP、VNC 多协议全能远程管理工具
  • 零基础数据结构与算法——第七章:算法实践与工程应用-搜索引擎
  • 洗浴中心泡池水过滤系统原理深度解析与工程实践
  • 数智先锋 | 告别运维黑盒!豪鹏科技×Bonree ONE构建全栈智能可观测体系
  • 【网络】TCP/UDP总结复盘
  • Ollama如何分别使用2张H100GPU和4张A100部署GPT-OSS-120B全指南:硬件配置与负载均衡实战
  • PostgreSQL——触发器