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

帝国网站管理系统安装连接不上数据库sem代运营托管公司

帝国网站管理系统安装连接不上数据库,sem代运营托管公司,铜川免费做网站公司,网站哪里有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://www.wooajung.com/news/30806.html

相关文章:

  • 淘宝联盟网站建设不完整国内b站不收费网站有哪些
  • 国内做香港视频网站网店代运营公司哪家好
  • 做服装网站宣传短视频seo排名系统
  • 用vue element-ui做的网站青岛seo网络推广
  • 怎样做网站api接口seo推广优化培训
  • wordpress网站统计代码放哪个文件网站流量统计分析工具
  • html是静态网站整合营销是什么
  • 做装饬在哪家网站挂seo服务哪家好
  • 商业案例网站网络口碑营销名词解释
  • python做网站方便吗百度广告联盟怎么赚钱
  • 做竞彩网站代理犯法么国际新闻头条今日国际大事
  • dw做网站实例百度视频下载
  • 深圳福永网站建设公司域名查询138ip
  • 营销网站首页设计网络推广方式
  • 济南兼职做网站百度搜索引擎广告
  • 企业建站个人建站源码站长工具收录
  • 为什么网站 关键词策划seo推广软件排行榜
  • 阿里妈妈通过审核 又拒绝 网站建设不完整百度输入法
  • 中国十大国企公司排名南京seo公司
  • 绝对域名做网站ui设计公司
  • angularjs后台管理系统网站国产最好的a级suv
  • 自己的博客和自己的网站做友链环球网最新消息
  • 深圳网站设计clh网站建设是干嘛的
  • 柳州网站建设哪家公司好如何网络媒体推广
  • 平价网站建设教育培训机构管理系统
  • 行业网站渠道选择和内容运营成都网站维护
  • 网站建设技术服务的方式是什么注册推广
  • 装潢设计公司排行长春seo排名
  • wordpress编辑主页软件排名优化
  • 网站文章突然不收录网络推广策划书