Pytorch深度學(xué)習(xí)經(jīng)典卷積神經(jīng)網(wǎng)絡(luò)resnet模塊訓(xùn)練
前言
隨著深度學(xué)習(xí)的不斷發(fā)展,從開山之作Alexnet到VGG,網(wǎng)絡(luò)結(jié)構(gòu)不斷優(yōu)化,但是在VGG網(wǎng)絡(luò)研究過程中,人們發(fā)現(xiàn)隨著網(wǎng)絡(luò)深度的不斷提高,準(zhǔn)確率卻沒有得到提高,如圖所示:
人們覺得深度學(xué)習(xí)到此就停止了,不能繼續(xù)研究了,但是經(jīng)過一段時間的發(fā)展,殘差網(wǎng)絡(luò)(resnet)解決了這一問題。
一、resnet
如圖所示:簡單來說就是保留之前的特征,有時候當(dāng)圖片經(jīng)過卷積進(jìn)行特征提取,得到的結(jié)果反而沒有之前的很好,所以resnet提出保留之前的特征,這里還需要經(jīng)過一些處理,在下面代碼講解中將詳細(xì)介紹。
二、resnet網(wǎng)絡(luò)結(jié)構(gòu)
本文將主要介紹resnet18
三、resnet18
1.導(dǎo)包
import torch import torchvision.transforms as trans import torchvision as tv import torch.nn as nn from torch.autograd import Variable from torch.utils import data from torch.optim import lr_scheduler
2.殘差模塊
這個模塊完成的功能如圖所示:
class tiao(nn.Module): def __init__(self,shuru,shuchu): super(tiao, self).__init__() self.conv1=nn.Conv2d(in_channels=shuru,out_channels=shuchu,kernel_size=(3,3),padding=(1,1)) self.bath=nn.BatchNorm2d(shuchu) self.relu=nn.ReLU() def forward(self,x): x1=self.conv1(x) x2=self.bath(x1) x3=self.relu(x2) x4=self.conv1(x3) x5=self.bath(x4) x6=self.relu(x5) x7=x6+x return x7
2.通道數(shù)翻倍殘差模塊
模塊完成功能如圖所示:
在這個模塊中,要注意原始圖像的通道數(shù)要進(jìn)行翻倍,要不然后面是不能進(jìn)行相加。
class tiao2(nn.Module): def __init__(self,shuru): super(tiao2, self).__init__() self.conv1=nn.Conv2d(in_channels=shuru,out_channels=shuru*2,kernel_size=(3,3),stride=(2,2),padding=(1,1)) self.conv11=nn.Conv2d(in_channels=shuru,out_channels=shuru*2,kernel_size=(1,1),stride=(2,2)) self.batch=nn.BatchNorm2d(shuru*2) self.relu=nn.ReLU() self.conv2=nn.Conv2d(in_channels=shuru*2,out_channels=shuru*2,kernel_size=(3,3),stride=(1,1),padding=(1,1)) def forward(self,x): x1=self.conv1(x) x2=self.batch(x1) x3=self.relu(x2) x4=self.conv2(x3) x5=self.batch(x4) x6=self.relu(x5) x11=self.conv11(x) x7=x11+x6 return x7
3.rensnet18模塊
class resnet18(nn.Module): def __init__(self): super(resnet18, self).__init__() self.conv1=nn.Conv2d(in_channels=3,out_channels=64,kernel_size=(7,7),stride=(2,2),padding=(3,3)) self.bath=nn.BatchNorm2d(64) self.relu=nn.ReLU() self.max=nn.MaxPool2d(2,2) self.tiao1=tiao(64,64) self.tiao2=tiao(64,64) self.tiao3=tiao2(64) self.tiao4=tiao(128,128) self.tiao5=tiao2(128) self.tiao6=tiao(256,256) self.tiao7=tiao2(256) self.tiao8=tiao(512,512) self.a=nn.AdaptiveAvgPool2d(output_size=(1,1)) self.l=nn.Linear(512,10) def forward(self,x): x1=self.conv1(x) x2=self.bath(x1) x3=self.relu(x2) x4=self.tiao1(x3) x5=self.tiao2(x4) x6=self.tiao3(x5) x7=self.tiao4(x6) x8=self.tiao5(x7) x9=self.tiao6(x8) x10=self.tiao7(x9) x11=self.tiao8(x10) x12=self.a(x11) x13=x12.view(x12.size()[0],-1) x14=self.l(x13) return x14
這個網(wǎng)絡(luò)簡單來說16層卷積,1層全連接,訓(xùn)練參數(shù)相對較少,模型相對來說比較簡單。
4.數(shù)據(jù)測試
model=resnet18().cuda() input=torch.randn(1,3,64,64).cuda() output=model(input) print(output)
5.損失函數(shù),優(yōu)化器
損失函數(shù)
loss=nn.CrossEntropyLoss()
在優(yōu)化器中,將學(xué)習(xí)率進(jìn)行每10步自動衰減
opt=torch.optim.SGD(model.parameters(),lr=0.001,momentum=0.9)exp_lr=lr_scheduler.StepLR(opt,step_size=10,gamma=0.1)opt=torch.optim.SGD(model.parameters(),lr=0.001,momentum=0.9) exp_lr=lr_scheduler.StepLR(opt,step_size=10,gamma=0.1)
在這里可以看一下對比圖,發(fā)現(xiàn)添加學(xué)習(xí)率自動衰減,loss下降速度會快一些,這說明模型擬合效果比較好。
6.加載數(shù)據(jù)集,數(shù)據(jù)增強(qiáng)
這里我們?nèi)匀贿x擇cifar10數(shù)據(jù)集,首先對數(shù)據(jù)進(jìn)行增強(qiáng),增加模型的泛華能力。
transs=trans.Compose([ trans.Resize(256), trans.RandomHorizontalFlip(), trans.RandomCrop(64), trans.ColorJitter(brightness=0.5,contrast=0.5,hue=0.3), trans.ToTensor(), trans.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5)) ])
ColorJitter函數(shù)中brightness(亮度)contrast(對比度)saturation(飽和度)hue(色調(diào))
加載cifar10數(shù)據(jù)集:
train=tv.datasets.CIFAR10( root=r'E:\桌面\資料\cv3\數(shù)據(jù)集\cifar-10-batches-py', train=True, download=True, transform=transs ) trainloader=data.DataLoader( train, num_workers=4, batch_size=8, shuffle=True, drop_last=True )
7.訓(xùn)練數(shù)據(jù)
for i in range(3): running_loss=0 for index,data in enumerate(trainloader): x,y=data x=x.cuda() y=y.cuda() x=Variable(x) y=Variable(y) opt.zero_grad() h=model(x) loss1=loss(h,y) loss1.backward() opt.step() running_loss+=loss1.item() if index%100==99: avg_loos=running_loss/100 running_loss=0 print("avg_loss",avg_loos)
8.保存模型
torch.save(model.state_dict(),'resnet18.pth')
9.加載測試集數(shù)據(jù),進(jìn)行模型測試
首先加載訓(xùn)練好的模型
model.load_state_dict(torch.load('resnet18.pth'),False)
讀取數(shù)據(jù)
test = tv.datasets.ImageFolder( root=r'E:\桌面\資料\cv3\數(shù)據(jù)', transform=transs, ) testloader = data.DataLoader( test, batch_size=16, shuffle=False, )
測試數(shù)據(jù)
acc=0 total=0 for data in testloader: inputs,indel=data out=model(inputs.cuda()) _,prediction=torch.max(out.cpu(),1) total+=indel.size(0) b=(prediction==indel) acc+=b.sum() print("準(zhǔn)確率%d %%"%(100*acc/total))
四、resnet深層對比
上面提到VGG網(wǎng)絡(luò)層次越深,準(zhǔn)確率越低,為了解決這一問題,才提出了殘差網(wǎng)絡(luò)(resnet),那么在resnet網(wǎng)絡(luò)中,到底會不會出現(xiàn)這一問題。
如圖所示:隨著,訓(xùn)練層次不斷提高,模型越來越好,成功解決了VGG網(wǎng)絡(luò)的問題,到現(xiàn)在為止,殘差網(wǎng)絡(luò)還是被大多數(shù)人使用。
以上就是Pytorch深度學(xué)習(xí)經(jīng)典卷積神經(jīng)網(wǎng)絡(luò)resnet模塊訓(xùn)練的詳細(xì)內(nèi)容,更多關(guān)于卷積神經(jīng)網(wǎng)絡(luò)resnet模塊訓(xùn)練的資料請關(guān)注腳本之家其它相關(guān)文章!
- Pytorch搭建簡單的卷積神經(jīng)網(wǎng)絡(luò)(CNN)實現(xiàn)MNIST數(shù)據(jù)集分類任務(wù)
- Pytorch卷積神經(jīng)網(wǎng)絡(luò)遷移學(xué)習(xí)的目標(biāo)及好處
- Pytorch卷積神經(jīng)網(wǎng)絡(luò)resent網(wǎng)絡(luò)實踐
- pytorch加載的cifar10數(shù)據(jù)集過程詳解
- pytorch中的模型訓(xùn)練(以CIFAR10數(shù)據(jù)集為例)
- Pytorch使用卷積神經(jīng)網(wǎng)絡(luò)對CIFAR10圖片進(jìn)行分類方式
相關(guān)文章
Python實現(xiàn)處理apiDoc轉(zhuǎn)swagger的方法詳解
這篇文章主要為大家詳細(xì)介紹了Python實現(xiàn)處理apiDoc轉(zhuǎn)swagger的方法,文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價值,感興趣的小伙伴可以了解一下2023-02-02Python中.join()和os.path.join()兩個函數(shù)的用法詳解
join()是連接字符串?dāng)?shù)組而os.path.join()是將多個路徑組合后返回。接下來通過本文重點(diǎn)給大家介紹Python中.join()和os.path.join()兩個函數(shù)的用法,感興趣的朋友一起看看吧2018-06-06Python實現(xiàn)普通圖片轉(zhuǎn)ico圖標(biāo)的方法詳解
ICO是一種圖標(biāo)文件格式,圖標(biāo)文件可以存儲單個圖案、多尺寸、多色板的圖標(biāo)文件。本文將利用Python實現(xiàn)普通圖片轉(zhuǎn)ico圖標(biāo),感興趣的小伙伴可以了解一下2022-11-11python3.3使用tkinter開發(fā)猜數(shù)字游戲示例
這篇文章主要介紹了python3.3使用tkinter開發(fā)猜數(shù)字游戲示例,需要的朋友可以參考下2014-03-03python smtplib模塊發(fā)送SSL/TLS安全郵件實例
這篇文章主要介紹了python smtplib模塊發(fā)送SSL/TLS安全郵件實例,本文講解了二種發(fā)送方式,需要的朋友可以參考下2015-04-04Python給exe添加以管理員運(yùn)行的屬性方法詳解
這篇文章主要為大家介紹了Python給exe添加以管理員運(yùn)行的屬性方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12python?動態(tài)規(guī)劃問題解析(背包問題和最長公共子串)
這篇文章主要介紹了python?動態(tài)規(guī)劃(背包問題和最長公共子串),在動態(tài)規(guī)劃中,你要將某個指標(biāo)最大化。在這個例子中,你要找出兩個單詞的最長公共子串。fish和fosh都包含的最長子串是什么呢,感興趣的朋友跟隨小編一起看看吧2022-05-05