deep-learning - 属性错误 : 'collections.OrderedDict' object has no attribute 'eval'

标签 deep-learning pytorch

我有一个看起来像这样的模型文件

OrderedDict([('inp.conv1.conv.weight', 
          (0 ,0 ,0 ,.,.) = 
           -1.5073e-01  6.4760e-02  1.9156e-01
            1.2175e-01  3.5886e-02  1.3992e-01
           -1.5903e-01  8.2055e-02  1.7820e-01

          (0 ,0 ,1 ,.,.) = 
            1.0604e-01 -1.3653e-01  1.4803e-01
            6.0276e-02 -1.4674e-02  2.3059e-06
           -6.2192e-02 -5.1061e-03 -7.4145e-03

          (0 ,0 ,2 ,.,.) = 
           -5.5632e-02  3.5326e-02  6.5108e-02
            1.1411e-01 -4.4160e-02  8.2610e-02
            8.9979e-02 -3.5454e-02  4.2549e-02

          (1 ,0 ,0 ,.,.) = 
            4.8523e-02 -4.3961e-02  5.3614e-02
           -1.2644e-01  1.2777e-01  8.9547e-02
            3.8392e-02  2.7016e-02 -1.4552e-01

          (1 ,0 ,1 ,.,.) = 
            9.5537e-02  2.8748e-02  3.9772e-02
           -6.2410e-02  1.1264e-01  7.8663e-02
           -2.6374e-02  1.4401e-01 -1.7109e-01

          (1 ,0 ,2 ,.,.) = 
            5.1791e-02 -1.6388e-01 -1.7605e-01
            3.5028e-02  7.7164e-02 -1.4499e-01
           -2.9189e-02  2.7064e-03 -2.3228e-02

          (2 ,0 ,0 ,.,.) = 
           -7.4446e-03 -9.7202e-02 -1.4704e-01
           -1.0019e-02  8.1780e-02 -5.3530e-02
           -1.8412e-01  1.5988e-01 -1.3450e-01

          (2 ,0 ,1 ,.,.) = 
           -1.1075e-01 -5.2478e-02  6.0658e-02
            1.6739e-01 -2.9360e-02  1.2621e-01
            2.0686e-02  1.1468e-01  1.2282e-01

我想对这个模型进行推理,但是当我执行 model.eval() 时,我得到了,
AttributeError: 'collections.OrderedDict' object has no attribute 'eval不太确定如何解决这个问题,关于如何解决这个问题的任何建议都会非常有帮助,提前致谢

最佳答案

它不是模型文件,而是一个状态文件。在模型文件中,存储了完整的模型,而在状态文件中,仅存储了参数。
那么,您的 OrderedDict只是您模型的值。您将需要创建模型,然后需要将这些值加载到您的模型中。所以,这个过程将是某种形式的

import torch
import torch.nn as nn

class TempModel(nn.Module):
    def __init__(self):
        self.conv1 = nn.Conv2d(3, 5, (3, 3))
    def forward(self, inp):
        return self.conv1(inp)

model = TempModel()
model.load_state_dict(torch.load(file_path))
model.eval()

您需要正确定义模型。上面例子中给出的只是一个假人。如果您自己构建模型,则可能需要更新已保存的 dict 文件的键值 here .最好的做法是以与 state_dict 完全相同的方式定义您的模型。保存后直接执行model.load_state_dict会工作。

关于deep-learning - 属性错误 : 'collections.OrderedDict' object has no attribute 'eval' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49941426/

相关文章:

machine-learning - 为什么 L1 正则化在机器学习中有效

python - 每个时期的数据大小都不同

c++ - 我怎么知道使用caffe framwork和c++程序的层中是否不存在偏差

python - 从 numpy 创建张量时缺少梯度

python - PyTorch 中的 Concat 张量

python - 检查一个张量值是否包含在另一个张量中

python - 如何在 PyTorch 中标准化图像

python - Tensorflow 中的成对排名损失函数

python tensorflow 在输入层上使用 dropout

pytorch - 填充张量直到达到所需的大小