You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jupyter Notebook中TypeError: 'dict'对象不可调用问题求助

解决YOLO-NAS模型本地加载后调用报错问题

问题描述

我构建了YOLO-NAS模型,代码在Colab中运行正常,但本地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()

错误信息

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

错误原因

torch.load("average_model.pth")加载得到的是模型的状态字典(dict类型),而非可调用的模型实例。Colab中能正常运行,是因为训练时保存的是完整模型对象(用torch.save(model, path)),而本地加载的文件只保存了状态字典(训练时用的是torch.save(model.state_dict(), path)),所以直接调用会触发字典不可调用的错误。

解决步骤

要正确加载模型,需要先初始化和训练时结构完全一致的模型实例,再将状态字典加载到实例中:

修改后的代码

import cv2
import torch
# 导入你训练时定义的YOLO-NAS模型类,替换为实际的导入路径
from your_model_definition import YOLO_NAS

# 1. 初始化模型实例,参数要和训练时完全匹配(比如类别数)
best_model = YOLO_NAS(num_classes=你的类别数量)  # 替换为训练时的实际参数

# 2. 加载状态字典到模型中
state_dict = torch.load("average_model.pth", map_location=torch.device('cpu'))
best_model.load_state_dict(state_dict)

# 设置模型为评估模式(推理时必须)
best_model.eval()

# 摄像头捕获
cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()
    if not ret:
        break  # 处理帧读取失败的情况

    # 转换颜色空间
    frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    
    # 预处理:转换为张量并调整维度(YOLO-NAS要求通道在前:C,H,W)
    input_tensor = torch.from_numpy(frame_rgb).float().unsqueeze(0)
    input_tensor = input_tensor.permute(0, 3, 1, 2)  # 从(batch, H, W, C)转为(batch, C, H, W)

    # 推理时关闭梯度计算,节省资源
    with torch.no_grad():
        output = best_model(input_tensor)

    predicted_class = output.argmax()

    # 显示帧
    cv2.imshow("Camera", frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

关键注意事项

  • 模型结构必须和训练时完全一致,包括层数、神经元数量、类别数等,否则load_state_dict会报错。
  • 如果训练时是用torch.save(model, "average_model.pth")保存的完整模型,本地可以直接用torch.load加载,但这种方式兼容性较差(不同PyTorch版本可能出问题),更推荐保存状态字典。
  • YOLO-NAS的输入要求通道在前(C,H,W),而OpenCV读取的帧是通道在后(H,W,C),必须用permute调整维度,这也是可能导致Colab正常本地报错的隐藏原因。

内容的提问来源于stack exchange,提问作者ARUN PRAVEEN P

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 21:27:12