pytorch 加载训练好的模型做inference

前提: 模型参数和结构是分别保存的

1、 构建模型(# load model graph)

model = MODEL()

2、加载模型参数(# load model state_dict)

model.load_state_dict
(
{
k.replace('module.',''):v for k,v in
 torch.load(config.model_path, map_location=config.device).items()
}
)
 
model = self.model.to(config.device)

   * config.device 指定使用哪块GPU或者CPU  

   *k.replace('module.',''):v  防止torch.DataParallel训练的模型出现加载错误

解决RuntimeError: module must have its parameters and buffers on device cuda:0 (device_ids[0]) but found one of them on device: cuda:1问题

3、设置当前阶段为inference# predict)

model.eval()
原文地址:https://www.cnblogs.com/llfctt/p/11896235.html