pytorch2.6.0版本测试YOLOv5中detect.py错误解决办法
- IT业界
- 2025-09-17 11:27:02

当出现如下错误时:File “D:\PythonProject_base\yolov5-v5.0\detect.py”, line 178, in detect() File “D:\PythonProject_base\yolov5-v5.0\detect.py”, line 34, in detect model = attempt_load(weights, map_location=device) # load FP32 model File “D:\PythonProject_base\yolov5-v5.0\models\experimental.py”, line 118, in attempt_load ckpt = torch.load(w, map_location=map_location) # load File “D:\PythonProject_base.venv\lib\site-packages\torch\serialization.py”, line 1470, in load raise pickle.UnpicklingError(_get_wo_message(str(e))) from None _pickle.UnpicklingError: Weights only load failed. This file can still be loaded, to do so you have two options, do those steps only if you trust the source of the checkpoint. (1) In PyTorch 2.6, we changed the default value of the weights_only argument in torch.load from False to True. Re-running torch.load with weights_only set to False will likely succeed, but it can result in arbitrary code execution. Do it only if you got the file from a trusted source. (2) Alternatively, to load with weights_only=True please check the recommended steps in the following error message. WeightsUnpickler error: Unsupported global: GLOBAL numpy.core.multiarray._reconstruct was not an allowed global by default. Please use torch.serialization.add_safe_globals([_reconstruct]) or the torch.serialization.safe_globals([_reconstruct]) context manager to allowlist this global if you trust this class/function. Check the documentation of torch.load to learn more about types accepted by default with weights_only pytorch.org/docs/stable/generated/torch.load.html.
错误发生在 attempt_load 函数里调用 torch.load 时,这是因为 PyTorch 2.6 及之后版本中 weights_only 参数默认值改变,导致加载包含不被允许的全局对象 。numpy.core.multiarray._reconstruct 的文件失败。
下面为你提供具体的解决办法: 如果你确定文件来源可靠,可以把 torch.load 中的 weights_only 参数设置为 False。在 models/experimental.py 文件里找到 attempt_load 函数,将 torch.load 修改如下: # 在 models/experimental.py 文件中找到 attempt_load 函数 def attempt_load(weights, map_location=None): # ... 其他代码 ... ckpt = torch.load(w, map_location=map_location, weights_only=False) # 修改这一行,添加 weights_only=False # ... 其他代码 ... return model也要将detect.py文件中的torch.load中的weights_only参数改为False
pytorch2.6.0版本测试YOLOv5中detect.py错误解决办法由讯客互联IT业界栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“pytorch2.6.0版本测试YOLOv5中detect.py错误解决办法”