动手学深度学习d2l.Animator无法在PyCharm中显示动态图片的解决方案

这篇具有很好参考价值的文章主要介绍了动手学深度学习d2l.Animator无法在PyCharm中显示动态图片的解决方案。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

from d2l import torch as d2l

一、问题描述

运行d2l的训练函数,仅在控制台输出以下内容,无法显示动态图片(训练监控)

<Figure size 350x250 with 1 Axes>
<Figure size 350x250 with 1 Axes>
<Figure size 350x250 with 1 Axes>
<Figure size 350x250 with 1 Axes>
<Figure size 350x250 with 1 Axes>
<Figure size 350x250 with 1 Axes>

二、解决方案

修改d2l.Animatoradd函数,以下分别是修改前的代码及修改后的代码:

def add(self, x, y):
    # Add multiple data points into the figure
    if not hasattr(y, "__len__"):
        y = [y]
    n = len(y)
    if not hasattr(x, "__len__"):
        x = [x] * n
    if 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)
def add(self, x, y):
    # Add multiple data points into the figure
    if not hasattr(y, "__len__"):
        y = [y]
    n = len(y)
    if not hasattr(x, "__len__"):
        x = [x] * n
    if 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)
    # 通过以下两行代码实现了在PyCharm中显示动图
    plt.draw()
    plt.pause(interval=0.001)
    display.clear_output(wait=True)

同时,在使用相关函数时,添加如下一行代码d2l.plt.show(),如下:

d2l.train_ch13(net, train_iter, test_iter, loss, trainer, num_epochs, devices)
d2l.plt.show()

三、实现效果

动手学深度学习d2l.Animator无法在PyCharm中显示动态图片的解决方案,深度学习,pycharm,人工智能

附:使用控制台打印输出训练监控信息,而不通过动态图的方式

重写训练函数,以d2l.train_ch13为例,以下分别是修改前的代码及修改后的代码:

