Pytorch 学习(2):神经网络及训练一个分类器(cifar10_tutorial的网络结构图)

版权声明:王家林大咖2018年新书《SPARK大数据商业实战三部曲》清华大学出版,清华大学出版社官方旗舰店(天猫)https://qhdx.tmall.com/?spm=a220o.1000855.1997427721.d4918089.4b2a2e5dT6bUsM https://blog.csdn.net/duan_zhihua/article/details/81582891

Pytorch 学习(2):神经网络及训练一个分类器(cifar10_tutorial的网络结构图)

本文代码来自Pytorch官网入门教程,相关内容可以从Pytorch官网学习。

cifar10_tutorial的网络结构图:

neural_networks_tutorial.py

# -*- coding: utf-8 -*-
"""
神经网络
===============

神经网络可以使用 ``torch.nn`` 包构建.

``autograd`` 实现了反向传播功能, 但是直接用来写深度学习的代码在很多情况下还是稍显复杂, 
``torch.nn`` 是专门为神经网络设计的模块化接口. ``nn`` 构建于 ``Autograd`` 之上, 可用来定义和运行神经网络.
``nn.Module`` 是 ``nn`` 中最重要的类, 可把它看成是一个网络的封装, 包含网络各层定义以及 ``forward`` 方法, 调用 ``forward(input)`` 方法, 可返回前向传播的结果.

例如, 看看这个分类数字图像的网络:

.. figure:: /_static/img/mnist.png
   :alt: convnet

   convnet

这是一个基础的前向传播(feed-forward)网络: 接收输入, 经过层层传递运算, 得到输出.

一个典型的神经网络训练过程如下:

- 定义具有一些可学习参数(或权重)的神经网络
- 迭代输入数据集
- 通过网络处理输入
- 计算损失(输出的预测值与实际值之间的距离)
- 将梯度传播回网络
- 更新网络的权重, 通常使用一个简单的更新规则:
  ``weight = weight - learning_rate * gradient``

定义网络
------------------

让我们来定义一个网络:
"""
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F


class Net(nn.Module):

    def __init__(self):
        super(Net, self).__init__()
        # 卷积层 '1'表示输入图片为单通道, '6'表示输出通道数, '5'表示卷积核为5*5
        # 核心
        self.conv1 = nn.Conv2d(1, 6, 5)
        self.conv2 = nn.Conv2d(6, 16, 5)
        # 仿射层/全连接层: y = Wx + b
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        #在由多个输入平面组成的输入信号上应用2D最大池化.
        # (2, 2) 代表的是池化操作的步幅
        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
        # 如果大小是正方形, 则只能指定一个数字
        x = F.max_pool2d(F.relu(self.conv2(x)), 2)
        x = x.view(-1, self.num_flat_features(x))
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

    def num_flat_features(self, x):
        size = x.size()[1:]  # 除批量维度外的所有维度
        num_features = 1
        for s in size:
            num_features *= s
        return num_features


net = Net()
print(net)

########################################################################
#你只要在 ``nn.Module`` 的子类中定义了 ``forward`` 函数, ``backward`` 函数就会自动被实现(利用 ``autograd`` ).
#在 ``forward`` 函数中可使用任何 Tensor 支持的操作.
#
#
# 网络的可学习参数通过 ``net.parameters()`` 返回, ``net.named_parameters`` 可同时返回学习的参数以及名称.

params = list(net.parameters())
print(len(params))
print(params[0].size())  # conv1的weight

########################################################################
# 向前的输入是一个 ``autograd.Variable``, 输出也是如此.
# 注意: 这个网络(LeNet)的预期输入大小是 32x32, 使用这个网上 MNIST 数据集, 请将数据集中的图像调整为 32x32.

input = Variable(torch.randn(1, 1, 32, 32))
out = net(input)
print(out)

########################################################################
# 将网络中所有参数的梯度清零.
net.zero_grad()
out.backward(torch.randn(1, 10))

