文化网站建设需要的功能,公司网站制作哪家公司好,广州安全教育平台登录,注册公司网站的步骤卷积神经网络LeNet
先上图#xff1a;LeNet的网络结构 卷积(6个5∗5的核)→降采样(池化)(2∗2的核#xff0c;步长2)→卷积(16个5∗5的核)→降采样(池化)(2∗2的核#xff0c;步长2)→全连接16∗5∗5→120→全连接120→84→全连接84→10\begin{matrix}卷积 \\ (6个5*5的核…卷积神经网络LeNet
先上图LeNet的网络结构
卷积(6个5∗5的核)→降采样(池化)(2∗2的核步长2)→卷积(16个5∗5的核)→降采样(池化)(2∗2的核步长2)→全连接16∗5∗5→120→全连接120→84→全连接84→10\begin{matrix}卷积 \\ (6个5*5的核) \end{matrix} \rightarrow \begin{matrix}降采样(池化) \\ (2*2的核步长2) \end{matrix}\rightarrow \begin{matrix}卷积 \\ (16个5*5的核) \end{matrix} \rightarrow \begin{matrix}降采样(池化) \\ (2*2的核步长2)\end{matrix}\rightarrow \\ \\ \begin{matrix}全连接 \\ 16*5*5\rightarrow120\end{matrix}\rightarrow \begin{matrix}全连接 \\ 120\rightarrow84\end{matrix}\rightarrow \begin{matrix}全连接 \\ 84\rightarrow10\end{matrix} 卷积(6个5∗5的核)→降采样(池化)(2∗2的核步长2)→卷积(16个5∗5的核)→降采样(池化)(2∗2的核步长2)→全连接16∗5∗5→120→全连接120→84→全连接84→10
LeNet分为卷积层块和全连接层块两个部分。
卷积层
卷积层块里的基本单位是卷积层后接最大池化层 卷积层用来识别图像里的空间模式如线条和物体局部之后的最大池化层则用来降低卷积层对位置的敏感性。卷积层块由两个这样的基本单位重复堆叠构成。
在卷积层块中每个卷积层都使用5×55\times 55×5的窗口并在输出上使用sigmoid激活函数。第一个卷积层输出通道数为6第二个卷积层输出通道数则增加到16。这是因为第二个卷积层比第一个卷积层的输入的高和宽要小所以增加输出通道使两个卷积层的参数尺寸类似。卷积层块的两个最大池化层的窗口形状均为2×22\times 22×2且步幅为2。由于池化窗口与步幅形状相同池化窗口在输入上每次滑动所覆盖的区域互不重叠。
全连接层
卷积层块的输出形状为(批量大小, 通道, 高, 宽)。 当卷积层块的输出传入全连接层块时全连接层块会将小批量中每个样本变平flatten。也就是说全连接层的输入形状将变成二维
其中第一维是小批量中的样本第二维是每个样本变平后的向量表示且向量长度为通道、高和宽的乘积。
全连接层块含3个全连接层。它们的输出个数分别是120、84和10其中10为输出的类别个数。
实现模型
下面通过Sequential类来实现LeNet模型。
import time
import torch
from torch import nn, optimdevice torch.device(cuda if torch.cuda.is_available() else cpu)class LeNet(nn.Module):def __init__(self):super(LeNet, self).__init__()self.conv nn.Sequential(nn.Conv2d(1, 6, 5), # in_channels, out_channels, kernel_sizenn.Sigmoid(),nn.MaxPool2d(2, 2), # kernel_size, stridenn.Conv2d(6, 16, 5),nn.Sigmoid(),nn.MaxPool2d(2, 2))self.fc nn.Sequential(nn.Linear(16*4*4, 120),nn.Sigmoid(),nn.Linear(120, 84),nn.Sigmoid(),nn.Linear(84, 10))def forward(self, img):feature self.conv(img)output self.fc(feature.view(img.shape[0], -1))return outputnet LeNet()
print(net)LeNet((conv): Sequential((0): Conv2d(1, 6, kernel_size(5, 5), stride(1, 1))(1): Sigmoid()(2): MaxPool2d(kernel_size2, stride2, padding0, dilation1, ceil_modeFalse)(3): Conv2d(6, 16, kernel_size(5, 5), stride(1, 1))(4): Sigmoid()(5): MaxPool2d(kernel_size2, stride2, padding0, dilation1, ceil_modeFalse))(fc): Sequential((0): Linear(in_features256, out_features120, biasTrue)(1): Sigmoid()(2): Linear(in_features120, out_features84, biasTrue)(3): Sigmoid()(4): Linear(in_features84, out_features10, biasTrue))
)获取数据集
def load_data_fashion_mnist(batch_size, resizeNone, root~/Datasets/FashionMNIST):Download the fashion mnist dataset and then load into memory.trans []if resize:trans.append(torchvision.transforms.Resize(sizeresize))trans.append(torchvision.transforms.ToTensor())transform torchvision.transforms.Compose(trans)mnist_train torchvision.datasets.FashionMNIST(rootroot, trainTrue, downloadTrue, transformtransform)mnist_test torchvision.datasets.FashionMNIST(rootroot, trainFalse, downloadTrue, transformtransform)if sys.platform.startswith(win):num_workers 0 # 0表示不用额外的进程来加速读取数据else:num_workers 4train_iter torch.utils.data.DataLoader(mnist_train, batch_sizebatch_size, shuffleTrue, num_workersnum_workers)test_iter torch.utils.data.DataLoader(mnist_test, batch_sizebatch_size, shuffleFalse, num_workersnum_workers)return train_iter, test_iterbatch_size 256
train_iter, test_iter load_data_fashion_mnist(batch_sizebatch_size)训练模型
模型准确率计算
def evaluate_accuracy(data_iter, net, deviceNone):if device is None and isinstance(net, torch.nn.Module):# 如果没指定device就使用net的devicedevice list(net.parameters())[0].deviceacc_sum, n 0.0, 0with torch.no_grad():for X, y in data_iter:if isinstance(net, torch.nn.Module):net.eval() # 评估模式, 这会关闭dropoutacc_sum (net(X.to(device)).argmax(dim1) y.to(device)).float().sum().cpu().item()net.train() # 改回训练模式else: if(is_training in net.__code__.co_varnames): # 如果有is_training这个参数# 将is_training设置成Falseacc_sum (net(X, is_trainingFalse).argmax(dim1) y).float().sum().item() else:acc_sum (net(X).argmax(dim1) y).float().sum().item() n y.shape[0]return acc_sum / n在GPU上训练模型
def train(net, train_iter, test_iter, batch_size, optimizer, device, num_epochs):net net.to(device)print(training on , device)loss torch.nn.CrossEntropyLoss()for epoch in range(num_epochs):train_l_sum, train_acc_sum, n, batch_count, start 0.0, 0.0, 0, 0, time.time()for X, y in train_iter:X X.to(device)y y.to(device)y_hat net(X)l loss(y_hat, y)optimizer.zero_grad()l.backward()optimizer.step()train_l_sum l.cpu().item()train_acc_sum (y_hat.argmax(dim1) y).sum().cpu().item()n y.shape[0]batch_count 1test_acc evaluate_accuracy(test_iter, net)print(epoch %d, loss %.4f, train acc %.3f, test acc %.3f, time %.1f sec% (epoch 1, train_l_sum / batch_count, train_acc_sum / n, test_acc, time.time() - start))学习率采用0.001训练算法使用Adam算法损失函数使用交叉熵损失函数。
lr, num_epochs 0.001, 5
optimizer torch.optim.Adam(net.parameters(), lrlr)
train(net, train_iter, test_iter, batch_size, optimizer, device, num_epochs)