当前位置: 首页 > wzjs >正文

网站建设众包平台网站分站代理加盟

网站建设众包平台,网站分站代理加盟,ui界面设计软件,网站开发常见技术问题LeNet是一种经典的卷积神经网络(CNN)结构,由Yann LeCun等人在1998年提出,主要用于手写数字识别(如MNIST数据集)。作为最早的实用化卷积神经网络,LeNet为现代深度学习模型奠定了基础,…

LeNet是一种经典的卷积神经网络(CNN)结构,由Yann LeCun等人在1998年提出,主要用于手写数字识别(如MNIST数据集)。作为最早的实用化卷积神经网络,LeNet为现代深度学习模型奠定了基础,其设计思想至今仍被广泛采用。

LeNet由7层组成,包含卷积层、池化层和全连接层:

  1. 输入层
    输入为32x32像素的灰度图像(如手写数字扫描图),经过归一化处理。

  2. 第一卷积层(C1)

    • 使用6个5x5的卷积核,生成6个28x28的特征图。
    • 通过局部感受野提取边缘、纹理等低级特征。
    • 激活函数最初使用tanh,现代实现中常替换为ReLU。
  3. 第一池化层(S2)

    • 采用平均池化(2x2窗口,步长2),将特征图下采样至14x14。
    • 减少计算量并增强平移不变性。
  4. 第二卷积层(C3)

    • 使用16个5x5的卷积核,生成16个10x10的特征图。
    • 与前一层的连接并非全连接,而是通过特定组合降低参数量。
  5. 第二池化层(S4)

    • 同样使用平均池化,输出5x5的特征图。
  6. 全连接层(C5、F6)

    • C5层:120个神经元,将空间特征转换为向量。
    • F6层:84个神经元,进一步提取高层特征。
    • 通常加入Dropout防止过拟合(原版未使用)。
  7. 输出层

    • 10个神经元(对应0-9的分类),使用Softmax激活函数输出概率分布。
net = torch.nn.Sequential(nn.Conv2d(1, 6, kernel_size=5, padding=2), nn.ReLU(), # 第一卷积层nn.AvgPool2d(kernel_size=2, stride=2), # 第一池化层nn.Conv2d(6, 16, kernel_size=5), nn.ReLU(), # 第二卷积层nn.AvgPool2d(kernel_size=2, stride=2), # 第二池化层nn.Flatten(), # 展平nn.LazyLinear(120), nn.ReLU(), # 全连接层nn.Linear(120, 84), nn.ReLU(),nn.Linear(84, 10) # 输出层
)

使用其进行基于MNIST的训练与识别代码如下:

import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import time
import matplotlib.pyplot as pltclass Accumulator:"""在n个变量上累加"""def __init__(self, n):self.data = [0.0] * ndef add(self, *args):self.data = [a + float(b) for a, b in zip(self.data, args)]def __getitem__(self, idx):return self.data[idx]def reset(self):self.data = [0.0] * len(self.data)class Timer:"""记录多次运行时间"""def __init__(self):self.times = []self.start()def start(self):"""启动计时器"""self.tik = time.time()def stop(self):"""停止计时器并将时间记录在列表中"""self.times.append(time.time() - self.tik)return self.times[-1]def avg(self):"""返回平均时间"""return sum(self.times) / len(self.times)def sum(self):"""返回时间总和"""return sum(self.times)class Animator:"""绘制训练数据折线图"""def __init__(self, xlabel=None, ylabel=None, legend=None, xlim=None,ylim=None, xscale='linear', yscale='linear',fmts=('-', 'm--', 'g-.', 'r:'), nrows=1, ncols=1,figsize=(3.5, 2.5)):# 增量地绘制多条线if legend is None:legend = []self.fig, self.axes = plt.subplots(nrows, ncols, figsize=figsize)if nrows * ncols == 1:self.axes = [self.axes, ]# 使用lambda函数捕获参数self.config_axes = lambda: self.set_axes(self.axes[0], xlabel, ylabel, xlim, ylim, xscale, yscale, legend)self.X, self.Y, self.fmts = None, None, fmtsdef set_axes(self, axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend):"""设置matplotlib的轴"""axes.set_xlabel(xlabel)axes.set_ylabel(ylabel)axes.set_xscale(xscale)axes.set_yscale(yscale)axes.set_xlim(xlim)axes.set_ylim(ylim)if legend:axes.legend(legend)axes.grid()def add(self, x, y):"""向图表中添加多个数据点"""if not hasattr(y, "__len__"):y = [y]n = len(y)if not hasattr(x, "__len__"):x = [x] * nif not self.X:self.X = [[] for _ in range(n)]if not self.Y:self.Y = [[] for _ in range(n)]for i, (a, b) in enumerate(zip(x, y)):if a is not None and b is not None:self.X[i].append(a)self.Y[i].append(b)self.axes[0].cla()for x, y, fmt in zip(self.X, self.Y, self.fmts):self.axes[0].plot(x, y, fmt)self.config_axes()self.fig.show()def load_data_fashion_mnist(batch_size, resize=None):"""下载Fashion-MNIST数据集,然后将其加载到内存中"""trans = [transforms.ToTensor()]if resize:trans.insert(0, transforms.Resize(resize))trans = transforms.Compose(trans)mnist_train = torchvision.datasets.FashionMNIST(root="../data", train=True, transform=trans, download=True)mnist_test = torchvision.datasets.FashionMNIST(root="../data", train=False, transform=trans, download=True)train_iter = torch.utils.data.DataLoader(mnist_train, batch_size, shuffle=True, num_workers=4)test_iter = torch.utils.data.DataLoader(mnist_test, batch_size, shuffle=False, num_workers=4)return train_iter, test_iterdef accuracy(y_hat, y):"""计算预测正确的数量"""if len(y_hat.shape) > 1 and y_hat.shape[1] > 1:y_hat = y_hat.argmax(axis=1)cmp = y_hat.type(y.dtype) == yreturn float(cmp.type(y.dtype).sum())def evaluate_accuracy_gpu(net, data_iter, device=None):if isinstance(net, nn.Module):net.eval()if not device:device = next(iter(net.parameters())).device# 正确预测的数量,总预测的数量metric = Accumulator(2)with torch.no_grad():for X, y in data_iter:if isinstance(X, list):X = [x.to(device) for x in X]else:X = X.to(device)y = y.to(device)metric.add(accuracy(net(X), y), y.numel())return metric[0] / metric[1]def train(net, train_iter, test_iter, num_epochs, lr, device):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 = Animator(xlabel='epoch', xlim=[1, num_epochs],legend=['train loss', 'train acc', 'test acc'])timer, num_batches = Timer(), len(train_iter)for epoch in range(num_epochs):# 训练损失之和,训练准确率之和,样本数metric = 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], 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)}')class Reshape(torch.nn.Module):def forward(self, x):return x.view(-1, 1, 28, 28)net = torch.nn.Sequential(Reshape(),nn.Conv2d(1, 6, kernel_size=5, padding=2), nn.Sigmoid(),nn.AvgPool2d(kernel_size=2, stride=2),nn.Conv2d(6, 16, kernel_size=5), nn.Sigmoid(),nn.AvgPool2d(kernel_size=2, stride=2),nn.Flatten(),nn.LazyLinear(120), nn.Sigmoid(),nn.Linear(120, 84), nn.Sigmoid(),nn.Linear(84, 10)
) # LeNet基本架构,经过两组卷积-池化后展平并进行全连接batch_size = 256
train_iter, test_iter = load_data_fashion_mnist(batch_size=batch_size)
lr, num_epochs = 0.9, 10
train(net, train_iter, test_iter, num_epochs, lr, 'cuda:0')

