Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError: 'collections.OrderedDict' object has no attribute 'eval'

I have a model file which looks like this

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

I want to do inference on this model, but when i do model.eval() i get,

AttributeError: 'collections.OrderedDict' object has no attribute 'eval
like image 463
Ryan Avatar asked Apr 20 '18 12:04

Ryan


1 Answers

It is not a model file, instead, this is a state file. In a model file, the complete model is stored, whereas in a state file only the parameters are stored.
So, your OrderedDict are just values for your model. You will need to create the model and then need to load these values into your model. So, the process will be something in form of

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()

You'll need to define your model properly. The one given in the example above is just a dummy. If you construct your model yourself, you might need to update the keys of the saved dict file as mentioned here. The best course of action is to define your model in exactly the same way from when the state_dict was saved and then directly executing model.load_state_dict will work.

like image 162
layog Avatar answered Sep 21 '22 20:09

layog