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

2024-03-28 09:54:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个新的深度学习和cnn,并试图通过Pythorch网站上的CIFAR10教程代码来熟悉这个领域。因此,在那段代码中,为了更好地理解它们的效果,我尝试着只使用一个完全连接的层将输入(这是一批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')

因此,当我运行代码时,我得到以下错误:

^{pr2}$

我试着检查x的长度,结果是,最初是4,但在这条线之后变成了1

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

我认为我的数字是正确的,但是看起来我只有1个张量,而不是我应该有的4个张量,我觉得这就是导致错误的原因。 我在想,为什么会这样?最好的解决方法是什么? 另外,在nn.线性(完全连接层)在这种情况下?在


Tags: andtheto代码selfas错误nn
1条回答
网友
1楼 · 发布于 2024-03-28 09:54:28

修改后的代码中有两个明显的错误(来自Pythorch网页的官方错误)。首先

torch.nn.Linear(in_features, out_features)

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

第二个bug与第一个bug相关。当你准备你的inputs张量时

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

您应该将其作为形状[batch_size, input_size]的张量传递,根据您的要求,它是{},因为您希望使用4的批大小。这是您应该提供批处理维度的地方;而不是在nn.Linear中,而这正是您当前所做的并导致错误的地方。在

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

^{pr2}$

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

修复这些错误应该可以修复您的错误。在


尽管如此,从概念上讲,我不确定这是否真的有效。因为这是一个简单的线性变换(即没有任何非线性的仿射变换)。在这个3072维空间(流形)中,数据点(对应于CIFAR10中的图像)很可能不是线性可分离的。因此,准确度将大大降低。因此,建议至少添加具有非线性的隐藏层,例如ReLU。在

相关问题 更多 >