简体   繁体   English

PyTorch 加载预训练权重

[英]PyTorch loading pretrained weights

I am trying to load a pretrained model re.net_18.pth file into pytorch. Online documentation suggested importing like so:我正在尝试将预训练的 model re.net_18.pth文件加载到 pytorch 中。在线文档建议这样导入:

weights = torch.load("resnet_18.pth")

When I print the output of weights , it gives something like the following:当我打印weights的 output 时,它给出如下内容:

 ('module.layer4.1.bn2.running_mean', tensor([ 9.1797e+01, -2.4204e+02,  5.6480e+01, -2.0762e+02,  4.5270e+01,
        -3.2356e+02,  1.8662e+02, -1.4498e+02, -2.3701e+02,  3.2354e+01,
...

All of the tutorials mentioned loading weights using a base model:所有教程都提到使用 model 为基础加载权重:

model = TheModelClass(*args, **kwargs)
model.load_state_dict(torch.load(PATH))
model.eval()

I want to use a default re.net-18 model to apply the weights on, but I the resent18 from tensorflow vision does not have the load_state_dict function. Help is appreciated.我想使用默认的 re.net-18 model 来应用权重,但是我来自tensorflow visionresent18没有load_state_dict function。感谢帮助。

from torchvision.models import resnet18
resnet18.load_state_dict(torch.load("resnet_18.pth"))

# 'function' object has no attribute 'load_state_dict'

re.net18 is itself a function that returns a ResNet18 model. What you can do to load your own pretrained weights is to use re.net18本身是一个 function,它返回一个ResNet18 model。加载自己的预训练权重可以做的是使用

model = resnet18()
model.load_state_dict(torch.load("resnet_18.pth"))

Note that load_state_dict(...) loads the weights in-place and does not return model itself.请注意, load_state_dict(...)就地加载权重并且不会返回 model 本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM