convolutional_neural_network

Convolutional_Neural_Network

# Import necessary packages.
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
# Device Configuration.
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(device)
cuda
# Set the Hyper parameters.
num_epochs = 5
num_classes = 10
batch_size = 100
learning_rate = 0.001
# Load the MNIST dataset.
train_dataset = torchvision.datasets.MNIST(root='../../data/',
                                           train=True,
                                           transform=transforms.ToTensor(),
                                           download=True)

test_dataset = torchvision.datasets.MNIST(root='../../data/',
                                          train=False,
                                          transform=transforms.ToTensor())
# Define the Data Loader.
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
                                           batch_size=batch_size,
                                           shuffle=True)

test_loder = torch.utils.data.DataLoader(dataset=test_dataset,
                                         batch_size=batch_size,
                                         shuffle=False)
# Convolutional neural network (two convolutional layers).
class ConvNet(nn.Module):
    def __init__(self, num_classes=10):
        super(ConvNet, self).__init__()
        self.layer1 = nn.Sequential(
            nn.Conv2d(1, 16, kernel_size=5, stride=1, padding=2),
            nn.BatchNorm2d(16),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2))
        self.layer2 = nn.Sequential(
            nn.Conv2d(16, 32, kernel_size=5, stride=1, padding=2),
            nn.BatchNorm2d(32),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2))
        self.fc = nn.Linear(7*7*32, num_classes)
    
    def forward(self, x):
        out = self.layer1(x)
        out = self.layer2(out)
        out = out.reshape(out.size(0), -1)
        out = self.fc(out)
        return out

model = ConvNet(num_classes).to(device)
# Loss and optimizer.
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
# Train the model.
total_step = len(train_loader)
for epoch in range(num_epochs):
    for i, (images, labels) in enumerate(train_loader):
        images = images.to(device)
        labels = labels.to(device)

        # Forward pass and calculate loss.
        outputs = model(images)
        loss = criterion(outputs, labels)

        # Backward and optimize.
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        if (i+1) % 100 == 0:
            print('Epoch [{}/{}], Step [{}/{}], Loss {:.4f}'
                  .format(epoch+1, num_epochs, i+1, total_step, loss.item()))
Epoch [1/5], Step [100/600], Loss 0.1166
Epoch [1/5], Step [200/600], Loss 0.0707
Epoch [1/5], Step [300/600], Loss 0.0773
Epoch [1/5], Step [400/600], Loss 0.0105
Epoch [1/5], Step [500/600], Loss 0.0625
Epoch [1/5], Step [600/600], Loss 0.0819
Epoch [2/5], Step [100/600], Loss 0.0348
Epoch [2/5], Step [200/600], Loss 0.0216
Epoch [2/5], Step [300/600], Loss 0.1454
Epoch [2/5], Step [400/600], Loss 0.0169
Epoch [2/5], Step [500/600], Loss 0.0153
Epoch [2/5], Step [600/600], Loss 0.0051
Epoch [3/5], Step [100/600], Loss 0.0160
Epoch [3/5], Step [200/600], Loss 0.0096
Epoch [3/5], Step [300/600], Loss 0.1079
Epoch [3/5], Step [400/600], Loss 0.0533
Epoch [3/5], Step [500/600], Loss 0.0084
Epoch [3/5], Step [600/600], Loss 0.0403
Epoch [4/5], Step [100/600], Loss 0.0063
Epoch [4/5], Step [200/600], Loss 0.0862
Epoch [4/5], Step [300/600], Loss 0.0327
Epoch [4/5], Step [400/600], Loss 0.0245
Epoch [4/5], Step [500/600], Loss 0.0453
Epoch [4/5], Step [600/600], Loss 0.3322
Epoch [5/5], Step [100/600], Loss 0.0070
Epoch [5/5], Step [200/600], Loss 0.0352
Epoch [5/5], Step [300/600], Loss 0.0684
Epoch [5/5], Step [400/600], Loss 0.0334
Epoch [5/5], Step [500/600], Loss 0.0664
Epoch [5/5], Step [600/600], Loss 0.0556
# Test the model.
model.eval()    # eval mode (batchnorm uses moving mean/variance instead of mini_batch mean/variance)
with torch.no_grad():
    correct = 0
    total = 0
    for images, labels in test_loder:
        images = images.to(device)
        labels = labels.to(device)
        outputs = model(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

    print('Test Accuracy of the model on the 10000 test images: {} %'.format(100 * correct / total))
Test Accuracy of the model on the 10000 test images: 99.15 %
# Save the model checkpoint.
torch.save(model.state_dict(), 'model_param.ckpt')
# Alternative method to save the hole model.
# torch.save(model, 'model.ckpt')

# Load the model checkpoint.
model.load_state_dict(torch.load('model_param.ckpt'))
# ALternative method to load the hole model.
# torch.load('model.ckpt')

你可能感兴趣的:(神经网络与深度学习,深度学习,python,机器学习,pytorch,卷积神经网络)