How do I create AI with PyTorch?

How do I create AI with PyTorch?

Creating an AI (Artificial Intelligence) model with PyTorch is a rewarding experience! Here’s a step-by-step beginner-friendly guide to get you started, covering a simple neural network for classification (like MNIST digit recognition):


Basic Steps to Create AI with PyTorch

1. Install PyTorch

pip install torch torchvision

2. Import Libraries

import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms

3. Prepare the Dataset

For example, using the MNIST dataset (handwritten digits):

transform = transforms.ToTensor()

train_dataset = torchvision.datasets.MNIST(root='./data', train=True,
                                           transform=transform, download=True)
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True)

test_dataset = torchvision.datasets.MNIST(root='./data', train=False,
                                          transform=transform)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=64, shuffle=False)

4. Define the Neural Network

Here's a simple fully connected network:

class SimpleNN(nn.Module):
    def __init__(self):
        super(SimpleNN, self).__init__()
        self.fc1 = nn.Linear(28*28, 512)
        self.relu = nn.ReLU()
        self.fc2 = nn.Linear(512, 10)

    def forward(self, x):
        x = x.view(-1, 28*28)  # Flatten the image
        x = self.fc1(x)
        x = self.relu(x)
        x = self.fc2(x)
        return x

5. Instantiate Model, Loss, Optimizer

model = SimpleNN()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)

6. Train the Model

for epoch in range(5):  # loop over the dataset multiple times
    for images, labels in train_loader:
        outputs = model(images)
        loss = criterion(outputs, labels)

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
    print(f'Epoch {epoch+1}, Loss: {loss.item()}')

7. Test the Model

correct = 0
total = 0

with torch.no_grad():
    for images, labels in test_loader:
        outputs = model(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

print('Accuracy: %d %%' % (100 * correct / total))

Summary

You now have a simple AI for digit classification! The same steps (define dataset, model, loss, optimizer, training loop) apply for much more complex tasks. PyTorch makes it flexible and easy.

Want code for another kind of AI (like image recognition, text generation, etc.) or a deeper explanation? Let me know!