首页 > 其他分享 >LeNet卷积神经网络——pytorch版

LeNet卷积神经网络——pytorch版

时间:2023-08-06 14:44:24浏览次数:42  
标签:nn 卷积 metric iter pytorch train LeNet device net

import torch
from torch import nn
from d2l import torch as d2l

class Reshape(torch.nn.Module):
    def forward(self,x):
        # 批量大小默认,输出通道为1
        return x.view(-1,1,28,28)

net = torch.nn.Sequential(
    # 28+4-5+1=28输出通道为6
    Reshape(),nn.Conv2d(1,6,kernel_size=5,padding=2),nn.Sigmoid(),
    # 28/2=14通道是6
    nn.AvgPool2d(kernel_size=2,stride=2),
    # 14-5+1=10输出通道是16
    nn.Conv2d(6,16,kernel_size=5),nn.Sigmoid(),
    # 10/2=5通道是16
    nn.AvgPool2d(kernel_size=2,stride=2),nn.Flatten(),
    # 上面是卷积层,下面是两个隐藏层的多层感知机
    # 扁平化处理后16*5x5=400,输出通道120
    nn.Linear(16*5*5,120),nn.Sigmoid(),
    nn.Linear(120,84),nn.Sigmoid(),
    nn.Linear(84,10)
)

x = torch.rand(size=(1,1,28,28),dtype=torch.float32)
# Sequential中每一层做迭代
for layer in net:
    x = layer(x)
    print(layer.__class__.__name__,'output shape: \t',x.shape)


print('**********************************************************')
# LeNet在Fashion-MNIST数据集上的表现
batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size=batch_size)
def evaluate_accuracy_gpu(net,data_iter,device=None):
    """使用GPU计算模型在数据集上的精度"""
    if isinstance(net,torch.nn.Module):
        net.eval()
        if not device:
            # 如果没有指定device则查看第一个parameteres所在的device
            device = next(iter(net.parameters())).device
    # 定义一个累加器
    metric = d2l.Accumulator(2)
    for X,y in data_iter:
        if isinstance(X,list):
            # 如果是一个list则依次挪到device上
            X=[x.to(device) for x in X]
        else:
            X=X.to(device)
        # y也挪到设备上
        y=y.to(device)
        metric.add(d2l.accuracy(net(X),y),y.numel())
    # 分类正确的元素个数/整个y大小
    return metric[0]/metric[1]

def train_ch6(net, train_iter, test_iter, num_epochs, lr, device):
    """用GPU训练模型(在第六章定义)"""
    def init_weights(m):
        if type(m) == nn.Linear or type(m) == nn.Conv2d:
            # 使得方差限定在合适的范围内
            nn.init.xavier_uniform_(m.weight)
    net.apply(init_weights)
    print('training on', device)
    net.to(device)
    optimizer = torch.optim.SGD(net.parameters(), lr=lr)
    loss = nn.CrossEntropyLoss()
    # animator = d2l.Animator(xlabel='epoch', xlim=[1, num_epochs],
    #                         legend=['train loss', 'train acc', 'test acc'])
    timer, num_batches = d2l.Timer(), len(train_iter)
    for epoch in range(num_epochs):
        # 训练损失之和,训练准确率之和,样本数
        metric = d2l.Accumulator(3)
        net.train()
        for i, (X, y) in enumerate(train_iter):
            timer.start()
            optimizer.zero_grad()
            X, y = X.to(device), y.to(device)
            y_hat = net(X)
            l = loss(y_hat, y)
            l.backward()
            optimizer.step()
            with torch.no_grad():
                metric.add(l * X.shape[0], d2l.accuracy(y_hat, y), X.shape[0])
            timer.stop()
            train_l = metric[0] / metric[2]
            train_acc = metric[1] / metric[2]
            # if (i + 1) % (num_batches // 5) == 0 or i == num_batches - 1:
                # animator.add(epoch + (i + 1) / num_batches,
                #              (train_l, train_acc, None))
        test_acc = evaluate_accuracy_gpu(net, test_iter)
        # animator.add(epoch + 1, (None, None, test_acc))
    print(f'loss {train_l:.3f}, train acc {train_acc:.3f}, '
          f'test acc {test_acc:.3f}')
    print(f'{metric[2] * num_epochs / timer.sum():.1f} examples/sec '
          f'on {str(device)}')

