Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AttributeError: 'Model' object has no attribute 'state_dict' #72

Closed
kiraans opened this issue Dec 31, 2020 · 9 comments
Closed

AttributeError: 'Model' object has no attribute 'state_dict' #72

kiraans opened this issue Dec 31, 2020 · 9 comments
Labels
bug Something isn't working

Comments

@kiraans
Copy link

kiraans commented Dec 31, 2020

While saving the best weights, I am facing this error.

torch.save(model.state_dict, 'checkpoint.pth')

Environment: Google Colab

  • torch version: 1.7
  • torchvision version: 0.6.1
    Could you please suggest a corrective measure for this error!
@kiraans kiraans added the bug Something isn't working label Dec 31, 2020
@alankbi
Copy link
Owner

alankbi commented Jan 1, 2021

You should be able to save the weights by using model.save('checkpoint.pth') - see here

@kiraans
Copy link
Author

kiraans commented Jan 1, 2021

@alankbi thank you for the quick reply!
The issue is when I use model.eval(), after loading using the above-said function, I get the following error!
'collections.OrderedDict' object has no attribute 'eval'.
Any solution for this?

@alankbi
Copy link
Owner

alankbi commented Jan 2, 2021

Are you running that on the Detecto model or the internal model? If it's the Detecto model, try getting the internal PyTorch model using model.get_internal_model() and then calling the eval method on that. If you've already been doing that, feel free to share a full stack trace and I can help further.

@kiraans
Copy link
Author

kiraans commented Jan 2, 2021

I did try your solution, but got a similar error!
AttributeError: 'collections.OrderedDict' object has no attribute 'get_internal_model'
We are actually trying to build a Streamlit application using the model which we got after training using Detecto. But when we try to evaluate the model using eval() function, we get the above-mentioned error.

Could you please suggest a suitable solution?

@alankbi
Copy link
Owner

alankbi commented Jan 2, 2021

Could you share the code? It seems like you're calling these methods on the wrong object but it'd be helpful to reference the code to figure out exactly where this is happening.

@kiraans
Copy link
Author

kiraans commented Jan 3, 2021

import streamlit as st
from torchvision import transforms
from PIL import Image
import torch

st.write('# Fire and Smoke detection')

uploaded_file = st.file_uploader("Choose an image file", type=["jpg","png"])
if uploaded_file is not None:
  img = Image.open(uploaded_file).convert("RGB")

  imageLocation = st.empty()

  imageLocation.image(img, use_column_width=True)

  img = transforms.ToTensor()(img)
  model = torch.load('model.pth', map_location = 'cpu')
  model.get_internal_model()
  #model.load_state_dict(torch.load('model.pth'))
  model.eval()
  #labels, boxes, scores = model.predict_top(image)
  output = get_prediction(model, img)
  #output = model.predict(img)
  img = plot_op( img, boxes, scores)


  imageLocation.image(img, use_column_width=True)

  nms = st.sidebar.slider('nms', 0.0, 1.0, 0.1)

  boxes, scores = post_process(output, nms_thresh = nms)

@st.cache

def post_process(outputs, nms_thresh = 0.3):
  boxes = outputs ['boxes'].data

This is the code which we wrote for testing!

@alankbi
Copy link
Owner

alankbi commented Jan 3, 2021

You should change this line:

model = torch.load('model.pth', map_location = 'cpu')

to this:

from detecto.core import Model

classes = [<insert list of classes/labels here>]

model = Model.load('model.pth', classes)

Then, model.get_internal_model() will return the PyTorch object that you can call eval on:

internal_model = model.get_internal_model()
internal_model.eval()
...

However, if you're using Detecto's model.predict or model.predict_top, you shouldn't need to call the eval method, since Detecto handles it for you.

@kiraans
Copy link
Author

kiraans commented Jan 4, 2021

Thank you! This worked for me.

@kiraans kiraans closed this as completed Jan 4, 2021
@saminnasr
Copy link

@alankbi
Hi,
I have a question
when I run this code : {
start_time = time.time()
m.trainer.fit(m)
print(f"--- Training on GPU: {(time.time() - start_time):.2f} seconds ---")
print(m.trainer.fit(m))

import tempfile
tmpdir = tempfile.TemporaryDirectory()

#save the prediction dataframe after training and compare with prediction after reload checkpoint
img_path = get_data("/content/orthomosaic.jpg")
m.create_trainer()
pred_after_train = m.predict_image(path = img_path)

#Create a trainer to make a checkpoint
m.trainer.save_checkpoint("/content/checkpoint.pl")

m.trainer.save_checkpoint("/content/checkpoint.pl",format(tmpdir))

#reload the checkpoint to model object
after = main.deepforest.load_from_checkpoint("{}/checkpoint.pl".format(tmpdir))
pred_after_reload = after.predict_image(path = img_path)

assert not pred_after_train.empty
assert not pred_after_reload.empty
pd.testing.assert_frame_equal(pred_after_train,pred_after_reload)
}
I get this error: AttributeError: 'NoneType' object has no attribute 'state_dict'
would you please help me?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

3 participants