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)過卷積進行特征提取,得到的結(jié)果反而沒有之前的很好,所以resnet提出保留之前的特征,這里還需要經(jīng)過一些處理,在下面代碼講解中將詳細介紹。
二、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ù)要進行翻倍,要不然后面是不能進行相加。
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í)率進行每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ù)增強
這里我們?nèi)匀贿x擇cifar10數(shù)據(jù)集,首先對數(shù)據(jù)進行增強,增加模型的泛華能力。
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ù),進行模型測試
首先加載訓(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)練的詳細內(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圖片進行分類方式
相關(guān)文章
利用Python實現(xiàn)K-Means聚類的方法實例(案例:用戶分類)
k-means是發(fā)現(xiàn)給定數(shù)據(jù)集的k個簇的算法,也就是將數(shù)據(jù)集聚合為k類的算法,下面這篇文章主要給大家介紹了關(guān)于利用Python實現(xiàn)K-Means聚類的相關(guān)資料,需要的朋友可以參考下2022-05-05
快速進修Python指南之網(wǎng)絡(luò)編程及并發(fā)編程
這篇文章主要為大家介紹了Java開發(fā)者如何快速進修Python指南之網(wǎng)絡(luò)編程及并發(fā)編程實例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-12-12
scrapy數(shù)據(jù)存儲在mysql數(shù)據(jù)庫的兩種方式(同步和異步)
這篇文章主要介紹了scrapy數(shù)據(jù)存儲在mysql數(shù)據(jù)庫的兩種方式(同步和異步),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02

