必做题:
(1)从 torchvision 中加载 resnet18 模型结构,并载入预训练好的模型权重
import torch
import torchvision.models as models
model = models.resnet18()
pretrained_state_dict=torch.load('./lesson2/weights/resnet18-5c106cde.pth')
model.load_state_dict(pretrained_state_dict, strict=True)
(2) 将(1)中加载好权重的resnet18模型,保存成onnx文件
onnx文件的大小为46.7 MB
(3) 以torch.rand([1,3,224,224]).type(torch.float32)作为输入,求resnet18的模型计算量和参数
量
1.82 GFLOPs and 11.69M parameters
(4) 以torch.rand([1,3,448,448]).type(torch.float32)作为输入,求resnet18的模型计算量和参数
量
7.27 GFLOPs and 11.69M parameters
思考题:
(1) 比较必做题中的(3)和(4)的结果,有什么规律?
因为模型没变,所以模型参数数量是相同的;输入图片的尺寸放大4倍,所以计算量也相应 扩大4倍
(2) 尝试用netron可视化resnet18的onnx文件
(3)model 作为 torch.nn.Module 的子类,除了用 model.state_dict()查看网络层外,还 可以用 model.named_parameters()和 model.parameters()。它们三儿有啥不同?
model.named_parameter() 相比 model.parameters() 可以多获取layer 的名字;这两者相比于model.state_dict() 的区别是他们获取的参数是部分可以被学习更新的参数,而后者获取到的是全部参数。
(4)加载模型权重时用的model.load_state_dict(字典,strict=True),里面的strict参数什么情况下要赋值 False?
当model 与预训练模型结构不完全匹配时,选用False 参数。



