import torchvision.models as models
1.調整最後一層輸出維度
model = models.ResNet(pretrained=True)
fc_features = model.fc.in_features# 獲取全連接層輸入維度
model.fc = torch.nn.Linear(fc_features, num_class)
``
2.調整某一層參數
import torch
import torch.nn as nn
from torchvision import models
class ft_net(nn.Module):
def __init__(self, class_num = 751):
super(ft_net, self).__init__()
#load the model
model_ft = models.resnet50(pretrained=True)
if stride == 1:
model_ft.layer4[0].downsample[0].stride = (1,1)
model_ft.layer4[0].conv2.stride = (1,1)
model_ft.avgpool = nn.AdaptiveAvgPool2d((1,1))
self.model = model_ft
self.fc = nn.Linear(2048, num_class)
def forward(self, x):
x = self.model.conv1(x)
x = self.model.bn1(x)
x = self.model.relu(x)
x = self.model.maxpool(x)
x = self.model.layer1(x)
x = self.model.layer2(x)
x = self.model.layer3(x)
x = self.model.layer4(x)
x = self.model.avgpool(x)
x = torch.squeeze(x)
x = self.fc(x) #use our classifier.
return x
調整模型中layer4[0]中的downsample[0]的stride值。
添加層並加載參數
import torchvision.models as models
import torch
import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
class CNN(nn.Module):
def __init__(self, block, layers, num_classes=9):
self.inplanes = 64
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
self.avgpool = nn.AvgPool2d(7, stride=1)
#新增一個反捲積層
self.convtranspose1 = nn.ConvTranspose2d(2048, 2048, kernel_size=3, stride=1, padding=1, output_padding=0, groups=1, bias=False, dilation=1)
#新增一個最大池化層
self.maxpool2 = nn.MaxPool2d(kernel_size=3, stride=1, padding=1)
#去掉原來的fc層,新增一個fclass層
self.fclass = nn.Linear(2048, num_classes)
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
def _make_layer(self, block, planes, blocks, stride=1):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes, stride, downsample))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(self.inplanes, planes))
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.avgpool(x)
#新加層的forward
x = x.view(x.size(0), -1)
x = self.convtranspose1(x)
x = self.maxpool2(x)
x = x.view(x.size(0), -1)
x = self.fclass(x)
return x
#加載model
resnet50 = models.resnet50(pretrained=True)
cnn = CNN(Bottleneck, [3, 4, 6, 3])
#讀取參數
pretrained_dict = resnet50.state_dict()
model_dict = cnn.state_dict()
#將pretrained_dict裏不屬於model_dict的鍵剔除掉
pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}
#更新現有的model_dict
model_dict.update(pretrained_dict)
#加載我們真正需要的state_dict
cnn.load_state_dict(model_dict)
#print(resnet50)
print(cnn)
多GPU訓練參數模型加載:
使用多GPU訓練權重需要使用model = torch.nn.Parallel(model)處理模型
對於參數模型中可能包含state_dict,epoch,accruccy,等鍵值對,我們只需要加載key爲state_dict的鍵值對。
例:
pretrained_dict = torch.load(dict_path)
model_dict_clone = pretrained_dict.copy()
for key, value in model_dict_clone.items():
if key == ‘state_dict’:
pretrained_dict = model_dict_clone['state_dict']
單個GPU訓練使用多GPU加載
由於單個GPU訓練保存的權重參數,key沒有module前綴,使用並行GPU不能直接加載模型參數。需要進行鍵值對的key進行處理,需要用list將字典包裝,否則在迭代處理字典的時候會出現錯誤
pretrained_dict = torch.load(dict_path)
model_dict_clone = pretrained_dict.copy()
for key, value in list(model_dict_clone.items()):
model_dict_clone['module.' + key] = model_dict_clone.pop(key)