pytorch2.6.0版本测试YOLOv5中detect.py错误解决办法

当出现如下错误时: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 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

requirements: 1 package updated per /home/a123/yolo/yolov5/requirements.txt requirements: ⚠️ Restart runtime or rerun command for updates to take effect YOLOv5 🚀 2024-11-27 torch 2.6.0+cpu CPU Traceback (most recent call last): File "/home/a123/yolo/yolov5/detect.py", line 178, in <module> detect() File "/home/a123/yolo/yolov5/detect.py", line 34, in detect model = attempt_load(weights, map_location=device) # load FP32 model File "/home/a123/yolo/yolov5/models/experimental.py", line 118, in attempt_load ckpt = torch.load(w, map_location=map_location) # load File "/home/a123/.local/lib/python3.10/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 https://pytorch.org/docs/stable/generated/torch.load.html.
03-13
### 解析 YOLOv5 加载权重时出现 `_pickle.UnpicklingError` 的解决方案 当遇到 `torch.load` 导致的 `_pickle.UnpicklingError` 错误时,这通常意味着 PyTorch 版本与保存模型使用的版本不兼容或者存在其他环境配置问题。为了有效解决问题并成功加载预训练权重,可以采取以下措施: #### 1. 使用 `weights_only=True` 通过设置参数 `weights_only=True` 可以减少潜在的兼容性问题。此选项仅加载模型状态字典而不加载整个模块结构,从而提高了不同环境中加载相同模型的成功率。 ```python import torch model_weights_path = 'path_to_your_model.pth' state_dict = torch.load(model_weights_path, map_location='cpu', weights_only=True)[^1] ``` #### 2. 更新 NumPyPyTorch 至最新稳定版 确保所使用的 Python 环境中的 NumPyPyTorch 是最新的稳定版本。旧版本可能存在 bug 或者与其他库之间的接口定义有所差异,更新这些依赖项有助于消除因版本冲突引发的问题。 ```bash pip install --upgrade numpy torch torchvision torchaudio ``` #### 3. 修改 `.pth` 文件格式 如果上述方法仍无法解决问题,则可能是由于 `.pth` 文件本身存在问题。尝试重新导出该文件或将现有文件转换成更通用的形式(如 `.pt`)。有时官方发布的某些预训练模型可能不适合特定的操作系统或硬件架构,在这种情况下寻找替代资源也是必要的。 #### 4. 调整工作目录下的子包顺序 有报告指出调整安装包列表中某些项目的先后次序也可能帮助解决此类错误。特别是对于那些包含多个相互关联组件的情况来说尤为重要。可以通过修改 `requirements.txt` 来实现这一点。 ```text numpy>=1.19.2,<1.20.0 ... other_packages ``` 以上建议基于实际经验总结而来,并结合了社区反馈以及官方文档说明[^1]。希望这些建议能够协助顺利加载 YOLOv5 预训练权重。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值