首页 > 解决方案 > 没有 Maxpool2d 时显示 Maxpool2d 错误

问题描述

我运行以下代码来训练一个神经网络,该网络包含一个具有最大池化和两个全连接层的 CNN:

class Net(nn.Module):
    def __init__(self, vocab_size, embedding_size):
        torch.manual_seed(0)
        super(Net, self).__init__()
        self.word_embeddings = nn.Embedding(vocab_size, embedding_size)
        self.conv1 = nn.Conv1d(embedding_size, 64, 3)
        self.drop1 = nn.Dropout(0.5)
        self.max_pool1 = nn.MaxPool1d(2)
        self.flat1 = nn.Flatten()
        self.fc1 = nn.Linear(64*99, 100)
        self.fc2 = nn.Linear(100, 1)

    def forward(self, sentence):
        embedding = self.word_embeddings(sentence).permute(0, 2, 1)
        conv1 = F.relu(self.conv1(embedding))
        drop1 = self.drop1(conv1)
        max_pool1 = self.max_pool1(drop1)
        flat1 = self.flat1(max_pool1)
        fc1 = F.relu(self.fc1(flat1))
        fc2 = torch.sigmoid(self.fc2(fc1))
        return fc2

net = Net(vocab_size, EMBEDDING_SIZE)
EPOCHS = 10
net.cuda()
criterion = nn.BCELoss()
optimizer = optim.Adam(net.parameters(), lr=0.001)
loader = DataLoader(train, batch_size=32)

net.train()
for epoch in range(EPOCHS):
    progress = tqdm_notebook(loader, leave=False)
    for inputs, target in progress:
        net.zero_grad()
        output = net(inputs.to(device))
        loss = criterion(output, target.to(device))
        loss.backward()
        optimizer.step()
    print(loss)

我收到以下错误(错误跟踪已更新,它包括完整的跟踪):

/usr/local/lib/python3.6/dist-packages/torch/nn/modules/loss.py:498: UserWarning: Using a target size (torch.Size([32])) that is different to the input size (torch.Size([32, 1])) is deprecated. Please ensure they have the same size.
  return F.binary_cross_entropy(input, target, weight=self.weight, reduction=self.reduction)
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-2-3c8a885417ba> in <module>()
     33     for inputs, target in progress:
     34         net.zero_grad()
---> 35         output = net(inputs.to(device))
     36         loss = criterion(output, target.to(device))
     37         loss.backward()

5 frames
/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in _max_pool1d(input, kernel_size, stride, padding, dilation, ceil_mode, return_indices)
    455         stride = torch.jit.annotate(List[int], [])
    456     return torch.max_pool1d(
--> 457         input, kernel_size, stride, padding, dilation, ceil_mode)
    458 
    459 max_pool1d = boolean_dispatch(

RuntimeError: max_pool2d_with_indices_out_cuda_frame failed with error code 0

我的代码中没有任何 Maxpool2ds!有人可以帮我解决这个问题吗?

标签: nlppytorch

解决方案


推荐阅读