Building a Convolutional Neural Network for Image Classification using PyTorch

Python

This code snippet uses PyTorch to create a convolutional neural network for multiclass image classification.

To train the model, the code applies normalization and convolutional layers with max pooling to ta dataset of images. It then uses the Adam optimizer, sparse categorical cross-entropy loss, and accuracy metrics to compile the model. Once the model is trained, you can easily evaluate its performance on test data to see how well it performs.

 1|  import torch
 2|  import torch.nn as nn
 3|  import torch.optim as optim
 4|  
 5|  # Step 1: We normalize the pixel values of 
 6|  # the images by dividing them by 255.0 to 
 7|  # scale them to the range of 0 to 1.
 8|  X_train = torch.tensor(X_train).float() / 255.0
 9|  X_test = torch.tensor(X_test).float() / 255.0
10|  X_val = torch.tensor(X_val).float() / 255.0
11|  
12|  # Step 2: We define the neural network model 
13|  # using the PyTorch Sequential API. In this example, 
14|  # we use two convolutional layers with max pooling
15|  # followed by a dense output layer with softmax activation.
16|  model = nn.Sequential(
17|      nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1),
18|      nn.ReLU(),
19|      nn.MaxPool2d(kernel_size=2, stride=2),
20|      nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1),
21|      nn.ReLU(),
22|      nn.MaxPool2d(kernel_size=2, stride=2),
23|      nn.Flatten(),
24|      nn.Linear(64*8*8, 10),
25|      nn.Softmax(dim=1)
26|  )
27|  
28|  # Step 3: We define the optimizer, loss function, and metrics for evaluation.
29|  # Here we use the Adam optimizer, sparse categorical cross-entropy loss
30|  # and accuracy as the evaluation metric.
31|  optimizer = optim.Adam(model.parameters(), lr=0.001)
32|  criterion = nn.CrossEntropyLoss()
33|  metrics = ['accuracy']
34|  
35|  # Step 4: Train the model. We specify the number of epochs 
36|  # to train for and the validation data to evaluate the model 
37|  # after each epoch.
38|  for epoch in range(10):
39|      model.train()
40|      optimizer.zero_grad()
41|      y_pred = model(X_train)
42|      loss = criterion(y_pred, y_train)
43|      loss.backward()
44|      optimizer.step()
45|      
46|      model.eval()
47|      with torch.no_grad():
48|          y_val_pred = model(X_val)
49|          val_loss = criterion(y_val_pred, y_val)
50|          val_metrics = [metric(y_val_pred.argmax(dim=1), y_val) for metric in metrics]
51|      
52|      print(f"Epoch {epoch+1}, train_loss: {loss:.4f}, val_loss: {val_loss:.4f}, val_metrics: {val_metrics}")
53|      
54|  # Step 5: Evaluate the trained model on the test data and 
55|  # print the test accuracy.
56|  model.eval()
57|  with torch.no_grad():
58|      y_test_pred = model(X_test)
59|      test_loss = criterion(y_test_pred, y_test)
60|      test_metrics = [metric(y_test_pred.argmax(dim=1), y_test) for metric in metrics]
61|      
62|  print(f"Test loss: {test_loss:.4f}, test_metrics: {test_metrics}")
Did you find this snippet useful?

Sign up for free to to add this to your code library