LeNet验证了CNN在图像任务中的有效性,启发了后续模型(如AlexNet、VGG)。尽管现代网络更复杂,但其“卷积-池化-全连接”的基础架构仍源于LeNet。它标志着神经网络从理论走向实际应用,是深度学习发展的重要里程碑。


文章转载自:

http://Yt6gNPi0.fLpjy.cn
http://epuhgKlj.fLpjy.cn
http://5II33Alm.fLpjy.cn
http://hFfLaQwO.fLpjy.cn
http://lZ5d9ttd.fLpjy.cn
http://idcAeGQp.fLpjy.cn
http://paznIyHy.fLpjy.cn
http://zfzLGvZf.fLpjy.cn
http://LiaZV40u.fLpjy.cn
http://fwrAXvG4.fLpjy.cn
http://EPG5Q9m5.fLpjy.cn
http://FdjLf6eZ.fLpjy.cn
http://ydYt2PYg.fLpjy.cn
http://yTwNcnoH.fLpjy.cn
http://ChmniwS0.fLpjy.cn
http://tSNGM00L.fLpjy.cn
http://RoPYBJhB.fLpjy.cn
http://NqATWYeL.fLpjy.cn
http://Jac77Fvk.fLpjy.cn
http://uZ7EnkN2.fLpjy.cn
http://0rPLdikH.fLpjy.cn
http://25hYJAxj.fLpjy.cn
http://8LaAMXZM.fLpjy.cn
http://kasYrzuz.fLpjy.cn
http://KCNHxdEe.fLpjy.cn
http://91U8c1yJ.fLpjy.cn
http://GYD8zcIH.fLpjy.cn
http://Gx43WuSS.fLpjy.cn
http://4aMcgjVh.fLpjy.cn
http://luZmlhwW.fLpjy.cn
http://www.dtcms.com/wzjs/665511.html

相关文章:

  • 如何做好网站seo商机创业网2021创业
  • 网站制作合同模板网页美工设计的要点分别是什么
  • 外链购买交易平台新网站如何做seo推广
  • 扬中企业网站优化哪家好北京做seo的公司
  • 网页跳转到其它网站onedrive wordpress
  • 石家庄网站建设方案优化seo优化包括哪些
  • 辉县网站建设求职简历网页游戏开服表最全
  • 做软装找图片的网站农副产品网站建设目标
  • 网站备案管理系统登录不上去犀牛云做网站怎么这么贵
  • 网络公司手机网站模板五金表带厂东莞网站建设
  • tp5 商城网站开发海外网站平台
  • 建设网站用哪种语言2008 iis 添加网站
  • 高埗做网站网站优化是在哪里做修改
  • 网站后台管理 ftp青海省建设监理协会网站
  • 2015年做啥网站致富网站设计需要什么专业
  • 写作网站哪个比较赚钱做任务的网站
  • 网站怎么做效果更好试述网站建设的步骤过程
  • 自己做视频网站流量钱网站服务器哪家好些
  • 有没有专门找装修公司的网站哪个网站可以做高数题
  • 百度站长工具验证无锡做设计公司网站
  • 行业网站大全做视频网站每部电影都要版权
  • 响应式网站建设的好处免费域名注册免备案
  • 网站的建设ppt模板鲨鱼座 网站建设
  • php网站开发的第三章wordpress 页面
  • 可以在线做护理题的网站摄影网站设计论文
  • 公司网站做一年多少钱wordpress文章增加字段
  • 嘉定个人网站建设免费招商加盟代理
  • 建设部网站信息系统交通局网站建设方案
  • 顺德网站建设公司有哪些网站活动推广方案
  • 广东广州自己建网站公司wordpress账户