Pytorch之MNIST数据集实现

Pytorch之MNIST数据集实现

  • 1. 全连接实现
  • 2. CNN实现

提示:如果数据集下载失败,可以直接从网上下载四个数据集到raw文件夹下,dataset和项目为同级目录,例如:C:\Users\dell\PycharmProjects\dataset\mnist\MNIST\raw

1. 全连接实现

代码如下(示例):

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
# transforms.ToTensor():Covert the PIL Image to Tensor
#  transforms.Normalize:The PARAMETERS are mean and std respectively,It use formulation x=(x-mean)/std
transform = transforms.Compose([transforms.ToTensor(),
                                transforms.Normalize((0.1307,), (0.3081,))])

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

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


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()
# --------------------------------------------------
criterion = torch.nn.CrossEntropyLoss()
# momentum是冲量,可以从局部极值走出来尽可能找到全局最优解
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)


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

        # forward + backward + update
        outputs = model(inputs)
        # print(outputs)
        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 = model(images)
            # print(outputs)
            _, predicted = torch.max(outputs.data, dim=1)
            total += labels.size(0)
            correct += (predicted == labels).sum().item()
    print('Accuracy on test set: %d %%' % (100 * correct / total))


if __name__ == '__main__':
    for epoch in range(10):
        train(epoch)
        test()

2. CNN实现

注:经过卷积后的图像长宽计算公式如下

h e i g h t o u t = ( h e i g h t i n − h e i g h t k e r n e l + 2 × p a d d i n g ) s t r i d e + 1 height_{out} =\frac{(height_{in}-height_{kernel}+2\times{padding})}{stride} +1 heightout=stride(heightinheightkernel+2×padding)+1
w i d t h o u t = ( w i d t h i n − w i d t h t k e r n e l + 2 × p a d d i n g ) s t r i d e + 1 width_{out} =\frac{(width_{in}-widtht_{kernel}+2\times{padding})}{stride} +1 widthout=stride(widthinwidthtkernel+2×padding)+1
代码如下(示例):

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
# transforms.ToTensor():Covert the PIL Image to Tensor
#  transforms.Normalize:The PARAMETERS are mean and std respectively,It use formulation x=(x-mean)/std
transform = transforms.Compose([transforms.ToTensor(),
                                transforms.Normalize((0.1307,), (0.3081,))])

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

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


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)

        self.conv1 = torch.nn.Conv2d(1, 10, kernel_size=(5, 5))
        self.conv2 = torch.nn.Conv2d(10, 20, kernel_size=(5, 5))
        self.pooling = torch.nn.MaxPool2d(2)
        self.fc = torch.nn.Linear(320, 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)

        # Flatten data from (n, 1, 28, 28) to (n, 784)
        # print(x.shape)
        batch_size = x.size(0)
        x = F.relu(self.pooling(self.conv1(x)))
        # print(x.shape)
        x = F.relu(self.pooling(self.conv2(x)))
        # print(x.shape)
        x = x.view(batch_size, -1)  # flatten
        # print(x.shape)
        x = self.fc(x)
        return x


model = Net()
# --------------------------------------------------
criterion = torch.nn.CrossEntropyLoss()
# momentum是冲量,可以从局部极值走出来尽可能找到全局最优解
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)


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

        # forward + backward + update
        outputs = model(inputs)
        # print(outputs)
        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 = model(images)
            # print(outputs)
            _, predicted = torch.max(outputs.data, dim=1)
            total += labels.size(0)
            correct += (predicted == labels).sum().item()
    print('Accuracy on test set: %d %%' % (100 * correct / total))


if __name__ == '__main__':
    for epoch in range(10):
        train(epoch)
        test()

你可能感兴趣的:(pytorch学习)