我在pytorch上遇到此错误“RuntimeError:invalid argument 2:size'[ - 1 x 400]”

问题描述 投票:1回答:3

任何人都可以帮我解决这个错误吗?

RuntimeError:无效参数2:对于在/Users/soumith/miniconda2/conda-bld/pytorch_1503975723910/work/torch/lib/TH/THStorage.c:37中输入1597248个元素,大小'[ - 1 x 400]'无效

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()

import torch.optim as optim

criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
for epoch in range(2):  # loop over the dataset multiple times

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

        # wrap them in Variable
        inputs, labels = Variable(inputs), Variable(labels)

        # zero the parameter gradients
        optimizer.zero_grad()

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

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

print('Finished Training')
python machine-learning torch pytorch image-size
3个回答
1
投票

当我缩放图像大小时,错误停止发生。

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

0
投票

您的问题是图像的大小不是32 * 32。要解决这个问题,您需要根据网络的输入大小计算self.fc1的输入大小。


0
投票

计算输入大小应解决它而不缩放图像。其公式为output_size =((image_size + 2 * padding -filter)/ stride + 1)

© www.soinside.com 2019 - 2024. All rights reserved.