python - Pytorch:使用 DataParallel 进行训练并在 cpu 上进行测试
问题描述
我有一个使用我在 pytorch 中的其他预训练模型之一的训练模型。对于测试,我想在 cpu 而不是 gpu 上进行测试。问题是,由于我在训练过程中使用了 Dataparallel 函数,因此将其转换为 cpu 对我来说并不简单。
我的训练模型代码如下:
class DGCNN_tl(nn.Module):
def __init__(self):
super(DGCNN_tl, self).__init__()
self.model = DGCNN()
if torch.cuda.device_count() > 1:
print(str(torch.cuda.device_count())+" GPUs detected!")
self.model = nn.DataParallel(self.model)
patch_replication_callback(self.model) #sync_batch_norm
self.model.to(device)
self.model.load_state_dict(torch.load("teeth_seg2_pretrained.pt"))
for param in self.model.parameters(): #making all layers fine tuneable
param.requires_grad = True
def forward(self, inputs, l):
outputs,t,feature = self.model(inputs, l)
return outputs, t, feature
以下是我尝试将其转换为 cpu 进行测试的方法:
dgcnn_lower = DGCNN_tl()
# original saved file with DataParallel
model_old = torch.load('teeth_seg2_lower_0.953iou.pt', map_location=torch.device('cpu'))
# create new OrderedDict that does not contain `module.`
from collections import OrderedDict
new_state_dict = OrderedDict()
for k, v in model_old.items():
name = k[7:] # remove `module.`
new_state_dict[name] = v
# load params
dgcnn_lower.load_state_dict(new_state_dict)
这给出了一个错误说
Missing key(s) in state_dict: "model.module.transform_net.bn1.weight", "model.module.transform_net.bn1.bias"
“teeth_seg2_pretrained.pt”:这是我的预训练模型,用于训练我当前的模型 “teeth_seg2_lower_0.953iou.pt”:这是我想在 cpu 上测试的当前模型
有人可以给我一个建议或帮助来解决这个问题吗?谢谢!!
解决方案
推荐阅读
- python - Pandas:为什么在 Titanic 数据库电子表格中缺少 Column 会将 dtype 作为对象?
- c++ - UWP 应用程序在 Class1 崩溃 c1 = new Class1(); 说 - 找不到指定的模块。(来自 HRESULT 的异常:0x8007007E
- git - Git / VSCode 错误或云错误
- git - 镜像远程 Git 存储库,包括使用脚本获取的子存储库
- python - ValueError:int() 的无效文字,以 10 为底:计算器中的“+”
- jenkins - 由于 SDK 过时,Jenkins Android 模拟器正在运行。我如何在詹金斯上更新它
- spring-integration - redisQueueInboundGateway.setReplyChannelName 是什么
- kubernetes - helm purge 后没有删除一些 PVC
- python - 在pyspark中创建带有arraytype列的数据框
- ruby-on-rails - 合并 ruby on rails 中相同键名的值