Pytorch之经典神经网络CNN(三) —— AlexNet(CIFAR-10) (LRN)

article/2025/9/15 2:35:47

2012年 多伦多大学Hinton提出的

 

AlexNet

AlexNet是第一个large-scale CNN, 从AlexNet之后CNN开始变得火了起来

 

贡献是提出了用多层最小卷积叠加来替换单个大卷积

AlexNet首次引入了dropout

AlexNet 该模型一共分为八层,5个卷积层, 以及3个全连接层 (注意这个8层是没算pooling层的)

 

https://cloud.tencent.com/developer/article/1575745

 

这里我们主要写模型,数据加载、训练等类似的步骤就直接用LeNet5的了

虽然论⽂中AlexNet使⽤ImageNet数据集,但因为ImageNet数据集训练时间较⻓,我们仍⽤CIFAR-10数据集来演⽰AlexNet。但用transforms.Resize([227, 227])把它拉到[227,227]上,但是这么做会让图片有点失真的

 

nn.ReLU(inplace=True)中inplace的作用

inplace-选择是否进行覆盖运算

nn.ReLU(inplace=True) 的意思就是对从上层网络Conv2d中传递下来的tensor直接进行修改,这样能够节省运算内存,不用多存储其他变量。否则就需要花费内存去多存储一个变量

 

nn.Dropout()

nn.Dropout(p), 默认p=0.5

Dropout的目的是防止过拟合

dropout层不会影响模型的shape

 

 

因为输入数据是[3,227,227], 我的4G显存的GPU只能容纳batch_size=32,再大就爆了

import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import torch.utils.data.dataloader as dataloader
import pdb
import os
from torchvision.transforms import ToPILImage
import matplotlib.pyplot as pltclass AlexNet(nn.Module):def __init__(self):super(AlexNet, self).__init__()self.features = nn.Sequential(# x的输入: [b,3,227,227]  3是彩色图片三通道nn.Conv2d(3, 96, kernel_size=(11,11), stride=4, padding=1),#[b,96,55,55]nn.ReLU(inplace=True),# [b,96,55,55]nn.MaxPool2d(kernel_size=(3,3), stride=2),# [b,96,27,27]nn.Conv2d(96, 256, kernel_size=(5,5), stride=1, padding=2),# [b,256,27,27]nn.ReLU(inplace=True),# [b,256,27,27]nn.MaxPool2d(kernel_size=(3,3), stride=2),#[b,256,13,13]nn.Conv2d(256, 384, kernel_size=(3,3), stride=1, padding=1),# [b,384,13,13]nn.ReLU(inplace=True),# [b,384,13,13]nn.Conv2d(384, 384, kernel_size=(3,3), stride=1, padding=1),# [b,384,13,13]nn.ReLU(inplace=True),# [b,384,13,13]nn.Conv2d(384, 256, kernel_size=(3,3), padding=1),# [b,256,13,13]nn.ReLU(inplace=True),# [b,256,13,13]nn.MaxPool2d(kernel_size=(3,3), stride=2),# [b,256,6,6])self.classifier = nn.Sequential(nn.Dropout(),nn.Linear(256 * 6 * 6, 4096),nn.ReLU(inplace=True),nn.Dropout(),nn.Linear(4096, 4096),nn.ReLU(inplace=True),nn.Linear(4096, 10),)def forward(self, x):x = self.features(x)x = x.view(x.size(0), -1)x = self.classifier(x)return xtransform = transforms.Compose([transforms.Resize([227, 227]),transforms.ToTensor(),transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]
)batch_size = 32
train_set = torchvision.datasets.CIFAR10(root="dataset/",download=True,train=True,transform=transform
)train_loader = dataloader.DataLoader(dataset=train_set,batch_size=batch_size,shuffle=False
)test_set = torchvision.datasets.CIFAR10(root="dataset/",download=True,train=False,transform=transform
)
test_loader = dataloader.DataLoader(dataset=test_set,batch_size=batch_size,shuffle=True
)device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = AlexNet()
model.to(device)lr = 1e-3
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=lr)show = ToPILImage()train_loss = []if os.path.isfile('params.pth'):model.load_state_dict(torch.load('params.pth'))print('load model parameters from params.pth')
else:for epoch in range(2):for i, (images, labels) in enumerate(train_loader):images = images.to(device)labels = labels.to(device)output = model(images)#output是[b,10]# print(output.shape)loss = criterion(output, labels)optimizer.zero_grad()loss.backward()optimizer.step()train_loss.append(loss)if i % 100 == 0:print('{} {}, Loss: {:.4f}'.format(epoch, i, loss.item()))print('Finished Training')torch.save(model.state_dict(), 'params.pth')print('model has been save into params.pth.')plt.plot(range(0,len(train_loss)), train_loss, color='blue')plt.legend(['value'], loc='upper right')plt.xlabel('step')plt.ylabel('value')plt.show()with torch.no_grad():correct = 0total = 0for (images, labels) in test_loader:images, labels = images.to(device), labels.to(device)output = model(images)_, predicted = torch.max(output.data, 1)total += labels.size(0)#pdb.set_trace()correct += (predicted == labels).sum().item()print("The accuracy of total {} images: {}%".format(total, 100 * correct / total))

 

 

