一起深度学习

CIFAR-10 卷积神经网络

下载数据集

python 复制代码
 batchsz = 32
    cifar_train= datasets.CIFAR10('data',train=True,transform=torchvision.transforms.Compose([
        torchvision.transforms.Resize((32,32)),
        torchvision.transforms.ToTensor()
    ]),download=True)
    cifar_train = DataLoader(cifar_train,batch_size=batchsz,shuffle=True)

    cifar_test= datasets.CIFAR10('data',train=False,transform=torchvision.transforms.Compose([
        torchvision.transforms.Resize((32,32)),
        torchvision.transforms.ToTensor()
    ]),download=True)
    cifar_test = DataLoader(cifar_test,batch_size=batchsz,shuffle=True)

构建网络

新建一个lenet5

python 复制代码
import torch
from torch import nn
from torch.nn import functional as F
class Lenet5(nn.Module):

    def __init__(self):
        super(Lenet5,self).__init__()

        self.conv_unit = nn.Sequential(
            # x :[b,3,32,32] => [b,6,]
            nn.Conv2d(3,6,5,1),  #卷积层
            #subsamping  池化层
            nn.AvgPool2d(kernel_size=2,stride=2,padding=0),
            #
            nn.Conv2d(6,16,5,1,0),
            nn.AvgPool2d(kernel_size=2,stride=2,padding=0)
        )
        #flatten
        #fc_unit
        self.fc_unit = nn.Sequential(
            nn.Linear(16*5*5,120),
            nn.ReLU(),
            nn.Linear(120,84),
            nn.ReLU(),
            nn.Linear(84,10)
        )

        # self.criten = nn.CrossEntropyLoss()

    def forward(self,x):
        bachsz = x.size(0) #获取样本数量
        x = self.conv_unit(x)
        x = x.view(bachsz,16*5*5)
        logits = self.fc_unit(x)  #获取输出标签
        return logits

运行测试

python 复制代码
   device  = torch.device('cuda') #使用gpu运行
    model = Lenet5().to(device)  #实例化网络
    criten = nn.CrossEntropyLoss().to(device)  #使用交叉熵
    optimizer = optim.Adam(model.parameters(),lr=1e-3)  #采用Adam及逆行优化参数
    for epoch in range(1000):
        for batchidx,(x,lable) in enumerate(cifar_train):
            x,lable = x.to(device),lable.to(device)
            logits = model(x)  #获得预测输出标签值
            loss = criten(logits,lable) #计算损失值
            optimizer.zero_grad() #将梯度归零
            loss.backward() #方向传播
            optimizer.step() #优化参数
        print(epoch,loss.item())
        total_correct = 0
        total_num = 0
        model.eval()  
        with torch.no_grad():  #表示不需要求梯度
            for x,label in cifar_test:
                x,label = x.to(device),label.to(device)
                logits = model(x)
                pred = logits.argmax(dim=1)  获取预测值
                total_correct += torch.eq(pred,label).float().sum().item()
                total_num += x.size(0)
            acc = total_correct /total_num
            print(epoch,acc)

网络图如下:

相关推荐
Lihua奏3 天前
从单核到多核:CPU为什么不能再只靠提频变快
深度学习
拾年2753 天前
大模型的"聪明"从哪来?聊聊 AI 数据集的那些事儿
人工智能·深度学习·机器学习
饼干哥哥7 天前
开源Skills|搭建亚马逊动态关键词库系统,每天抓SSS级机会词
人工智能·深度学习·数据分析
武子康9 天前
调查研究-191 SenseVoice 不只是 ASR:把语音从“转文字“升级成“理解状态“
人工智能·深度学习·openai
武子康10 天前
调查研究-189 Kronos 调研:金融 K 线基础模型,是真突破,还是量化圈的新玩具?
人工智能·深度学习·openai
xiao5kou4chang6kai416 天前
MATLAB机器学习、深度学习--从数据预处理到模型训练
深度学习·机器学习·matlab·数据预处理
renhongxia116 天前
世界模型作为AGI落地底层底座的作用
人工智能·深度学习·生成对抗网络·自然语言处理·知识图谱·agi
计算机科研狗@OUC16 天前
(cvpr26) AIMDepth: Asymmetric Image-Event Mamba for Monocular Depth Estimation
人工智能·深度学习·计算机视觉
β添砖java16 天前
深度学习(22)网络中的网络NiN
人工智能·深度学习
Kobebryant-Manba16 天前
深度学习时候d2l报错和使用问题
人工智能·深度学习