当出现如下错误时: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 theweights_only
argument intorch.load
fromFalse
toTrue
. Re-runningtorch.load
withweights_only
set toFalse
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 withweights_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 usetorch.serialization.add_safe_globals([_reconstruct])
or thetorch.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 https://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