机器学习之卷积神经网络Lenet5训练模型

有时候,不是因为你没有能力,也不是因为你缺少勇气,只是因为你付出的努力还太少,所以,成功便不会走向你。而你所需要做的,就是坚定你的梦想,你的目标,你的未来,然后以不达目的誓不罢休的那股劲,去付出你的努力,成功就会慢慢向你靠近。

导读:本篇文章讲解 机器学习之卷积神经网络Lenet5训练模型,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

Lenet5训练模型

下载数据集

在这里插入图片描述
可以提前下载也可以在线下载

train_data = torchvision.datasets.MNIST(root='./',download=True,train=True,transform=transform)
test_data = torchvision.datasets.MNIST(root='./',download=True,train=False,transform=transform)

训练模型

import torch
import torchvision
class Lenet5(torch.nn.Module):
    def __init__(self):
        super(Lenet5, self).__init__()
        self.model = torch.nn.Sequential(
            torch.nn.Conv2d(in_channels=1,out_channels=6,kernel_size=5), # 1*32*32 # 6*28*28
            torch.nn.ReLU(),
            torch.nn.MaxPool2d(kernel_size=2,  # 6*14*14
                                stride=2),
            torch.nn.Conv2d(in_channels=6,
                                    out_channels=16,
                                    kernel_size=5),  # 16 *10*10
            torch.nn.ReLU(),
            torch.nn.MaxPool2d(kernel_size=2,
                                stride=2),  # 16*5*5
            torch.nn.Conv2d(in_channels=16,
                                    out_channels=120,
                                    kernel_size=5),  # 120*1*1
            torch.nn.ReLU(),
            torch.nn.Flatten(),  # 展平 成120*1维
            torch.nn.Linear(120, 84),
            torch.nn.Linear(84, 10)
        )

    def forward(self,x):
        x = self.model(x)
        return x

transform = torchvision.transforms.Compose(
    [torchvision.transforms.Resize(32),
     torchvision.transforms.ToTensor()]
)
train_data = torchvision.datasets.MNIST(root='./',download=True,train=True,transform=transform)
test_data = torchvision.datasets.MNIST(root='./',download=True,train=False,transform=transform)

#分批次加载数据  64 128
train_loader =torch.utils.data.DataLoader(train_data,batch_size=64,shuffle=True)
test_loader =torch.utils.data.DataLoader(test_data,batch_size=64,shuffle=True)


#gpu
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
net = Lenet5().to(device)

loss_func = torch.nn.CrossEntropyLoss().to(device)
optim = torch.optim.Adam(net.parameters(),lr=0.001)

net.train()
for epoch in range(10):
    for step,(x,y) in enumerate(train_loader):
        x = x.to(device)
        y = y.to(device)

        ouput = net(x)
        loss = loss_func(ouput,y)  #计算损失

        optim.zero_grad()
        loss.backward()
        optim.step()

    print('epoch:',epoch,"loss:",loss)

torch.save(net,'net.pkl')

在这里插入图片描述

import torch
import torchvision
class Lenet5(torch.nn.Module):
    def __init__(self):
        super(Lenet5, self).__init__()
        self.model = torch.nn.Sequential(
            torch.nn.Conv2d(in_channels=1,out_channels=6,kernel_size=5), # 1*32*32 # 6*28*28
            torch.nn.ReLU(),
            torch.nn.MaxPool2d(kernel_size=2,  # 6*14*14
                                stride=2),
            torch.nn.Conv2d(in_channels=6,
                                    out_channels=16,
                                    kernel_size=5),  # 16 *10*10
            torch.nn.ReLU(),
            torch.nn.MaxPool2d(kernel_size=2,
                                stride=2),  # 16*5*5
            torch.nn.Conv2d(in_channels=16,
                                    out_channels=120,
                                    kernel_size=5),  # 120*1*1
            torch.nn.ReLU(),
            torch.nn.Flatten(),  # 展平 成120*1维
            torch.nn.Linear(120, 84),
            torch.nn.Linear(84, 10)
        )

    def forward(self,x):
        x = self.model(x)
        return x


transform = torchvision.transforms.Compose(
    [torchvision.transforms.Resize(32),
     torchvision.transforms.ToTensor()]
)
test_data = torchvision.datasets.MNIST(root='./',download=False,train=False,transform=transform)
test_loader =torch.utils.data.DataLoader(test_data,batch_size=64,shuffle=True)

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
net = torch.load('net.pkl')

net.eval()  #表明进行推理
with torch.no_grad():
    for step,(x,y) in enumerate(test_loader):
        x,y = x.to(device),y.to(device)

        pre = net(x)
        print(pre)
        pre_y = torch.max(pre.cpu(),1)[1].numpy()
        print(pre_y)
        y = y.cpu().numpy()

        acc = (pre_y == y).sum()/len(y)

    print("accu:",acc)



在这里插入图片描述

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/147413.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!