PyTorch实现Softmax Classifier处理MNIST数据集

Softmax Classifier

1. Prepare Dataset

神经网络希望输入数据最好是在-1到1之间,最好是正态分布,这样训练的效果最好。所以我们需要把图像的像素值进行转换。

PyTorch实现Softmax Classifier处理MNIST数据集_第1张图片
from torchvision import transforms
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307, ), (0.3081, ))])

transforms.ToTensor():将图转化为Channel*Width*Height的张量。

transforms.Normalize((0.1307, ), (0.3081, )):前者是均值,后者是标准差(对数据集计算得出)。即使Tensor中的数值符合01分布。

torch.Tensor默认是torch.FloatTensor是32位浮点类型数据,torch.LongTensor是64位整型

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

batch_size = 64

transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307, ), (0.3081, ))])

train_dataset = datasets.MNIST(root='./mnist/', train=True, download=True, transform=transform)
train_loader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size)
test_dataset = datasets.MNIST(root='./mnist/', train=False, download=True, transform=transform)
test_loader = DataLoader(test_dataset, shuffle=False, batch_size=batch_size)

2. Design Model

输入张量是(N, 1, 28, 28)。但在全连接模型中,需要输入张量为二维矩阵。

x=x.view(-1, 784):将图片一行行排列,一张图片有784个像素点,则得到的二维矩阵每一行有784列。-1表示自动计算。即通过输入的张量算出一共有多少个数值,然后除以784,得到行数。

class Net(torch.nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.l1 = torch.nn.Linear(784, 512)
        self.l2 = torch.nn.Linear(512, 256)
        self.l3 = torch.nn.Linear(256, 128)
        self.l4 = torch.nn.Linear(128, 64)
        self.l5 = torch.nn.Linear(64, 10)

    def forward(self, x):
        x = x.view(-1, 784)
        x = F.relu(self.l1(x))
        x = F.relu(self.l2(x))
        x = F.relu(self.l3(x))
        x = F.relu(self.l4(x))
        return self.l5(x)


model = Net()

3. Construct Loss and Optimizer

PyTorch实现Softmax Classifier处理MNIST数据集_第2张图片

criterion = torch.nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)

4. Train and Test

test的时候不需要backward操作,所以forward过程中不用计算梯度。

def train(epoch):
    running_loss = 0.0
    for batch_idx, data in enumerate(train_loader, 0):
        inputs, target = data
        optimizer.zero_grad()

        # forward + backwar + updata
        outputs = model(inputs)
        loss = criterion(outputs, target)
        loss.backward()
        optimizer.step()

        running_loss += loss.item()
        if batch_idx % 300 == 299:
            print('[%d, %5d] loss: %.3f' % (epoch + 1, batch_idx + 1, running_loss / 300))
            running_loss = 0.0


def test():
    correct = 0
    total = 0
    with torch.no_grad():
        for data in test_loader:
            images, labels = data
            # outputs是一个Tensor
            # max函数参数:dim=1表示沿着第一个维度。行是第0个维度,列是第1个维度。
            # max函数返回:最大值,最大值下标
            outputs = model(images)
            _, predicted = torch.max(outputs.data, dim=1)
            # labels = torch.Tensor(labels)
            total += labels.size(0)  # 样本数
            correct += (predicted == labels).sum().item()  # 张量间的比较运算
    print('Accuracy on test set: %d %%' % (100 * correct / total))


for epoch in range(10):
        train(epoch)
        test()

你可能感兴趣的:(Pytorch,深度学习,神经网络,人工智能)