PyTorch ConvNet 不工作。损失下降,因为准确率保持在 %14 左右

PyTorch ConvNet not working. Loss goes down as accuracy stays about %14

我正在尝试学习 pytorch,这是我的第一个卷积网络。但是模型不是在训练。损失在每个时期都在下降,但准确率在 10-20% 之间波动。我想知道我做错了什么来提升自己。

这是数据加载部分

training_data = datasets.MNIST(
    root="data",
    train=True,
    download=True,
    transform=transforms.ToTensor(),
    target_transform=transforms.Lambda(lambda y: torch.zeros(10,dtype=torch.float).scatter_(0,torch.tensor(y),value=1))
)
test_data = datasets.MNIST(
    root="data",
    train=False,
    download=True,
    transform=transforms.ToTensor(),
    target_transform=transforms.Lambda(lambda y: torch.zeros(10,dtype=torch.float).scatter_(0,torch.tensor(y),value=1))
)
train_dataloader = DataLoader(training_data,batch_size=64,shuffle=True)
test_dataloader = DataLoader(test_data,batch_size=64,shuffle=True)

这是我的模型

from torch.nn.modules.pooling import MaxPool2d
class CNN(nn.Module):
  def __init__(self):
    super(CNN,self).__init__()
    self.CNN_stack = nn.Sequential(
        nn.ReflectionPad2d((1,0,1,0)),
        nn.Conv2d(in_channels=1,out_channels=5,kernel_size=5,stride=2),
        nn.ReLU(),
        nn.Conv2d(in_channels=5,out_channels=50,kernel_size=5,stride=2),
        nn.ReLU(),
        nn.Flatten(),
        nn.Linear(1250,100),
        nn.ReLU(),
        nn.Linear(100,10)
    )

  def forward(self,x):
    logits = self.CNN_stack(x)
    return logits

model = CNN().to(device)

这些是我的传播循环

def train_loop(batch,X,y,model,loss_fn,optimizer):
  size = 60000

  #Forward Prop
  pred = model(X)
  loss = loss_fn(pred,y)

  #Backward Prop
  optimizer.zero_grad()
  loss.backward()
  optimizer.step()

  if batch % 100 == 0:
    loss, current = loss.item(), batch * len(X)
    print(f"loss: {loss:>7f}  [{current:>5d}/{size:>5d}]")

def test_loop(dataloader, model, loss_fn):
    size = len(dataloader.dataset)
    num_batches = len(dataloader)
    test_loss, correct = 0, 0

    with torch.no_grad():
        for X, y in dataloader:
            X,y=X.to(device),y.to(device)
            pred = model(X)
            test_loss += loss_fn(pred, y).item()
            correct += (pred.argmax(0) == y).type(torch.float).sum().item()
            #print(f"{pred[0].argmax(0)}={y[0]}")

    test_loss /= num_batches
    correct /= size
    print(f"Test Error: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(),lr=learning_rate)

epochs = 10
for t in range(epochs):
    print(f"Epoch {t+1}\n-------------------------------")
    for batch, (X,y) in enumerate(train_dataloader):
      X,y = X.to(device), y.to(device)
      train_loop(batch,X, y , model, loss_fn, optimizer)
    test_loop(test_dataloader , model, loss_fn)
print("Done!")

您的准确度计算不正确:

  • pred 端使用 argmax(1);
  • y 旁边注意 y 是 one-hot 编码的,所以在那里使用 argmax 或其他东西。

这会起作用:

correct += (pred.argmax(1) == y.argmax(1)).sum().item()

也使用更高的学习率,例如 0.01 以实现更快的学习。

通过这些更改,您的净收益率在 10 个时期后准确度==97.6%。