Here is an example code to load the CIFAR-10 dataset, build a CNN network, train it, and evaluate its accuracy:

import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt

# Load CIFAR-10 dataset
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=4, shuffle=True, num_workers=2)

testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=4, shuffle=False, num_workers=2)

classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')

# Define the CNN architecture
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(3, 6, 5)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = x.view(-1, 16 * 5 * 5)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

# Initialize the network
net = Net()

# Define the loss function and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)

# Train the network
num_epochs = 10
train_loss = []
val_loss = []
train_accuracy = []
val_accuracy = []

for epoch in range(num_epochs):
    running_loss = 0.0
    correct = 0
    total = 0
    
    for i, data in enumerate(trainloader, 0):
        inputs, labels = data
        optimizer.zero_grad()
        
        # Forward pass
        outputs = net(inputs)
        loss = criterion(outputs, labels)
        
        # Backward pass and optimize
        loss.backward()
        optimizer.step()
        
        # Compute statistics
        running_loss += loss.item()
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()
        
    # Compute training loss and accuracy
    train_loss.append(running_loss / len(trainloader))
    train_accuracy.append(correct / total)
    
    # Compute validation loss and accuracy
    val_loss_value = 0.0
    val_correct = 0
    val_total = 0
    
    with torch.no_grad():
        for data in testloader:
            images, labels = data
            outputs = net(images)
            val_loss_value += criterion(outputs, labels).item()
            _, predicted = torch.max(outputs.data, 1)
            val_total += labels.size(0)
            val_correct += (predicted == labels).sum().item()
    
    val_loss.append(val_loss_value / len(testloader))
    val_accuracy.append(val_correct / val_total)
    
    print(f'Epoch {epoch+1}/{num_epochs}, Training Loss: {train_loss[-1]:.4f}, Training Accuracy: {train_accuracy[-1]:.4f}, Validation Loss: {val_loss[-1]:.4f}, Validation Accuracy: {val_accuracy[-1]:.4f}')

# Plot the training and validation loss
plt.figure()
plt.plot(range(num_epochs), train_loss, label='Training Loss')
plt.plot(range(num_epochs), val_loss, label='Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()

# Plot the training and validation accuracy
plt.figure()
plt.plot(range(num_epochs), train_accuracy, label='Training Accuracy')
plt.plot(range(num_epochs), val_accuracy, label='Validation Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.show()

# Print the final accuracy
print(f'
Final Training Accuracy: {train_accuracy[-1]:.4f}')
print(f'Final Validation Accuracy: {val_accuracy[-1]:.4f}')

# Evaluate on the test set
test_correct = 0
test_total = 0

with torch.no_grad():
    for data in testloader:
        images, labels = data
        outputs = net(images)
        _, predicted = torch.max(outputs.data, 1)
        test_total += labels.size(0)
        test_correct += (predicted == labels).sum().item()

test_accuracy = test_correct / test_total
print(f'Testing Accuracy: {test_accuracy:.4f}')

You can modify the hyperparameters like the learning rate, number of epochs, batch size, etc. to improve the accuracy.

CIFAR-10 Image Classification with CNN using PyTorch

原文地址: https://www.cveoy.top/t/topic/dm63 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录