国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

使用pytorch搭建AlexNet操作(微調(diào)預(yù)訓(xùn)練模型及手動搭建)

2020-02-15 21:29:36
字體:
供稿:網(wǎng)友

本文介紹了如何在pytorch下搭建AlexNet,使用了兩種方法,一種是直接加載預(yù)訓(xùn)練模型,并根據(jù)自己的需要微調(diào)(將最后一層全連接層輸出由1000改為10),另一種是手動搭建。

構(gòu)建模型類的時候需要繼承自torch.nn.Module類,要自己重寫__ /_/___init__ /_/___方法和正向傳遞時的forward方法,這里我自己的理解是,搭建網(wǎng)絡(luò)寫在__ /_/___init__ /_/___中,每次正向傳遞需要計算的部分寫在forward中,例如把矩陣壓平之類的。

加載預(yù)訓(xùn)練alexnet之后,可以print出來查看模型的結(jié)構(gòu)及信息:

model = models.alexnet(pretrained=True)print(model)

分為兩個部分,features及classifier,后續(xù)搭建模型時可以也寫成這兩部分,并且從打印出來的模型信息中也可以看出每一層的引用方式,便于修改,例如model.classifier[1]指的就是Linear(in_features=9216, out_features=4096, bias=True)這層。

下面放出完整的搭建代碼:

import torch.nn as nnfrom torchvision import modelsclass BuildAlexNet(nn.Module):  def __init__(self, model_type, n_output):    super(BuildAlexNet, self).__init__()    self.model_type = model_type    if model_type == 'pre':      model = models.alexnet(pretrained=True)      self.features = model.features      fc1 = nn.Linear(9216, 4096)      fc1.bias = model.classifier[1].bias      fc1.weight = model.classifier[1].weight            fc2 = nn.Linear(4096, 4096)      fc2.bias = model.classifier[4].bias      fc2.weight = model.classifier[4].weight            self.classifier = nn.Sequential(          nn.Dropout(),          fc1,          nn.ReLU(inplace=True),          nn.Dropout(),          fc2,          nn.ReLU(inplace=True),          nn.Linear(4096, n_output))       #或者直接修改為#      model.classifier[6]==nn.Linear(4096,n_output)#      self.classifier = model.classifier    if model_type == 'new':      self.features = nn.Sequential(          nn.Conv2d(3, 64, 11, 4, 2),          nn.ReLU(inplace = True),          nn.MaxPool2d(3, 2, 0),          nn.Conv2d(64, 192, 5, 1, 2),          nn.ReLU(inplace=True),          nn.MaxPool2d(3, 2, 0),          nn.Conv2d(192, 384, 3, 1, 1),          nn.ReLU(inplace = True),          nn.Conv2d(384, 256, 3, 1, 1),          nn.ReLU(inplace=True),          nn.MaxPool2d(3, 2, 0))      self.classifier = nn.Sequential(          nn.Dropout(),          nn.Linear(9216, 4096),          nn.ReLU(inplace=True),          nn.Dropout(),          nn.Linear(4096, 4096),          nn.ReLU(inplace=True),          nn.Linear(4096, n_output))        def forward(self, x):    x = self.features(x)    x = x.view(x.size(0), -1)    out = self.classifier(x)    return out

微調(diào)預(yù)訓(xùn)練模型的思路為:直接保留原模型的features部分,重寫classifier部分。在classifier部分中,我們實際需要修改的只有最后一層全連接層,之前的兩個全連接層不需要修改,所以重寫的時候需要把這兩層的預(yù)訓(xùn)練權(quán)重和偏移保留下來,也可以像注釋掉的兩行代碼里那樣直接引用最后一層全連接層進(jìn)行修改。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 百色市| 永城市| 安康市| 靖西县| 长春市| 蒙阴县| 德钦县| 晋宁县| 会理县| 宁津县| 濉溪县| 甘肃省| 周至县| 中宁县| 绥棱县| 铁岭市| 巨野县| 洪江市| 阳东县| 天祝| 栖霞市| 信丰县| 中阳县| 潞西市| 桦川县| 黔西| 卢湾区| 伽师县| 宁海县| 京山县| 广元市| 延庆县| 婺源县| 眉山市| 拉孜县| 登封市| 昌吉市| 新源县| 沁源县| 革吉县| 沽源县|