title: PyTorch - Computing and printing the training accuracy of the QuickStart Tutorial
body: <p>to learn PyTorch, I started with the <a href="https://pytorch.org/tutorials/beginner/basics/quickstart_tutorial.html" rel="nofollow noreferrer">Quickstart Tutorial</a>. In the <strong>train()</strong> method, I noticed that <code>they don't print the training accuracy during the training session</code>. Only the training loss is printed.</p>
  <p>Coming from Keras, this was very unusual for me, since the training accuracy automatically printed when you call fit().</p>
  <p>So, I decided to modify the tutorial code like the following to print the training accuracy:</p>
  <pre><code>def train(dataloader, model, optimizer, loss_fn):
  
    model.train()
    size = len(dataloader.dataset)
    num_batches = len(dataloader)
  
    training_loss = 0.0
    correct = 0.0
  
    for batch, (imgs, labels) in enumerate(dataloader):
      imgs = imgs.to(device=device)
      labels = labels.to(device=device)
  
      predictions = model(imgs)
      loss = loss_fn(predictions, labels)
  
      optimizer.zero_grad()
      loss.backward()
      optimizer.step()
  
      # accumulate the training loss - each batch's loss will be added to trainin_loss
      training_loss += loss.item()
      
      # determines the number of correct predictions
      correct += (predictions.argmax(1) == labels).type(torch.float).sum().item()
    
    # end of for loop - all batches are processed      
  
    # after all batches are processed, determine the average training loss
    training_loss = training_loss / num_batches
    # this would be the training accuracy: number of correct predictions / number of samples in dataset
    correct = correct / size
  
    print(f&quot;{datetime.datetime.now()} Training Error: \n Accuracy: {(100*correct):&gt;0.1f}%, Avg loss: {training_loss:&gt;8f} \n&quot;)
  </code></pre>
  <p>Is this ok ? As a beginner to PyTorch, I wanted to make sure that is correct before I start training my neural networks.</p>