LRN(local response normalization)局部响应标准化

LRN函数类似DROPOUT和数据增强作为relu激励之后防止数据过拟合而提出的一种处理方法。这个函数很少使用,基本上被类似DROPOUT这样的方法取代,见最早的出处AlexNet论文对它的定义

 

 


http://chatgpt.dhexx.cn/article/h8wZ5LlG.shtml

相关文章

tf.nn.lrn() 局部响应归一化函数

背景文档 1、首先先了解一下 什么是过拟合和欠拟合?by Panda.X 2、下面简单说一下LRN,全称Local Response Normalization (局部响应归一化函数),是一种防止过拟合的方法,一般在激活层之后使用。这个函数很…

LRN层的实现

版权声明:本文为卜居原创文章,未经博主允许不得转载。卜居博客地址:http://blog.csdn.net/kkk584520 LRN全称为Local Response Normalization,即局部响应归一化层,具体实现在CAFFE_ROOT/src/caffe/layers/lrn_layer.cp…

简谈caffe中的LRN层

昨日面试,被问道BN层和LRN层,一直以来用的都是bn,所以当时对LRN只剩下点印象,事后弥补了一下这边知识点的不足,浅谈自己对LR&#xff…

LRN(Local Response Normalization)局部归一化分析

其中LRN的公式如下: 论文中说 Denoting by aix,y the activity of a neuron computed by applying kernel i at position (x, y) and then applying the ReLU nonlinearity, the response-normalized activity bix,y is given by the expression LRN是用在激活之后…

LRN学习笔记

LRN(Local Response Normalization) 作用:将不同卷积核RELU后的feature归一化,平滑处理,能增加泛化能力。 原因:生物方面,玄学 Alexnet提出 公式: 其中i代表第i个卷积核 a x , y i , 表 示 第…

LRN(局部响应归一化)

原理: LRN层模仿了生物神经系统的“侧抑制”机制,对局部神经元的活动创建竞争环境,使得其中响应比较大的值变得相对更大,并抑制其他反馈较小的神经元,增强模型的泛化能力。 LRN对于ReLU这种没有上限边界的激活函数会比…

LRN局部响应标准化

全称:local response normalization最早来源于论文AlexNet中提到的:i:代表下标,你要计算像素值的下标,从0计算起 j:平方累加索引,代表从j~i的像素值平方求和 x,y:像素的位…

tensorflow下的局部响应归一化函数tf.nn.lrn

1、其中LRN就是局部响应归一化: 这个技术主要是深度学习训练时的一种提高准确度的技术方法。其中caffe、tensorflow等里面是很常见的方法,其跟激活函数是有区别的,LRN一般是在激活、池化后进行的一中处理方法。 AlexNet将LeNet的思想发扬光大…

