AlexNet网络

依然范特西╮ 提交于 2019-12-10 03:48:22

AlexNet网络的实现

导入必要的工具包

import time
import torch
from torch import nn,optim
import torchvision

添加路径并且根据有无GPU进行选择

import sys
sys.path.append("..")
import d2lzh_pytorch as d2l
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

搭建自己的神经网络层

class AlexNet(nn.Module):
    def __init__(self):
        super(AlexNet,self).__init__()
        self.conv = nn.Sequential(
            nn.Conv2d(1,96,11,4),
            nn.ReLU(),
            nn.MaxPool2d(3,2),
            nn.Conv2d(96,256,5,1,2),
            nn.ReLU(),
            nn.MaxPool2d(3,2),
            nn.Conv2d(256,384,3,1,1),
            nn.ReLU(),
            nn.Conv2d(384,384,3,1,1),
            nn.ReLU(),
            nn.Conv2d(384,256,3,1,1),
            nn.ReLU(),
            nn.MaxPool2d(3,2)
        )
        self.fc = nn.Sequential(
            nn.Linear(256*5*5,4096),
            nn.ReLU(),
            nn.Dropout(0.5),
            nn.Linear(4096,4096),
            nn.ReLU(),
            nn.Dropout(0.5),
            nn.Linear(4096,10)
        )
    
    def forward(self,img):
        feature = self.conv(img)
        output = self.fc(feature.view(img.shape[0],-1))
        return output

查看神经网络层

net = AlexNet()
print(net)

加载MNIST数据集

def load_data_fashion__mnist(batch_size,resize = None,
                            root = '~/Dataaets/FashionMNIST'):
    """Download the fashion mnist dataset and then load into memory
    ."""
    trans = []
    if resize:
        trans.append(torchvision.transforms.Resize(size = resize))
    trans.append(torchvision.transforms.ToTensor())
    
    transform = torchvision.transforms.Compose(trans)
    mnist_train = torchvision.datasets.FashionMNIST(root = root,
                                                   train = True,download = True,transform = transform)
    mnist_test = torchvision.datasets.FashionMNIST(root = root,
                                                  train = False,download = True,transform = transform)
    train_iter = torch.utils.data.DataLoader(mnist_train,
                                            batch_size = batch_size,shuffle = True,num_workers = 4)
    test_iter = torch.utils.data.DataLoader(mnist_test,batch_size = batch_size,shuffle = False,num_workers = 4)
    
    return train_iter,test_iter
batch_size = 128
#如果出现“out of memory”的报错信息,可减少batch_size或者resize
train_iter,test_iter = load_data_fashion__mnist(batch_size,resize = 224)

执行神经网络

lr,num_epochs = 0.001,5
optimizer = torch.optim.Adam(net.parameters(),lr = lr)
d2l.train_ch5(net,train_iter,test_iter,batch_size,optimizer,device,num_epochs)

额外需要的扩展包代码

def train_ch5(net,train_iter,test_iter,batch_size,optimizer,device,num_epochs):
    net = net.to(device)
    print("training on",device)
    loss = torch.nn.CrossEntropyLoss()
    batch_count = 0
    for epoch in range(num_epochs):
        train_l_sum,train_acc_sum,n,start = 0.0,0.0,0,time.time()
        for X,y in train_iter:
            X = X.to(device)
            y = y.to(device)
            y_hat = net(X)
            l = loss(y_hat,y)
            optimizer.zero_grad()
            l.backward()
            optimizer.step()
            train_l_sum += l.cpu().item()
            train_acc_sum += (y_hat.argmax(dim =1) == y).sum().cpu().item()
            n += y.shape[0]
            batch_count += 1
        test_acc = evaluate_accuracy(test_iter,net)
        print('epoch %d, loss %.4f, train acc %.3f, test acc %.3f, time %.1f sec'
              % (epoch + 1, train_l_sum / batch_count,
                 train_acc_sum / n, test_acc, time.time() - start))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!