Adam_1 not found in checkpoint

本文解决了一个在使用预训练模型继续训练时遇到的Adam_1notfoundincheckpoint错误。通过GitHub上的解决方案,介绍了如何使用optimistic_restore函数来适配不同模型的参数,确保训练过程的顺利进行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天训练网上的代码,目前想基于他们训练好的代码,restore ckpt文件的参数以后,再接着训练。

但是加载完数据以后,报错为

Adam_1 not found in checkpoint

经过查找,应该是他们训练好的模型,没有存这些参数,经过查找方法,在GitHub上找到了答案,具体就是在checkpoint里找到所有的参数,和model文件里面的匹配,匹配上就用,匹配不上就算了。

def optimistic_restore(session, save_file):
	reader = tf.train.NewCheckpointReader(save_file)
	saved_shapes = reader.get_variable_to_shape_map()
	var_names = sorted([(var.name, var.name.split(':')[0]) for var in tf.global_variables()
			if var.name.split(':')[0] in saved_shapes])
	restore_vars = []
        name2var = dict(zip(map(lambda x:x.name.split(':')[0], tf.global_variables()), tf.global_variables()))
	with tf.variable_scope('', reuse=True):
		for var_name, saved_var_name in var_names:
			curr_var = name2var[saved_var_name]
			var_shape = curr_var.get_shape().as_list()
			if var_shape == saved_shapes[saved_var_name]:
				restore_vars.append(curr_var)
				saver = tf.train.Saver(restore_vars) #只加载checkpoint有参数的
				saver.restore(session, save_file)