局部响应归一化(Local Response Normalization,LRN)和批量归一化(Batch Normalization,BN)的区别

为什么要归一化? 归一化已成为深度神经网络中的一个重要步骤,它可以弥补ReLU、ELU等激活函数无界性的问题。有了这些激活函数,输出层就不会被限制在一个有限的范围内(比如tanh的 [ − 1 , 1 ] [-1,1] [−1,1]),而是可以根据训练需…

LRN 局部响应归一化层(Local Response Normalization)

局部响应归一化层(Local Response Normalization) 局部响应归一化层简称LRN,是在深度学习中提高准确度的技术方法。一般是在激活、池化后进行的一中处理方法,因在Alexnet中运用到,故做一下整理。 为什么要引入LRN层&a…

AlexNet中的LRN(Local Response Normalization)

神经网络初学者,没有什么理论基础,偶然看到个ImageNet,就准备从其入手,先弄懂每层的含义,其中这个LRN层真是让人百思不得其解,搜索了下,给出的介绍比较少。为什么会比较少呢,搜索到最…

Alexnet LRN层和conv2局部连接

LRN(local response norm)局部归一 AlexNet本文出自NIPS2012,作者是大神Alex Krizhevsky,属于多伦多大学Hinton组。当年取得了ImageNet最好成绩,也是在那年之后,更多的更深的神经网路被提出,比…

tensorflow中的lrn函数详解

LRN函数类似DROPOUT和数据增强作为relu激励之后防止数据过拟合而提出的一种处理方法,全称是 local response normalization--局部响应标准化。这个函数很少使用,基本上被类似DROPOUT这样的方法取代,具体原理还是值得一看的 函数原型 def lrn(input, de…

CNN中的LRN层

LRN层是按下述公式计算的:(用处不大 可被dropout normalization替代) 转自:https://blog.csdn.net/searobbers_duck/article/details/51645941

ImageNet 中的 LRN

LRN(Local Response Normalization) LRN 神经网络初学者,没有什么理论基础,偶然看到个ImageNet,就准备从其入手,先弄懂每层的含义,其中这个LRN层真是让人百思不得其解,搜索了下&am…

LRN局部响应归一化

这个技术主要是深度学习训练时的一种提高准确度的技术方法。其中caffe、tensorflow等里面是很常见的方法,其跟激活函数是有区别的,LRN一般是在激活、池化后进行的一中处理方法。   AlexNet将LeNet的思想发扬光大,把CNN的基本原理应用到了很…

深度神经网络中的局部响应归一化LRN简介及实现

Alex、Hinton等人在2012年的NIPS论文《ImageNet Classification with Deep Convolutional Neural Networks》中将LRN应用于深度神经网络中(AlexNet)。论文见:http://www.cs.toronto.edu/~hinton/absps/imagenet.pdf ,截图如下: 公式解释&…

LRN

发展时间点 局部响应归一化这个方法流行于2012年的 AlexNet网络,它将这种方法付诸实践,验证了它的可行性。在caffe框架和tensorflow框架中,这都是经常和卷积、池化配合使用的方法。 作用时间点:LRN一般是在激活、池化后进行的一中…

LRN (Local Response Normalization,即局部响应归一化层)

LRN (Local Response Normalization,即局部响应归一化层) (一)先看看归一化吧 什么是归一化? 归一化化是归纳统一样本的统计分布性。就是要把你需要处理的数据经过处理后(通过某种算法)限制在你需要的一定范…

详解LRN(local response normalization--局部响应标准化)缓解过拟合

局部响应归一化层(Local Response Normalization) LRN全称为Local Response Normalization,即局部响应归一化层,LRN函数类似Dropout和数据增强作为relu激活函数之后防止数据过拟合而提出的一种处理方法。这个函数很少使用&#xf…