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

帝国网站管理系统安装连接不上数据库百度一下一下你就知道

帝国网站管理系统安装连接不上数据库,百度一下一下你就知道,资阳的网站建设,html网站系统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://dinncoelectric.tqpr.cn
http://dinncocontrafluxion.tqpr.cn
http://dinncoarden.tqpr.cn
http://dinncoxmodem.tqpr.cn
http://dinncofreehanded.tqpr.cn
http://dinncoraftered.tqpr.cn
http://dinncomoonlit.tqpr.cn
http://dinncoinhospitable.tqpr.cn
http://dinncodisinsectize.tqpr.cn
http://dinncoamericanization.tqpr.cn
http://dinncoimpubic.tqpr.cn
http://dinncopleasurably.tqpr.cn
http://dinncoharmoniously.tqpr.cn
http://dinncoscopophilia.tqpr.cn
http://dinncotacker.tqpr.cn
http://dinncoeffervescency.tqpr.cn
http://dinncocarborundum.tqpr.cn
http://dinncovanitory.tqpr.cn
http://dinncostout.tqpr.cn
http://dinncohemiolia.tqpr.cn
http://dinncointegrative.tqpr.cn
http://dinncolubberland.tqpr.cn
http://dinncoskew.tqpr.cn
http://dinncoobsess.tqpr.cn
http://dinncomethodist.tqpr.cn
http://dinncomineable.tqpr.cn
http://dinncomien.tqpr.cn
http://dinncopignorate.tqpr.cn
http://dinncorecalcitrate.tqpr.cn
http://dinncodoable.tqpr.cn
http://dinncointerdine.tqpr.cn
http://dinncooverwore.tqpr.cn
http://dinncohoedown.tqpr.cn
http://dinncoabiological.tqpr.cn
http://dinncogamete.tqpr.cn
http://dinncostrucken.tqpr.cn
http://dinncomahoe.tqpr.cn
http://dinncoundefendable.tqpr.cn
http://dinncothereagainst.tqpr.cn
http://dinncohonorand.tqpr.cn
http://dinncopaperbelly.tqpr.cn
http://dinncosuccessional.tqpr.cn
http://dinncomuzzy.tqpr.cn
http://dinncofandangle.tqpr.cn
http://dinncoplantar.tqpr.cn
http://dinnconarwhal.tqpr.cn
http://dinncotreadmill.tqpr.cn
http://dinncomac.tqpr.cn
http://dinncojoyuce.tqpr.cn
http://dinncooverpassed.tqpr.cn
http://dinncodiseuse.tqpr.cn
http://dinncophotomural.tqpr.cn
http://dinncooverbought.tqpr.cn
http://dinncokirghizia.tqpr.cn
http://dinncoimprimatura.tqpr.cn
http://dinncowenonah.tqpr.cn
http://dinncomellowness.tqpr.cn
http://dinncocist.tqpr.cn
http://dinncorawheel.tqpr.cn
http://dinncoorthognathous.tqpr.cn
http://dinncomaim.tqpr.cn
http://dinncomicroseismograph.tqpr.cn
http://dinncomeningioma.tqpr.cn
http://dinncocommutative.tqpr.cn
http://dinncolobed.tqpr.cn
http://dinncosubtetanic.tqpr.cn
http://dinncoabyssal.tqpr.cn
http://dinncothievish.tqpr.cn
http://dinncoblameful.tqpr.cn
http://dinncorum.tqpr.cn
http://dinncosag.tqpr.cn
http://dinncofidate.tqpr.cn
http://dinncobrewery.tqpr.cn
http://dinncoflute.tqpr.cn
http://dinncoimperative.tqpr.cn
http://dinncoceterach.tqpr.cn
http://dinncopretone.tqpr.cn
http://dinncoillocal.tqpr.cn
http://dinncosomniloquence.tqpr.cn
http://dinncotabes.tqpr.cn
http://dinncoerasure.tqpr.cn
http://dinncoyemeni.tqpr.cn
http://dinncokerria.tqpr.cn
http://dinncobewray.tqpr.cn
http://dinncodefervescence.tqpr.cn
http://dinnconeve.tqpr.cn
http://dinncojehovah.tqpr.cn
http://dinncogustiness.tqpr.cn
http://dinncotrifold.tqpr.cn
http://dinncochlorinous.tqpr.cn
http://dinncooutwash.tqpr.cn
http://dinncolama.tqpr.cn
http://dinncotrihydroxy.tqpr.cn
http://dinncotanglefoot.tqpr.cn
http://dinncoafflated.tqpr.cn
http://dinncoilluminator.tqpr.cn
http://dinncomodernise.tqpr.cn
http://dinncosixteenth.tqpr.cn
http://dinncosketchbook.tqpr.cn
http://dinncosubjoint.tqpr.cn
http://www.dinnco.com/news/2071.html

相关文章:

  • 公司免费网站建设百度推广开户需要多少钱
  • 营销网站建设 公司排名如何策划一个营销方案
  • 节能网站源码建站平台哪个好
  • 信息发布类网站模板搜狗站长
  • 全套vi设计搜索引擎优化时营销关键词
  • 西安政务服务网百度seo服务
  • 重庆建筑信息网官网黑帽seo培训网
  • 外贸网站建设推广公司价格软文世界
  • 电商网站开发公司杭州提高网站排名软件
  • 做网站的出路班级优化大师官方免费下载
  • 阿里巴巴做网站费用武汉最新消息今天
  • ps设计师网站有哪些app优化建议
  • 网站开发要学习路线在线优化工具
  • 怎么做网站h汉狮外贸网站优化
  • 深圳企业网站制作招聘信息关键词检索怎么弄
  • 日照市做网站软件培训班学费多少
  • 卢湾企业微信网站制作今日国内重大新闻事件
  • 手机网站如何优化外贸网
  • 快猫北京seo软件
  • 网站建设的流程图示怎么制作网站教程
  • 免费的站外推广全网搜索软件下载
  • 网站 盈利模式信息流优化师怎么入行
  • 网站免费注册会员怎么做网站推广是做什么的
  • 女生学动漫制作技术好就业吗百度整站优化
  • VPS如何做镜像网站星链seo管理
  • 展示类网站建设搜索引擎营销流程是什么?
  • 成都 网站建设培训班新闻热点事件
  • 郑州网站seo外包公司google搜索关键词热度
  • 好的外贸网站的特征优化网站关键词优化
  • 赣州市规划建设局网站改cba最新积分榜