如何pytorch预训练
1、相关的迁移学习知识看王晋东的《迁移学习简明手册》.
2、可以在D:\anaconda3\envs\pytorch\Lib\site-packages\torchvision\modelD:\anaconda3\envs\pytorch\Lib\site-packages\torchvision\models
这里找到预训练模型代码
3、 官网有预训练模型使用说明以及论文
4、参考书籍下载《PyTorch 模型训练实用教程PyTorch_tutorial_余霆嵩》.
目录
1、模型加载
pytorch有两种加载模型以及权重的方法,方法一是采用torchvision.models里自带的模型且采用预训练权重,一般是finetune的时候使用该法。方法二是加载自行编写的模型以及权重,使用这种方法的情况有是因为某些原因而中断训练,需要重新加载;或者是嫌弃方法一下载模型权重的时间过长,而自行网页上下载再加载。
1.1 方法一
from torchvision import models
# 直接调用torchvision封装好的模型以及预训练权重
# 采用预训练权重可以加快模型的收敛速度
pretrain_net = models.vgg16_bn(pretrained = True)
# 打印预训练模型
print('pretrain_net.features',pretrain_net.features)
# 提取第0层的features
print('pretrain_net.features[0]',pretrain_net.features[0])
# 提取第0到7层的features
print('pretrain_net.features[:7]',pretrain_net.features[:7])
# 提取第0层的features的参数
print('pretrain_net.features[0].weight\n',pretrain_net.features[0].weight)
print('pretrain_net.features[0].weight.data\n',pretrain_net.features[0].weight.data)
print('pretrain_net.features[0].weight.shape\n',pretrain_net.features[0].weight.shape)
pretrained = True时是:(两次运行都是这些值)
pretrained = False时是:
(第一次运行)
(第二次运行)
1.2 方法二
加载自行编写的模型以及权重:这里用加载的Alexnet为例
from torchvision import models
path_state_dict