Search code examples
pythonmachine-learningpytorch

TypeError: 'dict' object is not callable in jupyter notebook


import cv2
import torch

# Load the model.
best_model = torch.load("average_model.pth", map_location=torch.device('cpu'))

# Capture video from webcam.
cap = cv2.VideoCapture(0)

while True:
    # Capture a frame from the camera.
    ret, frame = cap.read()

    # Convert the frame to RGB.
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

    # Predict handsign on frame.
    output = best_model(torch.from_numpy(frame).float().unsqueeze(0))

    # Get the predicted class.
    predicted_class = output.argmax()

    # Display the frame on the screen.
    cv2.imshow("Camera", frame)

    # Press Q to quit.
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release the camera.
cap.release()

# Close the window.
cv2.destroyAllWindows()

the error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[14], line 18
     15 frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
     17 # Predict handsign on frame.
---> 18 output = best_model(torch.from_numpy(frame).float().unsqueeze(0))
     20 # Get the predicted class.
     21 predicted_class = output.argmax()

TypeError: 'dict' object is not callable

i tried to build a yolo-nas model but when i worked in colab this worked fine but in my file jupyter notebook


Solution

  • Saved model is in fact a state_dict object with states of the weights in the model layers. So naturally the loaded object act as a dict and gives the error.

    To fix your problem, change the loading code (lines 4,5). Create/import the model structure and then load the state dict into it. Look for the clues where "average_model.pth" came from. See torch docs for more details on loading models.