(yolo) F:\BaiduNetdiskDownload\Jetson Orin NX\附件\源代码\yoloV5-5.0\yolov5\yolov5>python ./train.py github: skipping check (offline) Traceback (most recent call last): File "F:\BaiduNetdiskDownload\Jetson Orin NX\附件\源代码\yoloV5-5.0\yolov5\yolov5\train.py", line 514, in <module> opt.data, opt.cfg, opt.hyp = check_file(opt.data), check_file(opt.cfg), check_file(opt.hyp) # check files File "F:\BaiduNetdiskDownload\Jetson Orin NX\附件\源代码\yoloV5-5.0\yolov5\yolov5\utils\general.py", line 151, in check_file assert len(files), 'File Not Found: %s' % file # assert file was found AssertionError: File Not Found: data/data.yaml (yolo) F:\BaiduNetdiskDownload\Jetson Orin NX\附件\源代码\yoloV5-5.0\yolov5\yolov5>python ./train.py github: skipping check (offline) YOLOv5 2023-4-25 torch 2.7.1+cu128 CUDA:0 (NVIDIA GeForce RTX 4080 Laptop GPU, 12281.5MB) Namespace(weights='yolov5s.pt', cfg='', data='data.yaml', hyp='data/hyp.scratch.yaml', epochs=300, batch_size=16, img_size=[640, 640], rect=False, resume=False, nosave=False, notest=False, noautoanchor=False, evolve=False, bucket='', cache_images=False, image_weights=False, device='', multi_scale=False, single_cls=False, adam=False, sync_bn=False, local_rank=-1, workers=8, project='runs/train', entity=None, name='exp', exist_ok=False, quad=False, linear_lr=False, label_smoothing=0.0, upload_dataset=False, bbox_interval=-1, save_period=-1, artifact_alias='latest', world_size=1, global_rank=-1, save_dir='runs\\train\\exp3', total_batch_size=16) tensorboard: Start with 'tensorboard --logdir runs/train', view at http://localhost:6006/ hyperparameters: lr0=0.01, lrf=0.2, momentum=0.937, weight_decay=0.0005, warmup_epochs=3.0, warmup_momentum=0.8, warmup_bias_lr=0.1, box=0.05, cls=0.5, cls_pw=1.0, obj=1.0, obj_pw=1.0, iou_t=0.2, anchor_t=4.0, fl_gamma=0.0, hsv_h=0.015, hsv_s=0.7, hsv_v=0.4, degrees=0.0, translate=0.1, scale=0.5, shear=0.0, perspective=0.0, flipud=0.0, fliplr=0.5, mosaic=1.0, mixup=0.0 Traceback (most recent call last): File "F:\BaiduNetdiskDownload\Jetson Orin NX\附件\源代码\yoloV5-5.0\yolov5\yolov5\train.py", line 543, in <module> train(hyp, opt, device, tb_writer) File "F:\BaiduNetdiskDownload\Jetson Orin NX\附件\源代码\yoloV5-5.0\yolov5\yolov5\train.py", line 71, in train run_id = torch.load(weights).get('wandb_id') if weights.endswith('.pt') and os.path.isfile(weights) else None File "D:\anaconda\envs\yolo\lib\site-packages\torch\serialization.py", line 1524, 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([numpy.core.multiarray._reconstruct])` or the `torch.serialization.safe_globals([numpy.core.multiarray._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.
最新发布
07-12
<think>我们正在处理用户关于YOLOv5训练报错的两个问题: 1. File Not Found: data/data.yaml 2. _pickle.UnpicklingError: STACK_GLOBAL requires str 首先,我们需要分析这两个错误的原因,然后给出解决方案。 问题1:File Not Found: data/data.yaml 这个错误通常发生在YOLOv5训练时,因为系统找不到`data.yaml`文件。`data.yaml`文件是数据集配置文件,它指定了训练集、验证集、测试集的路径以及类别名称等信息。 可能的原因: - 文件路径错误:用户可能将`data.yaml`放在了错误的目录,或者训练命令中指定的路径不正确。 - 文件命名错误:可能是文件名拼写错误。 - 数据集路径未正确设置:在`data.yaml`中指定的图片路径可能不存在。 问题2:_pickle.UnpicklingError: STACK_GLOBAL requires str 这个错误通常发生在加载模型权重文件(.pt或.pth)时,表明权重文件可能已损坏,或者使用的PyTorch版本与生成权重文件的版本不兼容。 可能的原因: - 权重文件损坏:下载过程中可能中断,导致文件不完整。 - 版本不兼容:用户使用的PyTorch版本与训练该权重所使用的版本不一致。 - 权重文件格式问题:可能权重文件不是PyTorch模型文件,或者被错误地修改。 接下来,我们分别给出解决方案。 解决方案1:解决File Not Found: data/data.yaml 步骤1:检查文件路径 确保`data.yaml`文件位于正确的目录。通常,YOLOv5期望该文件在`data/`目录下(相对于项目根目录)。如果用户将数据集放在其他地方,需要在训练命令中指定正确的路径。 例如,如果`data.yaml`文件在`/path/to/your/dataset/`目录下,则训练命令应该类似: ```bash python train.py --data /path/to/your/dataset/data.yaml ... ``` 步骤2:检查文件内容 打开`data.yaml`文件,确保其中的路径设置正确。特别是`train`、`val`和`test`的路径。这些路径可以是绝对路径,也可以是相对于项目根目录的相对路径。 示例`data.yaml`内容: ```yaml train: ../datasets/images/train val: ../datasets/images/val test: ../datasets/images/test nc: 3 # 类别数量 names: ['class1', 'class2', 'class3'] # 类别名称 ``` 步骤3:检查文件是否存在 在命令行中,使用`ls`命令(Linux/macOS)或`dir`命令(Windows)检查文件是否存在: ```bash ls /path/to/your/dataset/data.yaml ``` 如果文件不存在,需要重新创建或下载。 解决方案2:解决_pickle.UnpicklingError: STACK_GLOBAL requires str 步骤1:重新下载权重文件 如果权重文件损坏,尝试重新下载。官方预训练权重可以从YOLOv5的发布页面或通过提供的URL下载。 步骤2:检查PyTorch版本 确保使用的PyTorch版本与训练权重的版本兼容。YOLOv5通常要求PyTorch>=1.7。可以通过以下命令查看PyTorch版本: ```bash python -c "import torch; print(torch.__version__)" ``` 步骤3:更新PyTorch和YOLOv5 如果版本过旧,更新PyTorch和YOLOv5到最新版本: ```bash pip install --upgrade torch torchvision pip install --upgrade -r requirements.txt # 在YOLOv5项目目录下 ``` 步骤4:尝试使用官方提供的权重 使用官方提供的预训练权重(如`yolov5s.pt`)进行测试,看是否同样报错。如果官方权重可以加载,则说明用户自己的权重文件有问题。 步骤5:检查权重文件来源 如果权重文件是用户自己训练的,检查训练过程中是否被中断,导致保存不完整。如果是,需要重新训练。 步骤6:使用torch.load的map_location参数 有时,加载权重时指定`map_location`参数可以避免一些错误,尤其是当训练和测试环境不同(如CPU/GPU)时。但此错误可能与版本不兼容更相关。 如果上述步骤无法解决,可以尝试使用以下代码片段加载权重(仅用于诊断): ```python import torch try: model = torch.load('path/to/weights.pt', map_location='cpu') except Exception as e: print(e) ``` 但是,由于错误是`_pickle.UnpicklingError`,这通常意味着文件在unpickle过程中出错,可能文件本身已经损坏。 总结: 对于第一个问题,重点检查文件路径和内容;对于第二个问题,重点检查权重文件完整性和版本兼容性。 最后,建议用户按照官方文档的步骤重新准备数据集和配置环境,以确保一致性。 相关问题: 1. 如何正确配置YOLOv5的数据集? 2. YOLOv5训练时常见的版本兼容性问题有哪些? 3. 如何解决PyTorch模型加载时的UnpicklingError?</think>### YOLOv5 训练报错解决方案 #### 1. **File Not Found: data/data.yaml** 此错误表示 YOLOv5 无法找到数据集配置文件。请按以下步骤解决: **步骤 1:检查文件路径** - 确保 `data.yaml` 文件存在于正确路径: ```bash # 示例目录结构 yolov5/ ├── data/ │ └── data.yaml # 配置文件位置 ├── datasets/ │ ├── images/ # 存放所有图片 │ └── labels/ # 存放所有标签 ``` - 若文件在其他位置,需在训练命令中指定绝对路径: ```bash python train.py --data /绝对路径/自定义数据集/data.yaml ``` **步骤 2:验证文件内容** - 打开 `data.yaml` 检查路径和类别设置: ```yaml train: ../datasets/images/train # 训练集路径 val: ../datasets/images/val # 验证集路径 nc: 3 # 类别数量 names: ['cat', 'dog', 'person'] # 类别名称(顺序必须与标签一致) ``` - **重点检查**: - 路径使用 `../` 表示上级目录 - `names` 必须与标签文件中的类别 ID 顺序完全匹配 **步骤 3:重建缓存文件** 删除旧缓存后重新运行训练,YOLOv5 会自动生成新缓存: ```bash rm datasets/images/*.cache # 删除图片缓存 rm datasets/labels/*.cache # 删除标签缓存 python train.py --data data/data.yaml ``` --- #### 2. **_pickle.UnpicklingError: STACK_GLOBAL requires str** 此错误通常由 PyTorch 版本不兼容或权重文件损坏引起: **步骤 1:更新 PyTorch 和 YOLOv5** ```bash # 更新 PyTorch(推荐 >=1.10) pip install torch==1.13.1 torchvision==0.14.1 # 更新 YOLOv5 代码库 git pull https://github.com/ultralytics/yolov5 ``` **步骤 2:验证权重文件完整性** - 官方权重需从 [YOLOv5 Release](https://github.com/ultralytics/yolov5/releases) 重新下载 - 使用 MD5 校验(示例为 yolov5s.pt): ```bash md5sum yolov5s.pt # 正确 MD5: 8c9e8a0607dfe96b5880ed8f3430b3ef ``` **步骤 3:兼容性加载(临时方案)** 在 `test.py` 或 `train.py` 中添加加载参数: ```python model = torch.load('weights.pt', map_location='cpu', pickle_module=pickle) ``` **步骤 4:重建权重文件** 若仍失败,尝试转换权重格式: ```python import torch model = torch.load('损坏的.pt', map_location='cpu') torch.save(model.state_dict(), '修复的.pt') # 仅保存模型参数 ``` --- ### 关键预防措施 1. **路径规范**: - 始终使用绝对路径或相对于 `yolov5/` 目录的相对路径 - 避免路径中包含中文或特殊字符 2. **版本一致性**: ```bash pip install -r requirements.txt # 安装 exact 版本 ``` 3. **数据集验证**: - 运行自动检查脚本: ```bash python utils/general.py --data data/data.yaml ``` > 引用说明:YOLOv5 的路径配置需严格遵循目录规范[^1],权重兼容性问题常见于 PyTorch 版本升级场景[^4]。 --- ### 相关问题 1. 如何正确划分 YOLOv5 数据集中的训练集/验证集/测试集? 2. YOLOv5 训练中出现 `CUDA out of memory` 错误如何解决? 3. 如何将 YOLOv5 模型部署到边缘计算设备(如 Jetson Nano)? 4. YOLOv5 的 `data.yaml` 文件中 `nc` 和 `names` 参数不一致会导致什么问题?
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值