PyTorch深度学习实践——基于GoogleNet网络实现的手写数字识别

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

batch_size =64
transform = transforms.Compose([transforms.ToTensor()])
train_dataset = datasets.MNIST(root = './datasets',train = True,download=True,transform = transform)
train_loader = DataLoader(train_dataset,shuffle = True,batch_size = batch_size)
test_datasets = datasets.MNIST(root = './datasets',train = False,download = True,transform = transform)
test_loader = DataLoader(test_datasets,shuffle = False,batch_size = batch_size)



class InceptionA(torch.nn.Module):
    def __init__(self,in_channels):
        super(InceptionA,self).__init__()
        self.branch1x1 = torch.nn.Conv2d(in_channels,16,kernel_size=1)

        self.branch5x5_1 = torch.nn.Conv2d(in_channels,16,kernel_size=1)
        self.branch5x5_2 = torch.nn.Conv2d(16,24,kernel_size=5,padding=2)

        self.branch3x3_1 = torch.nn.Conv2d(in_channels,16,kernel_size=1)
        self.branch3x3_2 = torch.nn.Conv2d(16,24,kernel_size=3,padding=1)
        self.branch3x3_3 = torch.nn.Conv2d(24,24,kernel_size=3,padding=1)

        #self.branch_pool_1 = torch.nn.functional.avg_pool2d(in_channels,kernel_size=3,stride=1,padding=1)
        self.branch_pool_2 = torch.nn.Conv2d(in_channels,24,kernel_size=1)

    def forward(self,x):
        branch1x1 = self.branch1x1(x)
        branch5x5_1 = self.branch5x5_1(x)
        branch5x5_2= self.branch5x5_2(branch5x5_1)

        branch3x3_1 = self.branch3x3_1(x)
        branch3x3_2 = self.branch3x3_2(branch3x3_1)
        branch3x3_3 = self.branch3x3_3(branch3x3_2)


        branch_pool_1 = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1)
        branch_pool_2 = self.branch_pool_2(branch_pool_1)

        outputs = torch.cat([branch1x1,branch5x5_2,branch3x3_3,branch_pool_2],dim=1)

        return outputs


class Net(torch.nn.Module):
    def __init__(self):
        super(Net,self).__init__()
        self.conv1 = torch.nn.Conv2d(1,10,kernel_size=5)
        self.conv2 = torch.nn.Conv2d(88,20,kernel_size=5)


        self.incep1 = InceptionA(in_channels=10)
        self.incel2 = InceptionA(in_channels=20)

        self.mp = torch.nn.MaxPool2d(2)
        self.fc = torch.nn.Linear(1408,10)

    def forward(self,x):
        batch_size = x.size(0)
        x = F.relu(self.mp(self.conv1(x)))#1 =》10
        x = self.incep1(x) #10 => 88
        x = F.relu(self.mp(self.conv2(x)))
        x = self.incel2(x)
        x = x.view(batch_size,-1)
        x = self.fc(x)
        return x
model = Net()
device = torch.device("cuda:0"if torch.cuda.is_available() else "cpu")
model.to(device)

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


loss_list = []
epoch_list =[]
acc_list =[]

def train():
    running_loss = 0.0
    for batch_idx ,data in enumerate(train_loader,0):
        inputs,labels = data
        inputs = inputs.to(device)
        labels = labels.to(device)
        y_pred = model(inputs)
        loss = criter(y_pred,labels)
        running_loss = running_loss+loss.item()
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
    running_loss = running_loss/ train_loader.__len__()
    #print(running_loss)
    loss_list.append(running_loss)

def test():
    correct = 0.0
    total = 0
    with torch.no_grad():
        for data in test_loader:
            images, labels = data
            images, labels = images.to(device), labels.to(device)
            outputs = model(images)
            _,predict = torch.max(outputs.data,dim = 1)
            total = total + labels.size(0)
            correct = correct + (labels == predict).sum().item()
    accuracy = 100* correct/total
    print(f"accuracy = {accuracy:.2f}")
    acc_list.append(accuracy)


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

plt.plot(epoch_list,acc_list)
plt.xlabel('epoch')
plt.xlabel('accuracy')
plt.show()

你可能感兴趣的:(pytorch深度学习,pytorch,深度学习,神经网络)