一起深度学习

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)

网络图如下:

相关推荐
wumingxiaoyao13 小时前
从 0 开始学 AI:第 2 课,AI、机器学习、深度学习和大模型是什么关系?
人工智能·深度学习·机器学习·ai·大模型·llm
weixin_4000056013 小时前
Vision-Language-Action:LMDrive双损失函数训练模块与 LangAuto 基准评测框架
人工智能·深度学习·算法·机器学习·自动驾驶
bandaoyu14 小时前
大模型训练并行技术理解-DP/TP/PP/SP/EP
深度学习
手写码匠14 小时前
手写 AI 上下文压缩系统:从零实现 Prompt 压缩与选择性上下文管理
人工智能·深度学习·算法·aigc
大鱼>17 小时前
推荐系统原理与实现:协同过滤/内容推荐/深度学习
人工智能·深度学习
天一生水water18 小时前
注意力机制与transformer 的关系与区别
人工智能·深度学习·transformer
AI街潜水的八角18 小时前
口罩检测和识别2:基于深度学习YOLO26神经网络实现口罩检测和识别(含训练代码和数据集)
人工智能·深度学习·神经网络
weixin_4000056019 小时前
RL-frenet-trajectory-planning-in-CARLA
人工智能·深度学习·算法·机器学习·自动驾驶
蒟蒻的贤19 小时前
python搭建MiniDL
开发语言·python·深度学习
霖大侠21 小时前
Decoupled and Reusable Adaptation for Efficient Cross-Modal Transfer
人工智能·深度学习·算法·机器学习·transformer