Yolov5加载自定义权重时出现ModuleNotFoundError问题求助
解决Yolov5自定义权重加载时的ModuleNotFoundError问题
问题根源
你的测试脚本无法找到Yolov5的models和utils模块,因为脚本所在目录不在Yolov5仓库的根目录下,且未将Yolov5路径添加到Python的模块搜索路径中。
解决建议
将测试脚本移至Yolov5根目录
假设你的Yolov5仓库位于C:\yolov5,将object-detection-test.py移动到该文件夹内。同时修改模型路径为相对路径:model = attempt_load("runs/train/exp3/weights/best.pt", map_location=device).autoshape()手动添加Yolov5路径到sys.path
在测试脚本的最顶部添加以下代码,将Yolov5仓库的绝对路径加入Python的模块搜索路径:import sys sys.path.append("C:/yolov5") # 替换为你实际的Yolov5文件夹路径注意路径使用正斜杠(
/)或双反斜杠(\\),避免转义字符问题。同时将模型路径改为绝对路径:model = attempt_load("C:/yolov5/runs/train/exp3/weights/best.pt", map_location=device).autoshape()统一设备配置
先确定设备再加载模型,确保模型运行在正确的硬件上:device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model = attempt_load("C:/yolov5/runs/train/exp3/weights/best.pt", map_location=device).autoshape() model.to(device)
内容的提问来源于stack exchange,提问作者JayBTProgramming
相关产品推荐
相关产品推荐

