手写resnet18



import torch

from torch import nn
from torch.nn import functional as F

class ResBlk(nn.Module):
    def __init__(self,ch_in,ch_out,stride = 1):
        super(ResBlk, self).__init__()

        self.conv1 = nn.Conv2d(ch_in,ch_out,kernel_size=3,stride=stride,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=1,stride=stride),
                nn.BatchNorm2d(ch_out)
            )

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

#         short cut
        out = self.extra(x) + out
        return out



class ResNet18(nn.Module):
    def __init__(self):
        super(ResNet18, self).__init__()
        self.conv1 = nn.Sequential(
            nn.Conv2d(3,64,kernel_size=3,stride=3,padding=0),
            nn.BatchNorm2d(64)
        )
        # flowed 4 blocks

        self.blk1 = ResBlk(64,128,stride=2)
        self.blk2 = ResBlk(128,256,stride=2)
        self.blk3 = ResBlk(256,512,stride=2)
        self.blk4 = ResBlk(512,512,stride=2)

        self.outlayer = nn.Linear(512*1*1,10)

    def forward(self,x):
        x = self.conv1(x)
        x = self.blk1(x)
        x = self.blk2(x)
        x = self.blk3(x)
        x = self.blk4(x)
        # print("after conv",x.shape)
        # [b,512,h,w] ==> [b,512,1,1]
        x = F.adaptive_avg_pool2d(x,[1,1])
        # print("after pooling",x.shape)
        x = x.view(x.size(0),-1)
        return self.outlayer(x)




if __name__ == '__main__':
    blk = ResBlk(64,128,2)

    tmp = torch.randn(2,64,32,32)
    out = blk(tmp)
    print(out.shape)

    x = torch.randn(2,3,32,32)
    model = ResNet18()
    out = model(x)
    print(out.shape)

在下面代码中训练

import torch
from torch import nn


import torchvision
from torchvision import datasets



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,kernel_size=5,stride=1,padding=0),
            nn.AvgPool2d(kernel_size=2,stride=2,padding=0),

            nn.Conv2d(6,16,kernel_size=5,stride=1,padding=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)
        )

        # 使用交叉熵损失  softmax和loss操作统一给这个函数了
        # self.crition = nn.CrossEntropyLoss()
#         x:[b,3,32,32]
#         tmp = torch.randn(2,3,32,32)
#         out = self.conv_unit(tmp)
#         print(out.shape)
    def forward(self,x):
        # [b,3,32,32,] => [b,16,5,5]
        batchsz = x.size(0)
        x = self.conv_unit(x)
#         [b,16,5,5] =>[b,16 * 5 * 5]
        x= x.view(batchsz,-1)
        # [b, 16 * 5 * 5] => [b,10]
        logits = self.fc_unit(x)
        return logits

from torchvision import  transforms
from torch.utils.data import DataLoader

from ResBlk import ResNet18

def main():
    batchsz = 32
    cifar_train = datasets.CIFAR10('cifar',True,transform=transforms.Compose(
        [
            transforms.Resize((32,32)),
            transforms.ToTensor(),
            transforms.Normalize(mean=[0.485,0.456,0.406],
                                 std=[0.229,0.224,0.225])
        ]
    ),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(),
            transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                 std=[0.229, 0.224, 0.225])
        ]
    ),download=True,)

    cifar_test = DataLoader(cifar_test,batch_size=batchsz,shuffle=False)

    x,label = iter(cifar_train).next()
    print("x",x.shape," label",label.shape)

    device = torch.device("cuda")
    # net = Lenet5()
    net = ResNet18()
    net.to(device)

    # 损失函数  包含softmax和 loss操作
    crition = nn.CrossEntropyLoss()

    optimizer = torch.optim.Adam(net.parameters(),lr=1e-3)


    for epoch in range(1000):
        net.train()
        for batchidx,(x,label) in enumerate(cifar_train):
            x,label = x.to(device),label.to(device)

            # x: [b,10] label:[b]
            x = net(x)
            loss = crition(x,label)
            # 梯度清零
            optimizer.zero_grad()
            # 计算梯度值
            loss.backward()

            # 将梯度值代入损失函数进行计算,并往下迭代一步  更新到weight
            optimizer.step()
        #           转化为numpy
        print(epoch,loss.item())

#         test
        net.eval()
        with torch.no_grad():
            total_correct = 0
            total_num = 0
            for x,label in cifar_test:
                x,label = x.to(device),label.to(device)
                # [b,10]
                logits = net(x)
                # [b]
                pred = logits.argmax(dim=1)

                total_correct+=torch.eq(pred,label).float().sum().item()
                total_num+=x.size(0)
            print("epoch ",epoch,"  acc ",total_correct/total_num)


    torch.save(net,'result.pt')
















if __name__ == '__main__':
    main()

    # net = Lenet5()
    # tmp = torch.randn(2,3,32,32)
    # out = net(tmp)
    # # [2,10]
    # print(out.shape)



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
手写数字识别是一种将手写数字图像转化为数字标签的任务。ResNet,即深度残差网络,是一种用于图像分类和目标识别的深度学习模型。 ResNet模型的基本结构是通过残差单元来构建的。相比于传统的深度神经网络,ResNet采用了跳跃连接的方法,解决了深层网络难以训练的问题。在ResNet中,输入数据经过多个残差单元,其中每个残差单元由两个卷积层和一个恒等映射组成。卷积层用于学习输入数据的特征,而恒等映射则通过跳跃连接将输入数据直接传递给后续的层。这种设计使得ResNet在训练过程中能够更好地优化网络权重,提高了模型的准确性。 对于手写数字识别任务,可以使用ResNet模型来进行训练和测试。首先,需要准备一个手写数字的数据集,包含大量的手写数字图像和对应的标签。可以使用MNIST数据集作为一个示例。然后,可以使用深度学习框架如TensorFlow或PyTorch来搭建ResNet模型,并加载训练数据进行训练。 在模型训练过程中,需要定义损失函数和优化器。对于手写数字识别任务,常用的损失函数是交叉熵损失函数,优化器可以选择Adam或SGD等算法。在每个训练迭代中,通过前向传播计算损失,并利用反向传播算法更新网络权重。可以设置合适的学习率和训练轮数来优化模型。 训练完成后,可以使用测试数据对模型进行评估,计算模型的准确率或其他性能指标。最后,可以使用已经训练好的ResNet模型对未知的手写数字图像进行预测,从而实现手写数字的识别。 总而言之,手写数字识别ResNet模型是一种利用深度残差网络来训练和识别手写数字的系统。通过合适的数据集、损失函数和优化器,可以训练一个准确度较高的模型用于手写数字的识别。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值