########################################################################
# .. note::
#
#    ``torch.nn`` 只支持小批量(mini-batches), 不支持一次输入一个样本, 即一次必须是一个 batch.
#
#    例如, ``nn.Conv2d`` 的输入必须是 4 维的, 形如 ``nSamples x nChannels x Height x Width``.
#
#    如果你只想输入一个样本, 需要使用 ``input.unsqueeze(0)`` 将 batch_size 设置为 1.
#
# 在继续之前, 让我们回顾一下迄今为止所有见过的类.
#
# **概括:**
#   -  ``torch.Tensor`` - 一个 *多维数组*.
#   -  ``autograd.Variable`` - *包装张量并记录应用于其上的历史操作*.
#      具有和 ``Tensor`` 相同的 API ,还有一些补充, 如 ``backward()``.
#      另外 *拥有张量的梯度*.
#   -  ``nn.Module`` - 神经网络模块. *方便的方式封装参数*,
#      帮助将其移动到GPU, 导出, 加载等. 
#   -  ``nn.Parameter`` - 一种变量, 当被指定为 ``Model`` 的属性时, 它会自动注册为一个参数.
#   -  ``autograd.Function`` - 实现 *autograd 操作的向前和向后定义* .
#      每个 ``Variable`` 操作, 至少创建一个 ``Function`` 节点,
#      连接到创建 ``Variable`` 的函数, 并 *编码它的历史*.
#
# **在这一点上, 我们涵盖:**
#   -  定义一个神经网络
#   -  处理输入并反向传播
#
# **还剩下:**
#   -  计算损失函数
#   -  更新网络的权重
#
# 损失函数
# -------------
# 损失函数采用 (output,target) 输入对, 并计算预测输出结果与实际目标的距离. 
#
# 在 ``nn`` 包下有几种不同的 `损失函数 <http://pytorch.org/docs/nn.html#loss-functions>`_ .
# 一个简单的损失函数是: ``nn.MSELoss`` 计算输出和目标之间的均方误差
#
# 例如:

output = net(input)
target = Variable(torch.arange(1, 11))  # 一个虚拟的目标
criterion = nn.MSELoss()

loss = criterion(output, target)
print(loss)

########################################################################
# 现在, 如果你沿着 ``loss`` 反向传播的方向使用 ``.grad_fn`` 属性, 你将会看到一个如下所示的计算图:
#
# ::
#
#     input -> conv2d -> relu -> maxpool2d -> conv2d -> relu -> maxpool2d
#           -> view -> linear -> relu -> linear -> relu -> linear
#           -> MSELoss
#           -> loss
#
# 所以, 当我们调用 ``loss.backward()``, 整个图与损失是有区别的,
# 图中的所有变量都将用 ``.grad`` 梯度累加它们的变量.
#
# 为了说明, 让我们向后走几步:

print(loss.grad_fn)  # MSELoss
print(loss.grad_fn.next_functions[0][0])  # Linear
print(loss.grad_fn.next_functions[0][0].next_functions[0][0])  # ReLU

########################################################################
# 反向传播
# --------
# 为了反向传播误差, 我们所要做的就是 ``loss.backward()``.
# 你需要清除现有的梯度, 否则梯度会累加之前的梯度.
#
#
# 现在我们使用 ``loss.backward()``, 看看反向传播之前和之后 ``conv1`` 的梯度.


net.zero_grad()     # 把之前的梯度清零

print('conv1.bias.grad before backward')
print(net.conv1.bias.grad)

loss.backward()

print('conv1.bias.grad after backward')
print(net.conv1.bias.grad)

########################################################################
# 现在, 我们已经看到了如何使用损失函数.
#
# **稍后阅读:**
#
#   神经网络包包含各种模块和损失函数, 形成深度神经网络的构建模块. 完整的文件列表 `在这里 <http://pytorch.org/docs/nn>`_
#
# **接下来学习的唯一东西是:**
#
#   - 更新网络的权重
#
# 更新权重
# ------------------
# 实践中使用的最简单的更新规则是随机梯度下降( SGD ):
#
#      ``weight = weight - learning_rate * gradient``
#
# 我们可以使用简单的 python 代码来实现这个:
#
# .. code:: python
#
#     learning_rate = 0.01
#     for f in net.parameters():
#         f.data.sub_(f.grad.data * learning_rate)
#
# 然而, 当你使用神经网络时, 你需要使用各种不同的更新规则, 比如 SGD, Nesterov-SGD, Adam, RMSProp等.
# 为了实现这个功能, 我们建立了一个包: ``torch.optim`` 实现所有这些方法.
# 使用它非常的简单:

