PyTorch ConvNet not working. Loss goes down as accuracy stays about %14
I am trying to learn pytorch and this is my first convolutional network. But the model is not training. Loss goes down on every epoch but accuracy fluctuates between 10-20%. I want to know what am i doing wrong to improve myself.
This is the data loading part
training_data = datasets.MNIST(
    root=&quot;data&quot;,
    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=&quot;data&quot;,
    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)

This is my model
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)

These are my propagation loops
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&quot;loss: {loss:&gt;7f}  [{current:&gt;5d}/{size:&gt;5d}]&quot;)

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&quot;{pred[0].argmax(0)}={y[0]}&quot;)

    test_loss /= num_batches
    correct /= size
    print(f&quot;Test Error: \n Accuracy: {(100*correct):&gt;0.1f}%, Avg loss: {test_loss:&gt;8f} \n&quot;)

loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(),lr=learning_rate)

epochs = 10
for t in range(epochs):
    print(f&quot;Epoch {t+1}\n-------------------------------&quot;)
    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(&quot;Done!&quot;)


your accuracy calculation is not correct:

on pred side use argmax(1);
on y side note that y is one-hot encoded, so use argmax there, or something else.

this will work:
correct += (pred.argmax(1) == y.argmax(1)).sum().item()
Also use higher learning rate, like 0.01 to see faster learning.
With these changes your net yields Accuracy==97.6% after 10 epochs.
