如何使用 PyTorch 中的单个全连接层将输入直接连接到输出?

How to connect the input to the output directly using single fully connected layer in PyTorch?

我是深度学习和 cnn 的新手,正在尝试使用 PyTorch 网站上的 CIFAR10 教程代码熟悉该领域。因此,在该代码中,我正在玩 removing/adding 层以更好地理解它们的效果,并且我尝试仅使用单个图像将输入(这是具有 4 个图像的批次的初始数据)直接连接到输出全连接层。我知道这没有多大意义,但我这样做只是为了实验。所以,当我尝试这样做时,我遇到了一些错误,如下所示:

首先,这是代码片段:

########################################################################
# 2. Define a Convolution Neural Network
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# Copy the neural network from the Neural Networks section before and modify it to
# take 3-channel images (instead of 1-channel images as it was defined).

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(768 * 4 * 4, 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, 768 * 4 * 4)
        #x = F.relu(self.fc1(x))
        #x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x


net = Net()

#######################################################################
# 3. Define a Loss function and optimizer
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# Let's use a Classification Cross-Entropy loss and SGD with momentum.

import torch.optim as optim

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

########################################################################
# 4. Train the network
# ^^^^^^^^^^^^^^^^^^^^
#
# This is when things start to get interesting.
# We simply have to loop over our data iterator, and feed the inputs to the
# network and optimize.

for epoch in range(4):  # loop over the dataset multiple times

    running_loss = 0.0
    for i, data in enumerate(trainloader, 0):
        # get the inputs
        inputs, labels = data

        # zero the parameter gradients
        optimizer.zero_grad()

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

        # print statistics
        running_loss += loss.item()
        if i % 2000 == 1999:    # print every 2000 mini-batches
            print('[%d, %5d] loss: %.3f' %
                  (epoch + 1, i + 1, running_loss / 2000))
            running_loss = 0.0

print('Finished Training')

因此,当我 运行 代码时,出现以下错误:

Traceback (most recent call last):
      File "C:\Users\Andrey\Desktop\Machine_learning_Danila\Homework 3\cifar10_tutorial1.py", line 180, in <module>
        loss = criterion(outputs, labels)
      File "C:\Program Files\Python36\lib\site-packages\torch\nn\modules\module.py", line 477, in __call__
        result = self.forward(*input, **kwargs)
      File "C:\Program Files\Python36\lib\site-packages\torch\nn\modules\loss.py", line 862, in forward
        ignore_index=self.ignore_index, reduction=self.reduction)
      File "C:\Program Files\Python36\lib\site-packages\torch\nn\functional.py", line 1550, in cross_entropy
        return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction)
      File "C:\Program Files\Python36\lib\site-packages\torch\nn\functional.py", line 1405, in nll_loss
        .format(input.size(0), target.size(0)))
    ValueError: Expected input batch_size (1) to match target batch_size (4).

我试图检查 x 的长度,结果发现它最初是 4,但在

行之后变为 1

x = x.view(-1, 768 * 4 * 4)

我认为我的数字是正确的,但似乎我只有 1 个张量而不是我应该拥有的 4 个,我觉得这就是导致该错误的原因。 我想知道,为什么会这样,解决这个问题的最佳方法是什么? 另外,在这种情况下,nn.Linear(全连接层)的输出维度输出的最佳数量是多少?

你修改的代码有两个明显的错误(来自PyTorch网页的官方代码)。首先,

torch.nn.Linear(in_features, out_features)

是正确的语法。但是,您将 768 * 4 * 4 作为 in_features 传递。这是一张CIFAR10图像(32*32*3 = 3072)中实际神经元(像素)数量的4倍。

第二个错误与第一个错误有关。当您准备 inputs 张量时,

# forward + backward + optimize;
# `inputs` should be a tensor of shape [batch_size, input_shape]
        outputs = net(inputs)

您应该将其作为形状为 [batch_size, input_size] 的张量传递,根据您的要求,它是 [4, 3072],因为您要使用 4 的批量大小。这是您应该提供批量的地方尺寸;不在 nn.Linear 中,这是您当前正在做的事情,这是导致错误的原因。

最后,您还应该修复 forward 方法中的行。更改以下行

x = x.view(-1, 768 * 4 * 4)   

x = x.view(-1, 32*32*3)

修复这些错误应该会修复您的错误。


话虽如此,我不确定这在概念意义上是否真的有效。因为这是一个简单的线性变换(即没有任何非线性的仿射变换)。在这个 3072 维 space(流形)中,数据点(对应于 CIFAR10 中的图像)很可能不是线性可分的。因此,准确性将非常差。因此,建议至少添加一个具有非线性的隐藏层,例如 ReLU。