import torch.optim as optim

# 新建一个优化器, 指定要调整的参数和学习率
optimizer = optim.SGD(net.parameters(), lr = 0.01)

# 在训练过程中:
optimizer.zero_grad()   # 首先梯度清零(与 net.zero_grad() 效果一样)
output = net(input)
loss = criterion(output, target)
loss.backward()
optimizer.step()    # 更新参数


###############################################################
# .. Note::
#
#       观察如何使用手动设置梯度清零 ``optimizer.zero_grad()`` . 需要手动清零的原因在 `Backprop`_ 中已经说明了(梯度会累加之前的梯度).

cifar10_tutorial.py

# -*- coding: utf-8 -*-
"""
训练一个分类器
=====================

就是这个, 你已经看到了如何定义神经网络, 计算损失并更新网络的权重.

现在你可能会想,

数据呢?
----------------

一般来说, 当你不得不处理图像, 文本, 音频或者视频数据时,
你可以使用标准的 Python 包将数据加载到一个 numpy 数组中.
然后你可以将这个数组转换成一个 ``torch.*Tensor``.

-  对于图像, 会用到的包有 Pillow, OpenCV .
-  对于音频, 会用的包有 scipy 和 librosa.
-  对于文本, 原始 Python 或基于 Cython 的加载, 或者 NLTK 和 Spacy 都是有用的.


特别是对于 ``vision``, 我们已经创建了一个叫做 ``torchvision``, 其中有对普通数据集如
Imagenet, CIFAR10, MNIST 等和用于图像数据的转换器, 即 ``torchvision.datasets`` 和 ``torch.utils.data.DataLoader``.

这提供了巨大的便利, 避免了编写重复代码.

在本教程中, 我们将使用 CIFAR10 数据集.
它有: ‘airplane’, ‘automobile’, ‘bird’, ‘cat’, ‘deer’,‘dog’, ‘frog’, ‘horse’, ‘ship’, ‘truck’ 这些类别.
CIFAR10 中的图像大小为 3x32x32 , 即 32x32 像素的 3 通道彩色图像.

.. figure:: /_static/img/cifar10.png
   :alt: cifar10

   cifar10


训练一个图像分类器
----------------------------

我们将按顺序执行以下步骤:

1. 加载 CIFAR10 测试和训练数据集并规范化
   ``torchvision``
2. 定义一个卷积神经网络
3. 定义一个损失函数
4. 在训练数据上训练网络
5. 在测试数据上测试网络

1. 加载并规范化 CIFAR10
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

使用 ``torchvision``, 加载 CIFAR10 非常简单.
"""
import torch
import torchvision
import torchvision.transforms as transforms

########################################################################
# torchvision 数据集的输出是范围 [0, 1] 的 PILImage 图像. 我们将它们转换为归一化范围是[-1,1]的张量

transform = transforms.Compose(
    [transforms.ToTensor(),
     transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])

trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
                                        download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=4,
                                          shuffle=True, num_workers=2)

testset = torchvision.datasets.CIFAR10(root='./data', train=False,
                                       download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=4,
                                         shuffle=False, num_workers=2)

classes = ('plane', 'car', 'bird', 'cat',
           'deer', 'dog', 'frog', 'horse', 'ship', 'truck')

########################################################################
# 让我们展示一些训练图像, 只是为了好玩 (0.0).

import matplotlib.pyplot as plt
import numpy as np

# 定义函数来显示图像


