【问题标题】:Error while executing CrossEntropyLoss() in PyTorch在 PyTorch 中执行 CrossEntropyLoss() 时出错
【发布时间】:2021-06-06 12:00:46
【问题描述】:

我的数据集包含形状为 [3,28,28] 的图像。我写了以下代码:

class ConvNet(nn.Module):
    def __init__(self):
        super(ConvNet, self).__init__()
        self.layer1 = nn.Sequential(nn.Conv2d(3, 28, kernel_size=5, stride=1, padding=2),nn.ReLU(),nn.MaxPool2d(kernel_size=2, stride=2))
        self.layer2 = nn.Sequential(nn.Conv2d(28, 56, kernel_size=5, stride=1, padding=2),nn.ReLU(),nn.MaxPool2d(kernel_size=2, stride=2))
        self.drop_out = nn.Dropout()
        self.fc1 = nn.Linear(7 * 7 * 56, 1000)
        self.fc2 = nn.Linear(1000, 10)
     

    def forward(self, x):
        out = self.layer1(x)
        out = self.layer2(out)
        out = out.reshape(out.size(0), -1)
        out = self.drop_out(out)
        out = self.fc1(out)
        out = self.fc2(out)
        return out

model = ConvNet()
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
total_step = len(loader_train)

for e in range(num_epochs):
    print("Epoch ", e+1,": ")
    for i, (images, labels) in enumerate(loader_train):
        optimizer.zero_grad()
        actual_out = model(images)
        loss = criterion(actual_out, labels)
        loss.backward()
        optimizer.step()
 
        if (i+1) % 100 == 0:
            print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.3f}' .format(e+1, num_epochs, i+1, total_step, loss.item()))     

但是,我收到以下错误: AttributeError Traceback(最近一次调用最后一次) 在 8 实际输出 = 模型(图像) 9 ---> 10 损失 = 标准(实际输出,标签) 11 loss.backward()

AttributeError: 'tuple' 对象没有属性 'size'

我通过以下方法将标签转换为张量:

target_out = torch.empty(batch_size,dtype=torch.long).random_(labels)
loss = criterion(actual_out, target_out)

但这会产生: TypeError Traceback(最近一次调用最后一次) 在 ---> 11 target_out = torch.empty(batch_size,dtype=torch.long).random_(labels) 12 损失 = 标准(实际输出,目标输出)

TypeError: random_() 接收到无效的参数组合 - 得到(元组),但预期是以下之一:

  • (*,torch.Generator 生成器)
  • (int from,int to,*,torch.Generator 生成器)
  • (int to, *, torch.Generator 生成器)

【问题讨论】:

  • 如果你能粘贴你的数据集类和数据加载器,我可以帮助你

标签: neural-network pytorch conv-neural-network


【解决方案1】:

您的 labels 对象是一个元组,您希望将其转换为 dtype long 的张量。

您可以通过以下方式执行此操作:

torch.tensor(labels, dtype=torch.long)

【讨论】:

    【解决方案2】:

    假设这是您的 train_loader 的结构,您可以在训练循环中而不是在 forward() 函数中重塑。我已经给出了一个示例,可以根据需要更改它。

    同样在后退过程中,清除 grad,.to(device) 是可选的,如果你有 GPU 的话

    train_loader = torch.utils.data.DataLoader(dataset=train_dataset, 
                                                   batch_size=batch_size, 
                                                   shuffle=True)
        
    
        for epoch in range(num_epochs):
                for i, (images, labels) in enumerate(train_loader):  
                    # origin shape: [100, 1, 28, 28]
                    # resized: [100, 784]
                    images = images.reshape(-1, 28*28).to(device)
                    labels = labels.to(device)
                    
                    # Forward pass
                    outputs = model(images)
                    loss = criterion(outputs, labels)
                    
                    # Backward and optimize
                    optimizer.zero_grad()
                    loss.backward()
                    optimizer.step()
    

    【讨论】:

      猜你喜欢
      • 2018-08-18
      • 2019-03-28
      • 2021-08-16
      • 2021-03-16
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-08
      相关资源
      最近更新 更多