def train_ch13(net, train_iter, test_iter, loss, trainer, num_epochs,
               devices=d2l.try_all_gpus()):
    """Train a model with multiple GPUs (defined in Chapter 13).

    Defined in :numref:`sec_image_augmentation`"""
    timer, num_batches = d2l.Timer(), len(train_iter)
    animator = d2l.Animator(xlabel='epoch', xlim=[1, num_epochs], ylim=[0, 1],
                            legend=['train loss', 'train acc', 'test acc'])
    net = nn.DataParallel(net, device_ids=devices).to(devices[0])
    for epoch in range(num_epochs):
        # Sum of training loss, sum of training accuracy, no. of examples,
        # no. of predictions
        metric = d2l.Accumulator(4)
        for i, (features, labels) in enumerate(train_iter):
            timer.start()
            l, acc = train_batch_ch13(
                net, features, labels, loss, trainer, devices)
            metric.add(l, acc, labels.shape[0], labels.numel())
            timer.stop()
            if (i + 1) % (num_batches // 5) == 0 or i == num_batches - 1:
                animator.add(epoch + (i + 1) / num_batches,
                             (metric[0] / metric[2], metric[1] / metric[3],
                              None))
        test_acc = d2l.evaluate_accuracy_gpu(net, test_iter)
        animator.add(epoch + 1, (None, None, test_acc))
    print(f'loss {metric[0] / metric[2]:.3f}, train acc '
          f'{metric[1] / metric[3]:.3f}, test acc {test_acc:.3f}')
    print(f'{metric[2] * num_epochs / timer.sum():.1f} examples/sec on '
          f'{str(devices)}')
def train_ch13(net, train_iter, test_iter, loss, trainer, num_epochs, devices=d2l.try_all_gpus()):
    """使用多GPU训练模型"""
    timer, num_batches = d2l.Timer(), len(train_iter)
    net = nn.DataParallel(net, device_ids=devices).to(devices[0])
    for epoch in range(num_epochs):
        # 训练损失、训练准确度、实例数
        metric = d2l.Accumulator(3)
        for i, (features, labels) in enumerate(train_iter):
            timer.start()
            l, acc = train_batch_ch13(net, features, labels, loss, trainer, devices)
            metric.add(l, acc, labels.shape[0])  # labels.shape[0] == labels.numel()
            timer.stop()
            if (i + 1) % (num_batches // 5) == 0 and not (i + 1) == num_batches:
                print(
                    f'epoch {epoch + 1}, iter {i + 1}: train loss {metric[0] / metric[2]:.3f}, train acc {metric[1] / metric[2]:.3f}')
        test_acc = d2l.evaluate_accuracy_gpu(net, test_iter)
        print(
            f'epoch {epoch + 1}: train loss {metric[0] / metric[2]:.3f}, train acc {metric[1] / metric[2]:.3f}, test acc {test_acc:.3f}')
    print(f'{metric[2] * num_epochs / timer.sum():.1f} examples/sec on {str(devices)}')

修改后的训练代码运行效果如下图所示:

动手学深度学习d2l.Animator无法在PyCharm中显示动态图片的解决方案,深度学习,pycharm,人工智能文章来源地址https://www.toymoban.com/news/detail-696906.html

epoch 1, iter 6: train loss 2.580, train acc 0.484
epoch 1, iter 12: train loss 1.871, train acc 0.560
epoch 1, iter 18: train loss 1.390, train acc 0.653
epoch 1, iter 24: train loss 1.111, train acc 0.709
epoch 1, iter 30: train loss 0.936, train acc 0.748
epoch 1: train loss 0.909, train acc 0.754, test acc 0.894
epoch 2, iter 6: train loss 0.257, train acc 0.909
epoch 2, iter 12: train loss 0.266, train acc 0.898
epoch 2, iter 18: train loss 0.255, train acc 0.902
epoch 2, iter 24: train loss 0.257, train acc 0.906
epoch 2, iter 30: train loss 0.252, train acc 0.908
epoch 2: train loss 0.247, train acc 0.910, test acc 0.911
epoch 3, iter 6: train loss 0.207, train acc 0.922
epoch 3, iter 12: train loss 0.191, train acc 0.923
epoch 3, iter 18: train loss 0.204, train acc 0.914
epoch 3, iter 24: train loss 0.212, train acc 0.912
epoch 3, iter 30: train loss 0.211, train acc 0.914
epoch 3: train loss 0.209, train acc 0.915, test acc 0.901
epoch 4, iter 6: train loss 0.192, train acc 0.930
epoch 4, iter 12: train loss 0.213, train acc 0.924
epoch 4, iter 18: train loss 0.222, train acc 0.918
epoch 4, iter 24: train loss 0.212, train acc 0.921
epoch 4, iter 30: train loss 0.215, train acc 0.920
epoch 4: train loss 0.214, train acc 0.919, test acc 0.914
epoch 5, iter 6: train loss 0.191, train acc 0.938
epoch 5, iter 12: train loss 0.188, train acc 0.935
epoch 5, iter 18: train loss 0.193, train acc 0.931
epoch 5, iter 24: train loss 0.191, train acc 0.930
epoch 5, iter 30: train loss 0.196, train acc 0.925
epoch 5: train loss 0.197, train acc 0.924, test acc 0.936
176.0 examples/sec on [device(type='cuda', index=0)]

到了这里,关于动手学深度学习d2l.Animator无法在PyCharm中显示动态图片的解决方案的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 卷积神经网络——中篇【深度学习】【PyTorch】【d2l】

    5.5.1、理论部分 两个⌈ 卷积块 ⌋ 每个卷积块中的基本单元是一个⌈ 卷积层 ⌋、一个 ⌈ sigmoid激活函数 ⌋和 ⌈ 平均汇聚层 ⌋ 三个⌈ 全连接层密集块 ⌋ 早期神经网络,先使用卷积层学习图片空间信息,然后全连接层转换到类别空间。 5.5.2、代码实现 定义一个 Sequential块

    2024年02月11日
    浏览(41)
  • 线性神经网路——线性回归随笔【深度学习】【PyTorch】【d2l】

    线性回归是显式解,深度学习中绝大多数遇到的都是隐式解。 3.1.1、PyTorch 从零实现线性回归 生成数据集及标签 d2l.plt.scatter(,,) ,使用d2l库中的绘图函数来创建散点图。 这个函数接受三个参数: features[:,1].detach().numpy() 是一个二维张量features的切片操作,选择了所有行的第二

    2024年02月15日
    浏览(43)
  • 李沐深度学习环境安装(包括pytorch和d2l)

    进入Anaconda官网下载:https://www.anaconda.com/distribution/ 安装细节不在这赘述,和一般软件相同。如下图注意点 最后检测是否安装成功,打开cmd命令行输入 conda --version ,如下图显示版本即为安装成功 2.1 切换到国内镜像源,分别输入以下4行代码: 2.2 创建pytorch环境 创建pytorch环境

    2024年02月13日
    浏览(26)
  • Pycharm安装jupyter和d2l

    jupyter是d2l的依赖库,没有它就用不了d2l pycharm中端输入 pip install jupyter 安装若失败则: 若网速过慢,则更改镜像源再下载: 若还是下载失败则是由于电脑有外网APN,也就是说是科学上网的原因导致的: 关掉后再输入命令下载即可。 先下载whl: 链接 点击下载地址下载 再找项

    2024年02月06日
    浏览(30)
  • 关于安装李沐深度学习d2l包报错的解决办法(保姆教程)

    因为换了新电脑,所以环境都是从零开始配置,但是在安装李沐深度学习里常用的d2l包的时候,确实频繁报错。 这里总结一下我的报错原因,希望大家在遇到bug的时候能够从容面对。 在安装深度学习框架之前,请先检查你的计算机上是否有可用的GPU。 例如,你可以查看计算

    2024年02月03日
    浏览(38)
  • d2l学习——第一章Introduction

    使用d2l库,安装如下: 如果安装不上d2l可以用下面的方法: pip install git+https://github.com/d2l-ai/d2l-en 就和统计学习方法书中说的一样,机器学习也可以分为几个核心要义, Data, Models, Objective Functions, Optimization Algorithms , 其中: Data: 用来学习的数据 Model: 如何转换/translate数据的

    2024年02月08日
    浏览(35)
  • d2l_第八章学习_现代卷积神经网络

    参考: d2l 研究人员认为: 更大更干净的 数据集 或是稍加改进的特征提取方法,比任何学习算法带来的进步大得多。 认为特征本身应该被学习,即卷积核参数应该是可学习的。 创新点在于GPU与更深的网络,使用ReLU激活函数,Dropout层。 可参考: AlexNet https://blog.csdn.net/qq_4

    2024年02月11日
    浏览(32)
  • D2L学习记录-10-词嵌入word2vec

    《动手学深度学习 Pytorch 第1版》第10章 自然语言处理 第1、2、3 和 4节 (词嵌入) 词向量:自然语言中,词是表义的基本单元。词向量是用来表示词的向量。 词嵌入 (word embedding):将词映射为实数域向量的技术称为词嵌入。 词嵌入出现的原因:由于 one-hot 编码的词向量不能准确

    2024年02月14日
    浏览(31)
  • d2l包安装教程

    目录 一、下载d2l包 1、错误的安装方法 2、正确的安装方法 二、可能会遇到的问题 1、网络超时导致下载中断 2、windows powershell激活虚拟环境时报错        直接按照教程安装 — 动手学深度学习 2.0.0 documentation运行命令 pip install d2l==0.17.6 安装会比较慢,很大可能会因为网络

    2024年01月19日
    浏览(34)
  • d2l 线性回归的简洁实现

    上一节 张量:数据存储、线性代数;自动微分:计算梯度 开源框架,可自动化基于梯度的学习算法中重复性的工作 数据迭代器、损失函数、优化器、神经网络层 使用深度学习框架简洁实现 线性回归模型 生成数据集 标准深度学习模型,使用框架预定义好的层 关注用哪些层

    2024年02月14日
    浏览(30)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包