if __name__ == '__main__':
    lr, num_epochs = 0.9, 10
    train_ch6(net, train_iter, test_iter, num_epochs, lr, d2l.try_gpu())

 

标签:nn,卷积,metric,iter,pytorch,train,LeNet,device,net
From: https://www.cnblogs.com/jinbb/p/17609405.html

相关文章

  • 实现二维卷积层
    importtorchfromtorchimportnnfromd2limporttorchasd2ldefcorr2d(x,k):"""计算二维互相关运算"""#获取卷积核的高和宽h,w=k.shape#输出的高和宽y=torch.zeros((x.shape[0]-h+1,x.shape[1]-w+1))foriinrange(y.shape[0......
  • (通俗易懂)可视化详解多通道 & 多通道输入输出卷积代码实现
    以前对多通道和多通道输入输出的卷积操作不理解,今天自己在草稿纸上画图推理了一遍,终于弄懂了。希望能帮助到大家。多通道可视化一通道的2x2矩阵torch.Size([2,2])相当于torch.Size([1,2,2]),是一通道的2x2矩阵二通道的2x2矩阵torch.Size([2,2,2])代表二通道的2x2矩阵,第一个2表......
  • 6.2 手写卷积类
    importtorchfromtorchimportnnfromd2limporttorchasd2lclassConv2D(nn.Module):def__init__(self,kernel_size):super().__init__()self.weight=nn.Parameter(torch.rand(kernel_size))#如kernel_size=(2,2),则随机初始化一个2x2的卷积......
  • CNN tflearn处理mnist图像识别代码解说——conv_2d参数解释,整个网络的训练,主要就是为
    官方参数解释:Convolution2Dtflearn.layers.conv.conv_2d(incoming,nb_filter,filter_size,strides=1,padding='same',activation='linear',bias=True,weights_init='uniform_scaling',bias_init='zeros',regularizer=None,wei......
  • 配置pytorch环境时出现的问题 Failed to load image Python extension
    安装了torch1.12.0+torchvision0.13.0+torchaudio0.12.0版本后,condainstallpytorch==1.12.0torchvision==0.13.0torchaudio==0.12.0cudatoolkit=11.3-cpytorch按照《动手学深度学习》输入 fromd2limporttorchasd2l命令,跳出警告UserWarning:Failed......
  • 动手深度学习pytorch 8-章
    1. 序列模型a)自回归模型对见过的数据建模b)马尔可夫模型c)因果关系2.单机多卡并行数据并行和模型并行:数据并行,将小批量分成n块,每个GPU拿到完整参数计算,性能更好。模型并行,将模型分成n块,每个GPU拿到一块模型计算前向和方向结果,用于单GPU放不下小批......
  • doubly block toeplitz matrix 在加速矩阵差卷积上的应用
    文档链接CNN的卷积是执行了\(w'_{i,j}=\sum\limits_{x,y}w_{i+x,j+y}\timesC_{x,y}\),有人认为每次平移卷积核,运算量很大,又是乘法又是加法。现在我们吧\(w_{x,y}\)展开形成一个\([n\timesm,1]\)的向量\(V\),然后构造一个大小为\([(n+1)\times(m+1),n\timesm]\)矩阵......
  • pytorch实现cnn&图像分类器
    1pytorch实现神经网络1.1定义网络从基类nn.Module继承过来,必须重载def__init__()和defforward()classNet(nn.Module):def__init__(self):#网络结构super(Net,self).__init__()#1inputimagechannel,6outputchannels,5x5squareco......
  • 卷积神经网络(LeNet)
    卷积神经网络(LeNet)卷积神经网络(LeNet)tensorflow..... pytorch实现LeNet5......
  • ubuntu系统conda下运行pytorch报错:ImportError: libopenblas.so.0: cannot open share
    如题:ubuntu系统conda下运行pytorch报错:ImportError:libopenblas.so.0:cannotopensharedobjectfile   网上找了一些资料,基本都是自己下载openblas源码进行编译,不过突然之间相当conda环境提供一定的编译好的lib环境,使用conda命令既可安装,于是按照这个思路再进行搜索......