python - Pytorch损失函数最后一批错误

标签 python machine-learning pytorch loss-function

假设我有 77 个样本来训练 CNN,并且我的批处理大小为 10。那么最后一个批处理的批处理大小为 7,而不是 10。不知何故当我将它传递给诸如 nn.MSELoss() 之类的损失函数时,它给出了错误:

RuntimeError: The size of tensor a (10) must match the size of tensor b (7) at non-singleton dimension 1

那么pytorch不支持不同大小的批处理?

我的代码有疑问:

import numpy as np
import torch
from torch import nn
import torchvision
import torch.nn.functional as F
import torch.optim as optim

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(1, 6, (5,4))
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.fc1 = nn.Linear(64, 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, x.shape[1] * x.shape[2] * x.shape[3])
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

model = Net()

batch_size = 10

# Generating Artifical data
x_train = torch.randn((77,1,20,20))
y_train = torch.randint(0,10,size=(77,),dtype=torch.float)

trainset = torch.utils.data.TensorDataset(x_train,y_train)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=0)
# testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size, shuffle=False, num_workers=0)

criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)

for epoch in range(20):  # 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 = model(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

        # print statistics
        running_loss += loss.item()
        if i%10==0:
            print('epoch{}, step{}, loss: {}'.format(epoch + 1, i + 1, running_loss))
#             print("frac post = {}".format(frac_post))
            running_loss = 0.0

最佳答案

问题不是由于批量大小,而是由于无法在 CNN 的 10 个输出和每个示例中提供的单个标签之间正确广播。 如果您在抛出错误的批处理期间查看模型输出和标签张量形状,

print(outputs.shape, labels.shape)
#out: torch.Size([7, 10]) torch.Size([7])

您将看到标签存储在单例张量中。根据pytorch broadcasting rules ,为了可广播,两个张量必须在所有尾随维度上兼容。在这种情况下,模型输出(10)的尾部尺寸与标签(7)的尾部尺寸不兼容。

要解决此问题,请向标签添加虚拟维度(假设您实际上想要广播标签以匹配您的十个网络输出),或者定义具有标量输出的网络。例如:

y_train = torch.randint(0,10,size=(77,1),dtype=torch.float)

结果

print(outputs.shape, labels.shape)
#out: torch.Size([7, 10]) torch.Size([7,1])
# these are broadcastable

关于python - Pytorch损失函数最后一批错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55507391/

相关文章:

python - 对 Docker 容器的 HTTP 调用将 IP 重定向到 Docker ID

python - 将python打印输出保存到变量

r - 如何在 R 中使用 libSVM(包 e1071)获得概率?

Python 切片表示法

python - 如何在 GPU 上从 PyTorch 中的另外两个张量有条件地构造一个张量?

deep-learning - 如何计算 PyTorch 中的自举交叉熵损失?

Python 获取 <title>

image - 用于图像分类的 Imagenet 数据集的子集

python - 用 pytorch 计算预测函数的损失

python - 使用python打开其他应用程序