【深度学习】卷积网络代码实战ResNet

ResNet (Residual Network) 是由微软研究院的何凯明等人在2015年提出的一种深度卷积神经网络结构。ResNet的设计目标是解决深层网络训练中的梯度消失和梯度爆炸问题,进一步提高网络的表现。下面是一个ResNet模型实现,使用PyTorch框架来展示如何实现基本的ResNet结构。这个例子包括了一个基本的残差块(Residual Block)以及ResNet-18的实现,代码结构分为model.py(模型文件)和train.py(训练文件)。

model.py

首先,我们导入所需要的包

python 复制代码
import torch
from torch import nn
from torch.nn import functional as F

然后,定义Resnet Block(ResBlk)类。

python 复制代码
class ResBlk(nn.Module):
    def __init__(self):
        super(ResBlk, self).__init__()
        self.conv1 = nn.Conv2d(ch_in, ch_out, kernel_size=3, stride=1, padding=1)
        self.bn1 = nn.BatchNorm2d(ch_out)
        self.conv2 = nn.Conv2d(ch_out, ch_out, kernel_size=3, stride=1, padding=1)
        self.bn2 = nn.BatchNorm2d(ch_out)

        self.extra = nn.Sequential()
        if ch_out != ch_in
            self.extra = nn.Sequential(
                nn.Conv2d(ch_in, ch_out, kernel_size=3, stride=1)
                nn.BatchNorm2d(ch_out)
            )

    def forward(self, x):
        out = F.relu(self.bn1(self.conv1(x)))
        out = F.relu(self.bn2(self.conv2(x)))
        out = self.extra(x) + out
        return out

最后,根据ResNet18的结构对ResNet Block进行堆叠。

python 复制代码
class Resnet18(nn.Module):
    def __init__(self):
        super(Resnet18, self).__init__()
        self.conv1 = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1)
            nn.BatchNorm2d(64)
        )
        self.blk1 = ResBlk(64, 128)
        self.blk2 = ResBlk(128, 256)
        self.blk3 = ResBlk(256, 512)
        self.blk4 = ResBlk(512, 1024)
        self.outlayer = nn.Linear(512, 10)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        x = self.blk1(x)
        x = self.blk2(x)
        x = self.blk3(x)
        x = self.blk4(x)
        
        # print('after conv1:', x.shape)
        x = F.adaptive_avg_pool2d(x, [1,1])
        x = x.view(x.size(0), -1)
        x = self.outlayer(x)
        return x

其中,在网络结构搭建过程中,需要用到中间阶段的图片参数,用下述测试过程求得。

python 复制代码
def main():
    tmp = torch.randn(2, 3, 32, 32)
    out = blk(tmp)
    print('block', out.shape)
    
    x = torch.randn(2, 3, 32, 32)
    model = ResNet18()
    out = model(x)
    print('resnet:', out.shape)

train.py

首先,导入所需要的包

python 复制代码
import torch
from torchvision import datasets
from torchvision import transforms
from torch import nn, optimizer

然后,定义main()函数

python 复制代码
def main():
    batchsz = 32
    cifar_train = datasets.CIFAR10('cifar', True, transform=transforms.Compose([
        transforms.Resize((32, 32)),
        transforms.ToTensor()
        ]), download=True)
    cifar_train = DataLoader(cifar_train, batch_size=batchsz, shuffle=True)
    cifar_test = datasets.CIFAR10('cifar', False, transform=transforms.Compose([
        transforms.Resize((32, 32)),
        transforms.ToTensor()
        ]), download=True)
    cifar_test = DataLoader(cifar_test, batch_size=batchsz, shuffle=True)
 
    x, label = iter(cifar_train).next()
    print('x:', x.shape, 'label:', label.shape)
    
    device = torch.device('cuda')
    model = ResNet18().to(device)
    criteon = nn.CrossEntropyLoss()
    optimizer = optim.Adam(model.parameters(), lr=1e-3)
    print(model)
 
    for epoch in range(100):
        for batchidx, (x, label) in enumerate(cifar_train):
            x, label = x.to(device), label.to(device)
            logits = model(x)
            loss = criteon(logitsm label)
    
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
    print(loss.item())
 
 
    with torch.no_grad():
        total_correct = 0
        total_num = 0
        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).floot().sum().item()
            total_num += x.size(0)
 
        acc = total_correct / total_num
        print(epoch, acc)
相关推荐
傻啦嘿哟3 小时前
某短视频平台视频爬虫实战:抓取推荐流视频信息,绕过反爬的3种技巧
开发语言·爬虫·python
迷迭香yy3 小时前
集合竞价数据挖掘实战:用Python构建开盘信号识别系统
人工智能·python·数据挖掘
AI人工智能+5 小时前
一种基于深度学习技术的高精度医疗机构执业许可证识别系统,构建了一套基于深度神经网络的端到端智能识别系统,为医疗行业提
深度学习·ocr·医疗机构执业许可证识别
硅谷秋水5 小时前
EgoSteer:一种基于第一人称视角视频、实现可控灵巧操作的全栈系统
深度学习·机器学习·语言模型·机器人·音视频
李昊哲小课5 小时前
fastapi sse websocket 奶茶店实时订单看板
人工智能·python·websocket·网络协议·fastapi·sse
AI街潜水的八角6 小时前
基于YOLO26交通标志检测系统1:交通标志检测数据集说明(含下载链接)
深度学习·神经网络
aiblog7 小时前
深度学习中“Transformer”怎么翻译为中文?
人工智能·深度学习·transformer
2401_844582958 小时前
工具包:软件架构设计的实用技巧与经验分享
python
RFID固定资产管理系统8 小时前
适配媒体行业的固定资产管理软件有哪些功能与核心优势
大数据·人工智能·python·媒体
AndrewHZ8 小时前
【LLM技术全景】阶段总结:技术原理篇核心知识回顾
人工智能·深度学习·算法·语言模型·大模型·llm·芯片开发