pytorch 載入預訓練模型

2021-10-22 08:44:36 字數 1585 閱讀 2929

pytorch的torchvision中給出了很多經典的預訓練模型,模型的引數和權重都是在imagenet資料集上訓練好的

載入模型

方法一:直接使用預訓練模型中的引數

import torchvision.models as models

model = models.resnet18(pretrained = true)

#pretrained設為true,表示使用在imagenet上訓練好的引數

import torchvision.models as models

model = models.resnet18(pretrained = false)

#pretrained設為false

state_dict = torch.load(

'resnet18.pth'

)#使用本地磁碟上的模型引數檔案

model.load_state_dict(state_dict)

#把讀入的模型引數載入到模型中

修改模型

因為預訓練模型是在imagenet資料集上訓練的,而imagenet一共有1000個類別,如果我們要訓練的資料集只有20個類別,這時就需要修改模型的全連線層

import torchvision.models as models

model = models.resnet18(pretrained=true)

num_classes =

20#自己的資料集的類別

inchannel = model.fc.in_features

model.fc = nn.linear(inchannel, num_classes)

#修改全連線層

總結

import torchvision.models as models

model = models.resnet18(pretrained=true)

forp

in model.parameters(

): p.requires_grad = false #設為false表示只訓練最後全連線層的權重,其餘層不訓練

num_classes =

20#自己的資料集的類別

model.conv1 = nn.conv2d(

14, 64, kernel_size

=7, stride

=2, padding

=3, bias

=false)

#改輸入通道數

inchannel = model.fc.in_features

model.fc = nn.linear(inchannel, num_classes)

#修改全連線層

model = nn.dataparallel(model).cuda(

)#gpu訓練

model.eval(

)#排除bn和dropout的影響

pytorch載入預訓練模型後,訓練指定層

1 有了已經訓練好的模型引數,對這個模型的某些層做了改變,如何利用這些訓練好的模型引數繼續訓練 pretrained params torch.load pretrained model model the new model model.load state dict pretrained par...

pytorch載入預訓練模型後,訓練指定層

1 有了已經訓練好的模型引數,對這個模型的某些層做了改變,如何利用這些訓練好的模型引數繼續訓練 pretrained params torch.load pretrained model model the new model model.load state dict pretrained par...

pytorch載入預訓練模型後,訓練指定層

1 有了已經訓練好的模型引數,對這個模型的某些層做了改變,如何利用這些訓練好的模型引數繼續訓練 pretrained params torch.load pretrained model model the new model model.load state dict pretrained par...