日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人工智能 > 卷积神经网络 >内容正文

卷积神经网络

(pytorch-深度学习系列)卷积神经网络LeNet-学习笔记

發布時間:2024/8/23 卷积神经网络 87 豆豆
生活随笔 收集整理的這篇文章主要介紹了 (pytorch-深度学习系列)卷积神经网络LeNet-学习笔记 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

卷積神經網絡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} (65?5)?()(2?22)?(165?5)?()(2?22)?16?5?5120?12084?8410?

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 output net = LeNet() print(net) LeNet((conv): Sequential((0): Conv2d(1, 6, kernel_size=(5, 5), stride=(1, 1))(1): Sigmoid()(2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)(3): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))(4): Sigmoid()(5): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False))(fc): Sequential((0): Linear(in_features=256, out_features=120, bias=True)(1): Sigmoid()(2): Linear(in_features=120, out_features=84, bias=True)(3): Sigmoid()(4): Linear(in_features=84, out_features=10, bias=True)) )

獲取數據集

def load_data_fashion_mnist(batch_size, resize=None, root='~/Datasets/FashionMNIST'):"""Download the fashion mnist dataset and then load into memory."""trans = []if resize:trans.append(torchvision.transforms.Resize(size=resize))trans.append(torchvision.transforms.ToTensor())transform = torchvision.transforms.Compose(trans)mnist_train = torchvision.datasets.FashionMNIST(root=root, train=True, download=True, transform=transform)mnist_test = torchvision.datasets.FashionMNIST(root=root, train=False, download=True, transform=transform)if sys.platform.startswith('win'):num_workers = 0 # 0表示不用額外的進程來加速讀取數據else:num_workers = 4train_iter = torch.utils.data.DataLoader(mnist_train, batch_size=batch_size, shuffle=True, num_workers=num_workers)test_iter = torch.utils.data.DataLoader(mnist_test, batch_size=batch_size, shuffle=False, num_workers=num_workers)return train_iter, test_iterbatch_size = 256 train_iter, test_iter = load_data_fashion_mnist(batch_size=batch_size)

訓練模型

模型準確率計算:

def evaluate_accuracy(data_iter, net, device=None):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(dim=1) == 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_training=False).argmax(dim=1) == y).float().sum().item() else:acc_sum += (net(X).argmax(dim=1) == 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(dim=1) == 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(), lr=lr) train(net, train_iter, test_iter, batch_size, optimizer, device, num_epochs)

總結

以上是生活随笔為你收集整理的(pytorch-深度学习系列)卷积神经网络LeNet-学习笔记的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。