def imshow(img):
    img = img / 2 + 0.5     # 非标准化
    npimg = img.numpy()
    plt.imshow(np.transpose(npimg, (1, 2, 0)))


# 得到一些随机的训练图像
dataiter = iter(trainloader)
images, labels = dataiter.next()

# 显示图像
imshow(torchvision.utils.make_grid(images))
# 输出类别
print(' '.join('%5s' % classes[labels[j]] for j in range(4)))


########################################################################
# 2. 定义一个卷积神经网络
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# 从神经网络部分复制神经网络, 并修改它以获取 3 通道图像(而不是定义的 1 通道图像).

from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F


class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(3, 6, 5)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = x.view(-1, 16 * 5 * 5)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x


net = Net()

########################################################################
# 3. 定义一个损失函数和优化器
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# 我们使用交叉熵损失函数( CrossEntropyLoss )和随机梯度下降( SGD )优化器.

import torch.optim as optim

criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)

########################################################################
# 4. 训练网络
# ^^^^^^^^^^^^^^^^^^^^
#
# 这是事情开始变得有趣的时候.
# 我们只需循环遍历数据迭代器, 并将输入提供给网络和优化器.

for epoch in range(2):  # 循环遍历数据集多次

    running_loss = 0.0
    for i, data in enumerate(trainloader, 0):
        # 得到输入数据
        inputs, labels = data

        # 包装数据
        inputs, labels = Variable(inputs), Variable(labels)

        # 梯度清零
        optimizer.zero_grad()

        # forward + backward + optimize
        outputs = net(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

        # 打印信息
        running_loss += loss.data[0]
        if i % 2000 == 1999:    # 每2000个小批量打印一次
            print('[%d, %5d] loss: %.3f' %
                  (epoch + 1, i + 1, running_loss / 2000))
            running_loss = 0.0

print('Finished Training')

########################################################################
# 5. 在测试数据上测试网络
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# 我们在训练数据集上训练了2遍网络, 但是我们需要检查网络是否学到了什么.
#
# 我们将通过预测神经网络输出的类标签来检查这个问题, 并根据实际情况进行检查.
# 如果预测是正确的, 我们将样本添加到正确预测的列表中.
#
# 好的, 第一步. 让我们显示测试集中的图像以便熟悉.

dataiter = iter(testloader)
images, labels = dataiter.next()

# 打印图像
imshow(torchvision.utils.make_grid(images))
print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))

########################################################################
# 好的, 现在让我们看看神经网络认为这些例子是什么:

outputs = net(Variable(images))

########################################################################
# 输出的是10个类别的能量.
# 一个类别的能量越高, 则可以理解为网络认为越多的图像是该类别的.
# 那么, 让我们得到最高能量的索引:
_, predicted = torch.max(outputs.data, 1)

print('Predicted: ', ' '.join('%5s' % classes[predicted[j]]
                              for j in range(4)))

########################################################################
# 结果看起来不错.
#
# 让我们看看网络如何在整个数据集上执行.

correct = 0
total = 0
for data in testloader:
    images, labels = data
    outputs = net(Variable(images))
    _, predicted = torch.max(outputs.data, 1)
    total += labels.size(0)
    correct += (predicted == labels).sum()

print('Accuracy of the network on the 10000 test images: %d %%' % (
    100 * correct / total))

########################################################################
# 训练的准确率远比随机猜测(准确率10%)好, 证明网络确实学到了东西. 
#
# 嗯, 我们来看看哪些类别表现良好, 哪些类别表现不佳:

class_correct = list(0. for i in range(10))
class_total = list(0. for i in range(10))
for data in testloader:
    images, labels = data
    outputs = net(Variable(images))
    _, predicted = torch.max(outputs.data, 1)
    c = (predicted == labels).squeeze()
    for i in range(4):
        label = labels[i]
        class_correct[label] += c[i]
        class_total[label] += 1


for i in range(10):
    print('Accuracy of %5s : %2d %%' % (
        classes[i], 100 * class_correct[i] / class_total[i]))

