为什么AttributeError: 'collections.OrderedDict' object has no attribute 'module'
时间: 2023-06-21 19:20:27 浏览: 1585
这个错误是由于你尝试在一个 `collections.OrderedDict` 对象上调用 `.module` 属性,但是这个对象并没有 `.module` 属性。
在 PyTorch 中,当你使用 `DataParallel` 或者 `DistributedDataParallel` 在多个 GPU 上训练模型时,模型的状态字典 `state_dict` 会被包装在一个带有 `.module` 属性的 `nn.DataParallel` 或者 `nn.parallel.DistributedDataParallel` 对象中。因此,在加载模型时,你需要先将 `state_dict` 从这个包装对象中提取出来,再加载到你的模型中。
如果你在加载模型时出现了 `'collections.OrderedDict' object has no attribute 'module'` 的错误,通常是因为你尝试在一个 `collections.OrderedDict` 对象上调用 `.module` 属性,而这个对象并没有被 `DataParallel` 或者 `DistributedDataParallel` 包装。
解决这个问题的方法是,当你保存模型的时候,使用 `model.module.state_dict()` 来获取被 `DataParallel` 或者 `DistributedDataParallel` 包装后的状态字典。例如:
```
torch.save(model.module.state_dict(), PATH)
```
然后在加载模型时,使用 `torch.load()` 函数加载状态字典,而不是整个模型。例如:
```
state_dict = torch.load(PATH)
model.load_state_dict(state_dict)
```
这样就能够正确地加载模型参数了。