PyTorch, developed by Facebook's AI Research lab, is a popular open-source library for deep learning. It's known for its dynamic computation graphs and ease of use, making it perfect for research and production. Let's delve into a PyTorch training example to understand its functionality better.

Before diving into the example, ensure you have installed the necessary libraries. You can do this by running:

``` pip install torch torchvision ```
Setup and Data Preparation
For this example, we'll use the Fashion-MNIST dataset, a collection of 60,000 28x28 grayscale images of 10 fashion categories.

Let's load and normalize this dataset using PyTorch's built-in torchvision module.
Loading the Data

We'll first load the training and test datasets using torch.utils.data.DataLoader, which also handles batching.
Here's how you can do it:
```python from torchvision import datasets, transforms transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,)) ]) train_data = datasets.FashionMNIST(root='./data', train=True, download=True, transform=transform) test_data = datasets.FashionMNIST(root='./data', train=False, download=True, transform=transform) train_loader = torch.utils.data.DataLoader(train_data, batch_size=64, shuffle=True) test_loader = torch.utils.data.DataLoader(test_data, batch_size=64, shuffle=True) ```
Understanding the Data

Now, let's check the size of the datasets and the images' shape:
The output should look something like this: Number of training examples = 60000, Number of test examples = 10000, and Image shape = (3, 28, 28).
Defining the Neural Network Architecture

Let's create a simple neural network with one convolutional layer and two fully connected layers using PyTorch's torch.nn module.
Convolutional Neural Network (CNN) Architecture




















Here's a basic CNN architecture for this task:
```python import torch.nn as nn import torch.nn.functional as F class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 32, 3, 1) self.fc1 = nn.Linear(32 * 27 * 27, 128) self.fc2 = nn.Linear(128, 10) def forward(self, x): x = F.relu(self.conv1(x)) x = x.view(-1, 32 * 27 * 27) x = F.relu(self.fc1(x)) x = self.fc2(x) return x ```
Initializing the Network and Optimizer
Now, let's instantiate the network, define the loss function, and choose an optimizer:
Output when defining the network and optimizer:
Net(), criterion, and optimizer should now be defined.
Training the Neural Network
It's time to train our model using the prepared data and defined network.
Training Loop
Here's a simple training loop that iterates through the dataset, makes predictions, calculates losses, and updates the model's parameters:
```python def train(model, device, train_loader, optimizer, epoch): model.train() for batch_idx, (data, target) in enumerate(train_loader): data, target = data.to(device), target.to(device) optimizer.zero_grad() output = model(data) loss = F.nll_loss(output, target) loss.backward() optimizer.step() if batch_idx % 100 == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format( epoch, batch_idx * len(data), len(train_loader.dataset), 100. * batch_idx / len(train_loader), loss.item())) ```
Running the Training Loop
You can run this function for a specified number of epochs (iterations over the entire dataset) like this:
```python for epoch in range(1, 11): train(model, device, train_loader, optimizer, epoch) ```
After running the training loop for a few epochs, you'll see the model's loss decrease, indicating that it's learning from the data.
Evaluating the Model
Once trained, let's evaluate the model's performance on the test dataset.
Testing the Model
Here's a simple testing loop that calculates the model's accuracy on the test set:
```python def test(model, device, test_loader): model.eval() test_loss = 0 correct = 0 with torch.no_grad(): for data, target in test_loader: data, target = data.to(device), target.to(device) output = model(data) test_loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability correct += pred.eq(target.view_as(pred)).sum().item() test_loss /= len(test_loader.dataset) print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.*%})\n'.format( test_loss, correct, len(test_loader.dataset), 100. * correct / len(test_loader.dataset))) ```
Running the Testing Loop
After training, run the test function to evaluate the model:
```python test(model, device, test_loader) ```
Remember, the accuracy will depend on the number of epochs and the specifics of your model. This example provides a starting point for your PyTorch training journey.
Now that you've seen a complete PyTorch training example, it's time to dive deeper into more advanced models, architectures, and techniques. Happy coding!