Introduction
Welcome to our guide on building your first AI model using PyTorch! PyTorch is an open-source machine learning library based on the Torch library, used for applications such as computer vision and natural language processing. Let’s get started!
Step 1: Install PyTorch
The first step is to install PyTorch. You can do this using pip, the Python package installer. Run the following command in your terminal:
“`
pip install torch torchvision
“`
Step 2: Import the Necessary Libraries
In your Python script, import the torch and torch.nn modules, which contain the essential functions and classes for building neural networks.
“`python
import torch
import torch.nn as nn
“`
Step 3: Define the Neural Network
Next, define a simple neural network. In this example, we’ll create a feed-forward neural network with one hidden layer.
“`python
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(784, 256)
self.fc2 = nn.Linear(256, 10)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = self.fc2(x)
return x
“`
Step 4: Prepare the Data
For simplicity, we’ll use the MNIST dataset of handwritten digits. Load the dataset and prepare your data (e.g., normalize the images, split the data into training and testing sets).
“`python
from torchvision.datasets import MNIST
from torchvision.transforms import ToTensor
train_data = MNIST(root=’./data’, train=True, transform=ToTensor(), download=True)
train_loader = torch.utils.data.DataLoader(train_data, batch_size=64, shuffle=True)
test_data = MNIST(root=’./data’, train=False, transform=ToTensor(), download=True)
test_loader = torch.utils.data.DataLoader(test_data, batch_size=64, shuffle=False)
“`
Step 5: Train the Neural Network
Now, let’s train our neural network. In this example, we’ll use the cross-entropy loss function and the Adam optimizer.
“`python
device = torch.device(‘cuda’ if torch.cuda.is_available() else ‘cpu’)
net = Net().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(net.parameters(), lr=0.001)
for epoch in range(10): # loop over the dataset multiple times
running_loss = 0.0
for i, data in enumerate(train_loader, 0):
inputs, labels = data[0].to(device), data[1].to(device)
optimizer.zero_grad()
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
print(f’Epoch {epoch + 1}, Loss: {running_loss / (i + 1)}’)
“`
Step 6: Test Your Model
Finally, let’s test our trained neural network on the test dataset.
“`python
correct = 0