首页 > 解决方案 > ValueError:在昏暗 2 处预期长度为 0 的序列(得到 1)

问题描述

我最近开始了一个关于 Python 神经网络的教程。我正在使用 CNN 进行猫/狗分类任务。然而,即使我认为我已经完全按照教程告诉我的去做了,我还是以某种方式结束了一个模糊的错误。

是教程。我相信他使用的是 Python 3.7,我使用的是 Python 3.9(64 位)。

错误:ValueError:dim 2 处长度为 0 的预期序列(得到 1)
代码行:y = torch.Tensor([i[1] for i in training_data])

听起来我在准备训练数据时可能犯了一个错误,但我不确定。这是代码:

class DogsVSCats:
    IMG_SIZE = 50
    CATS = '[Path]'
    DOGS = '[Path]'

    LABELS = {CATS: 0, DOGS: 1}

    training_data = []

    catcount = 0
    dogcount = 0

    def make_training_data(self):
        for label in self.LABELS:
            print label

            for f in tqdm(os.listdir(label)):
                try:
                    path = os.path.join(label, f)
                    img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
                    img = cv2.resize(img, (self.IMG_SIZE,
                            self.IMG_SIZE))

                    self.training_data.append([np.array(img), np.eye(2,
                            self.LABELS[label])])

                    if label == self.CATS:
                        self.catcount += 1
                    elif label == self.DOGS:

                        self.dogcount += 1
                except Exception, e:

                    pass

            np.random.shuffle(self.training_data)
            np.save('training_data.npy', self.training_data)

            print ('Cats: ', self.catcount)
            print ('Dogs: ', self.dogcount)

    if REBUILD_DATA:
        dogsvcats = DogsVSCats()
        dogsvcats.make_training_data()


print 'Nothing found!!'

这一切似乎都像教程中那样工作,没有错误,并且每个类别显示相同数量的图片。这也是有问题的行:

class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(1, 32, 5)
        self.conv2 = nn.Conv2d(32, 64, 5)
        self.conv3 = nn.Conv2d(64, 128, 5)

        x = torch.randn(50, 50).view(-1, 1, 50, 50)
        self._to_linear = None
        self.convs(x)

        self.fc1 = nn.Linear(self._to_linear, 512)
        self.fc2 = nn.Linear(512, 2)

    def convs(self, x):
        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
        x = F.max_pool2d(F.relu(self.conv2(x)), (2, 2))
        x = F.max_pool2d(F.relu(self.conv3(x)), (2, 2))

        if self._to_linear is None:
            self._to_linear = x[0].shape[0] * x[0].shape[1] * x[0].shape[2]
        return x

    def forward(self, x):
        x = self.convs(x)
        x = x.view(-1, self._to_linear)
        x = F.relu(self.fc1(x))
        x = self.fc2(x)

        return F.softmax(x, dim = 1)

net = Net()

optimizer = optim.Adam(net.parameters(), lr = 1e-3)
loss_function = nn.MSELoss()

X = torch.Tensor([i[0] for i in training_data]).view(-1, 50, 50)
X = X / 255.0
y = torch.Tensor([i[1] for i in training_data]) !!!Error Line!!!

VAL_PCT = 0.1
val_size = int(len(X) * VAL_PCT)

train_X = X[:-val_size]
train_y = y[:-val_size]

test_X = X[-val_size:]
test_y = y[-val_size:]

print(val_size)

标签: pythonneural-networkpytorchconv-neural-networkvalueerror

解决方案


你没有正确定义标签,它不应该是

np.eye(2, self.LABELS[label])

但反而:

np.eye(2)[self.LABELS[label]]

推荐阅读