########################################################################
# 好的, 接下来呢?
#
# 我们如何在 GPU 上运行这些神经网络?
#
# 在 GPU 上训练
# ----------------
# 就像你如何将一个张量传递给GPU一样, 你将神经网络转移到GPU上. 这将递归遍历所有模块, 并将其参数和缓冲区转换为CUDA张量:
#
# .. code:: python
#
#     net.cuda()
#
#
# 请记住, 您必须将输入和目标每一步都发送到GPU:
#
# ::
#
#         inputs, labels = Variable(inputs.cuda()), Variable(labels.cuda())
#
# 如果发现在 GPU 上并没有比 CPU 提速很多, 实际上是因为网络比较小, GPU 没有完全发挥自己的真正实力.
#
# **练习:** 尝试增加网络的宽度(第一个 ``nn.Conv2d`` 的参数2和第二个 ``nn.Conv2d`` 的参数1 它们需要是相同的数字),
# 看看你得到什么样的加速.
#
# **目标达成**:
#
# - 深入了解PyTorch的张量库和神经网络.
# - 训练一个小的神经网络来分类图像.
#
# 在多个GPU上进行训练
# -------------------------
# 如果你希望使用所有 GPU 来看更多的 MASSIVE 加速, 请查看可选 :doc:`data_parallel_tutorial`.
#
# 我下一步去哪里?
# -------------------
#
# -  :doc:`训练神经网络玩电子游戏 </intermediate/reinforcement_q_learning>`
# -  `在 imagenet 上培训最先进的 ResNet 网络`
# -  `利用生成对抗网络训练人脸生成器`
# -  `使用 Recurrent LSTM 网络训练单词语言模型`
# -  `更多的例子`
# -  `更多教程`
# -  `在论坛上讨论 PyTorch`
# -  `与 Slack 上与其他用户聊天`
#
# .. _Train a state-of-the-art ResNet network on imagenet: https://github.com/pytorch/examples/tree/master/imagenet
# .. _Train a face generator using Generative Adversarial Networks: https://github.com/pytorch/examples/tree/master/dcgan
# .. _Train a word-level language model using Recurrent LSTM networks: https://github.com/pytorch/examples/tree/master/word_language_model
# .. _More examples: https://github.com/pytorch/examples
# .. _More tutorials: https://github.com/pytorch/tutorials
# .. _Discuss PyTorch on the Forums: https://discuss.pytorch.org/
# .. _Chat with other users on Slack: http://pytorch.slack.com/messages/beginner/

可能遇到的问题:

1,提示BrokenPipeError: [Errno 32] Broken pipe

