请选择 进入手机版 | 继续访问电脑版
MSIPO技术圈 首页 IT技术 查看内容

PyTorch训练简单的全连接神经网络:手写数字识别

2023-07-13

pytorch 神经网络训练demo

数据集:MNIST

该数据集的内容是手写数字识别,其分为两部分,分别含有60000张训练图片和10000张测试图片

神经网络:全连接网络

# Imports
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import DataLoader
import torchvision.datasets as datasets
import torchvision.transforms as transforms

# Create Fully Connected Network
class NN(nn.Module):
    def __init__(self, input_size, num_classes): #(28 * 28 = 784)
        super(NN, self).__init__()
        self.fc1 = nn.Linear(input_size, 50)
        self.fc2 = nn.Linear(50, num_classes)

    def forward(self, x):
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        return x

model = NN(784, 10)
x = torch.randn(64, 784)

# Set device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# Hyperparameters
input_size = 784
num_classes = 10
learning_rate = 0.001
batch_size = 64
num_epochs = 1


# Load data
train_dataset = datasets.MNIST(root='dataset/', 
                               train=True, 
                               transform=transforms.ToTensor(),
                               download=True)
train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)
# print(f'train_loader: {train_loader}')
test_dataset = datasets.MNIST(root='dataset/', 
                              train=False, 
                               transform=transforms.ToTensor(),
                               download=True)
test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=True)

# Initialize network
model = NN(input_size=input_size, num_classes=num_classes).to(device)

# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)

# Train network
for epoch in range(num_epochs):
    # data: images, targets: labels
    for batch_idx, (data, targets) in enumerate(train_loader):
        # Get data to cuda if possible
        data = data.to(device)
        targets = targets.to(device)
        # Get to correct shape
        # print(data.shape) # (batch_size, input_channel, height, width)
        data = data.reshape(data.shape[0], -1) # 64*784

        # forward
        scores = model(data) # 64*10
        # print(f'scores: {scores.shape}') # 64*10
        # print(f'targets: {targets.shape}') # 64*1
    
        loss = criterion(scores, targets)

        # backward
        optimizer.zero_grad()
        loss.backward()

        # gradient descent or adam step
        optimizer.step()


# Check accuracy on training & test to see how good our model
def check_accuracy(loader, model):
    if loader.dataset.train:
        print("Checking accuracy on training data")
    else:
        print("Checking accuracy on test data")
    num_correct = 0
    num_samples = 0
    model.eval()

    with torch.no_grad(): # 不计算梯度
        for x, y in loader:
            x = x.to(device)
            y = y.to(device)
            x = x.reshape(x.shape[0], -1) # 64*784

            scores = model(x)# 64*10
            # torch.max()这个函数返回的是两个值:
                #第一个值是具体的value(我们用下划线_表示)
                #第二个值是value所在的index(也就是predictions)。
            # 我们不关心最大值是什么,而关心最大值对应的index是什么,所以选用下划线代表不需要用到的变量。
            # 比如在图像分类任务中,index就对应着图片的类别,这里我们只关心网络预测的类别是什么,而不关心该类别的预测概率。
            _, predictions = scores.max(dim=1) #dim=1,表示对每行取最大值,每行代表一个样本。
            num_correct += (predictions == y).sum()
            num_samples += predictions.size(0) # 64

        print(f'Got {num_correct} / {num_samples} with accuracy {float(num_correct)/float(num_samples)*100:.2f}%')

    model.train()

check_accuracy(train_loader, model)
check_accuracy(test_loader, model)

输出结果

Checking accuracy on training data
Got 55770 / 60000 with accuracy 92.95%
Checking accuracy on test data
Got 9316 / 10000 with accuracy 93.16%

来源

【1】https://www.youtube.com/watch?v=Jy4wM2X21u0&list=PLhhyoLH6IjfxeoooqP9rhU3HJIAVAJ3Vz&index=3

相关阅读

热门文章

    手机版|MSIPO技术圈 皖ICP备19022944号-2

    Copyright © 2024, msipo.com

    返回顶部