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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人工智能 > pytorch >内容正文

pytorch

(pytorch-深度学习)实现残差网络(ResNet)

發布時間:2024/8/23 pytorch 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 (pytorch-深度学习)实现残差网络(ResNet) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

實現殘差網絡(ResNet)

  • 我們一般認為,增加神經網絡模型的層數,充分訓練后的模型理論上能更有效地降低訓練誤差。
  • 理論上,原模型解的空間只是新模型解的空間的子空間。也就是說,如果我們能將新添加的層訓練成恒等映射f(x)=xf(x) = xf(x)=x,新模型和原模型將同樣有效。
  • 由于新模型可能得出更優的解來擬合訓練數據集,因此添加層似乎更容易降低訓練誤差。
  • 然而在實踐中,添加過多的層后訓練誤差往往不降反升。即使利用批量歸一化帶來的數值穩定性使訓練深層模型更加容易,該問題仍然存在。針對這一問題,何愷明等人提出了殘差網絡(ResNet)。它在2015年的ImageNet圖像識別挑戰賽奪魁,并深刻影響了后來的深度神經網絡的設計。

殘差塊

殘差塊的結構在之前的blog中詳細解釋了,感興趣的可以去看。

ResNet沿用了VGG全3×33\times 33×3卷積層的設計。

  • 殘差塊里首先有2個有相同輸出通道數的3×33\times 33×3卷積層。
  • 每個卷積層后接一個批量歸一化層和ReLU激活函數
  • 然后輸入跳過這兩個卷積運算后直接加在最后的ReLU激活函數前。
  • 這樣的設計要求兩個卷積層的輸出與輸入形狀一樣,從而可以相加
  • 如果想改變通道數,就需要引入一個額外的1×11\times 11×1卷積層來將輸入變換成需要的形狀后再做相加運算。

殘差塊的實現如下。它可以設定輸出通道數、是否使用額外的1×11\times 11×1卷積層來修改通道數以及卷積層的步幅。

import time import torch from torch import nn, optim import torch.nn.functional as Fdevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')class Residual(nn.Module): def __init__(self, in_channels, out_channels, use_1x1conv=False, stride=1):super(Residual, self).__init__()self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, stride=stride)self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1)if use_1x1conv:self.conv3 = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride)else:self.conv3 = Noneself.bn1 = nn.BatchNorm2d(out_channels)self.bn2 = nn.BatchNorm2d(out_channels)def forward(self, X):Y = F.relu(self.bn1(self.conv1(X)))Y = self.bn2(self.conv2(Y))if self.conv3:X = self.conv3(X)return F.relu(Y + X)

查看輸入和輸出形狀一致的情況。

blk = Residual(3, 3) X = torch.rand((4, 3, 6, 6)) blk(X).shape # torch.Size([4, 3, 6, 6])

我們也可以在增加輸出通道數的同時減半輸出的高和寬。

blk = Residual(3, 6, use_1x1conv=True, stride=2) blk(X).shape # torch.Size([4, 6, 3, 3])

ResNet模型

ResNet的前兩層跟GoogLeNet中的一樣:

  • 在輸出通道數為64、步幅為2的7×77\times 77×7卷積層后接步幅為2的3×33\times 33×3的最大池化層。
  • 每個卷積層后增加批量歸一化層。
net = nn.Sequential(nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3),nn.BatchNorm2d(64), nn.ReLU(),nn.MaxPool2d(kernel_size=3, stride=2, padding=1))
  • ResNet使用4個由殘差塊組成的模塊,每個模塊使用若干個同樣輸出通道數的殘差塊。
  • 第一個模塊的通道數同輸入通道數一致無須減小高和寬(之前已經使用了步幅為2的最大池化層)。
  • 之后的每個模塊在第一個殘差塊里將上一個模塊的通道數翻倍,并將高和寬減半
def resnet_block(in_channels, out_channels, num_residuals, first_block=False):if first_block:assert in_channels == out_channels # 第一個模塊的通道數同輸入通道數一致blk = []for i in range(num_residuals):if i == 0 and not first_block:blk.append(Residual(in_channels, out_channels, use_1x1conv=True, stride=2))else:blk.append(Residual(out_channels, out_channels))return nn.Sequential(*blk)

接著我們為ResNet加入所有殘差塊。這里每個模塊使用兩個殘差塊

net.add_module("resnet_block1", resnet_block(64, 64, 2, first_block=True)) net.add_module("resnet_block2", resnet_block(64, 128, 2)) net.add_module("resnet_block3", resnet_block(128, 256, 2)) net.add_module("resnet_block4", resnet_block(256, 512, 2))

加入全局平均池化層后接上全連接層輸出。

class GlobalAvgPool2d(nn.Module):# 全局平均池化層可通過將池化窗口形狀設置成輸入的高和寬實現def __init__(self):super(GlobalAvgPool2d, self).__init__()def forward(self, x):return F.avg_pool2d(x, kernel_size=x.size()[2:])class FlattenLayer(torch.nn.Module):def __init__(self):super(FlattenLayer, self).__init__()def forward(self, x): # x shape: (batch, *, *, ...)return x.view(x.shape[0], -1) net.add_module("global_avg_pool", GlobalAvgPool2d()) # GlobalAvgPool2d的輸出: (Batch, 512, 1, 1) net.add_module("fc", nn.Sequential(FlattenLayer(), nn.Linear(512, 10)))
  • 這里每個模塊里有4個卷積層(不計算1×11\times 11×1卷積層),加上最開始的卷積層和最后的全連接層,共計18層。這個模型通常也被稱為ResNet-18。
  • 通過配置不同的通道數和模塊里的殘差塊數可以得到不同的ResNet模型,例如更深的含152層的ResNet-152。雖然ResNet的主體架構跟GoogLeNet的類似,但ResNet結構更簡單,修改也更方便。這些因素都導致了ResNet迅速被廣泛使用。
X = torch.rand((1, 1, 224, 224)) for name, layer in net.named_children():X = layer(X)print(name, ' output shape:\t', X.shape) 0 output shape: torch.Size([1, 64, 112, 112]) 1 output shape: torch.Size([1, 64, 112, 112]) 2 output shape: torch.Size([1, 64, 112, 112]) 3 output shape: torch.Size([1, 64, 56, 56]) resnet_block1 output shape: torch.Size([1, 64, 56, 56]) resnet_block2 output shape: torch.Size([1, 128, 28, 28]) resnet_block3 output shape: torch.Size([1, 256, 14, 14]) resnet_block4 output shape: torch.Size([1, 512, 7, 7]) global_avg_pool output shape: torch.Size([1, 512, 1, 1]) fc output shape: torch.Size([1, 10])

獲取數據

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_iter batch_size = 256 # 如出現“out of memory”的報錯信息,可減小batch_size或resize train_iter, test_iter = load_data_fashion_mnist(batch_size, resize=96)

訓練模型

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)) 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-深度学习)实现残差网络(ResNet)的全部內容,希望文章能夠幫你解決所遇到的問題。

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