将cifar10_tutorial.py改代码: num_workers=2 ====》 num_workers=0 解决。
D:\PycharmProjects\Pytorch_2018_test>python cifar10_tutorial.py
Files already downloaded and verified
Files already downloaded and verified
Files already downloaded and verified
Files already downloaded and verified
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "G:\ProgramData\Anaconda3\lib\multiprocessing\spawn.py", line 105, in spawn_main
    exitcode = _main(fd)
  File "G:\ProgramData\Anaconda3\lib\multiprocessing\spawn.py", line 114, in _main
    prepare(preparation_data)
  File "G:\ProgramData\Anaconda3\lib\multiprocessing\spawn.py", line 225, in prepare
    _fixup_main_from_path(data['init_main_from_path'])
  File "G:\ProgramData\Anaconda3\lib\multiprocessing\spawn.py", line 277, in _fixup_main_from_path
    run_name="__mp_main__")
  File "G:\ProgramData\Anaconda3\lib\runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
  File "G:\ProgramData\Anaconda3\lib\runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "G:\ProgramData\Anaconda3\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "D:\PycharmProjects\Pytorch_2018_test\cifar10_tutorial.py", line 94, in <module>
    dataiter = iter(trainloader)
  File "G:\ProgramData\Anaconda3\lib\site-packages\torch\utils\data\dataloader.py", line 451, in __iter__
    return _DataLoaderIter(self)
  File "G:\ProgramData\Anaconda3\lib\site-packages\torch\utils\data\dataloader.py", line 239, in __init__
    w.start()
  File "G:\ProgramData\Anaconda3\lib\multiprocessing\process.py", line 105, in start
    self._popen = self._Popen(self)
  File "G:\ProgramData\Anaconda3\lib\multiprocessing\context.py", line 223, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "G:\ProgramData\Anaconda3\lib\multiprocessing\context.py", line 322, in _Popen
    return Popen(process_obj)
  File "G:\ProgramData\Anaconda3\lib\multiprocessing\popen_spawn_win32.py", line 33, in __init__
    prep_data = spawn.get_preparation_data(process_obj._name)
  File "G:\ProgramData\Anaconda3\lib\multiprocessing\spawn.py", line 143, in get_preparation_data
    _check_not_importing_main()
  File "G:\ProgramData\Anaconda3\lib\multiprocessing\spawn.py", line 136, in _check_not_importing_main
    is not going to be frozen to produce an executable.''')
RuntimeError:
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.
Traceback (most recent call last):
  File "cifar10_tutorial.py", line 94, in <module>
    dataiter = iter(trainloader)
  File "G:\ProgramData\Anaconda3\lib\site-packages\torch\utils\data\dataloader.py", line 451, in __iter__
    return _DataLoaderIter(self)
  File "G:\ProgramData\Anaconda3\lib\site-packages\torch\utils\data\dataloader.py", line 239, in __init__
    w.start()
  File "G:\ProgramData\Anaconda3\lib\multiprocessing\process.py", line 105, in start
    self._popen = self._Popen(self)
  File "G:\ProgramData\Anaconda3\lib\multiprocessing\context.py", line 223, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "G:\ProgramData\Anaconda3\lib\multiprocessing\context.py", line 322, in _Popen
    return Popen(process_obj)
  File "G:\ProgramData\Anaconda3\lib\multiprocessing\popen_spawn_win32.py", line 65, in __init__
    reduction.dump(process_obj, to_child)
  File "G:\ProgramData\Anaconda3\lib\multiprocessing\reduction.py", line 60, in dump
    ForkingPickler(file, protocol).dump(obj)
BrokenPipeError: [Errno 32] Broken pipe

2,提示input and target shapes do not match: input [1 x 10], target [10]

neural_networks_tutorial.py改代码: target = Variable(torch.arange(1, 11).view(1,10)) 解决。

Traceback (most recent call last):
  File "D:/PycharmProjects/Pytorch_2018_test/neural_networks_tutorial.py", line 68, in <module>
    loss = criterion(output, target)
  File "G:\ProgramData\Anaconda3\lib\site-packages\torch\nn\modules\module.py", line 491, in __call__
    result = self.forward(*input, **kwargs)
  File "G:\ProgramData\Anaconda3\lib\site-packages\torch\nn\modules\loss.py", line 372, in forward
    return F.mse_loss(input, target, size_average=self.size_average, reduce=self.reduce)
  File "G:\ProgramData\Anaconda3\lib\site-packages\torch\nn\functional.py", line 1569, in mse_loss
    input, target, size_average, reduce)
  File "G:\ProgramData\Anaconda3\lib\site-packages\torch\nn\functional.py", line 1537, in _pointwise_loss
    return lambd_optimized(input, target, size_average, reduce)
RuntimeError: input and target shapes do not match: input [1 x 10], target [10] at c:\programdata\miniconda3\conda-bld\pytorch_1524543037166\work\aten\src\thnn\generic/MSECriterion.c:13

Process finished with exit code 1

3,提示 value cannot be converted to type uint8_t without overflow。

cifar10_tutorial.py改代码:暂时注释掉打印代码。

Traceback (most recent call last):
  File "D:/PycharmProjects/Pytorch_2018_test/cifar10_tutorial.py", line 251, in <module>
    classes[i], 100 * class_correct[i] / class_total[i]))
RuntimeError: value cannot be converted to type uint8_t without overflow: 1000.000000

猜你喜欢

转载自blog.csdn.net/duan_zhihua/article/details/81582891