我是Pytorch的新手,我正在尝试实现一个简单的CNN以识别MNIST图像。
我正在使用MSE损失作为损失函数并使用SGD作为优化器来训练网络。当我参加培训时,它会给我以下内容>
警告:“用户警告:使用与输入大小(torch.Size([64,10])不同的目标大小(torch.Size([64]))。由于以下原因,可能会导致错误的结果广播。请确保它们的尺寸相同。”
然后我得到以下内容
error: "RuntimeError: The size of tensor a (10) must match the size of tensor b (64) at non-singleton dimension 1".
我已经尝试使用在其他问题中找到的一些解决方案来解决它,但似乎没有任何效果。这是我如何加载数据集的代码:
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,),(0.5,))]) trainset = torchvision.datasets.MNIST(root='./data', train = True, transform = transform, download = True) trainloader = torch.utils.data.DataLoader(trainset, batch_size = 64, shuffle = True) testset = torchvision.datasets.MNIST(root='./data', train = False, transform = transform, download = True) testloader = torch.utils.data.DataLoader(testset, batch_size = 64, shuffle = False)
定义我的网络的代码:
class Net(nn.Module): def __init__(self): super(Net, self).__init__() #Convolutional layers self.conv1 = nn.Conv2d(1, 6, 5) self.conv2 = nn.Conv2d(6, 12, 5) #Fully connected layers self.fc1 = nn.Linear(12*4*4, 120) self.fc2 = nn.Linear(120, 60) self.out = nn.Linear(60,10) def forward(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 = x.reshape(-1, 12*4*4) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.out(x) return x
这是培训:
net = Net() print(net) criterion = nn.MSELoss() optimizer = optim.SGD(net.parameters(), lr=0.001) epochs = 3 for epoch in range(epochs): running_loss = 0; for images, labels in trainloader: optimizer.zero_grad() output = net(images) loss = criterion(output, labels) loss.backward() optimizer.step() running_loss += loss.item() else: print(f"Training loss: {running_loss/len(trainloader)}") print('Finished training')
谢谢!
我是Pytorch的新手,我正在尝试实现一个简单的CNN以识别MNIST图像。我正在使用MSE损失作为损失函数并使用SGD作为优化器来训练网络。当我开始训练时...
您正在使用的损失(nn.MSELoss
)对于此问题不正确。您应该使用use nn.CrossEntropyLoss
。