训练YOLOv7-w6模型触发IndexError无法启动训练求助
YOLOv7-w6训练启动失败:IndexError: list index out of range 解决方案
我尝试训练YOLOv7的YOLOv7-w6变体,训练无法启动,报错信息如下:
Epoch gpu_mem box obj cls total labels img_size 0% 0/1827 [00:00<?, ?it/s]/content/yolov7/train.py:353: DeprecationWarning: non-integer arguments to randrange() have been deprecated since Python 3.10 and will be removed in a subsequent version sz = random.randrange(imgsz * 0.5, imgsz * 1.5 + gs) // gs * gs # size 0% 0/1827 [00:01<?, ?it/s] Traceback (most recent call last): File "/content/yolov7/train.py", line 616, in <module> train(hyp, opt, device, tb_writer) File "/content/yolov7/train.py", line 363, in train loss, loss_items = compute_loss_ota(pred, targets.to(device), imgs) # loss scaled by batch_size File "/content/yolov7/utils/loss.py", line 585, in __call__ bs, as_, gjs, gis, targets, anchors = self.build_targets(p, targets, imgs) File "/content/yolov7/utils/loss.py", line 677, in build_targets b, a, gj, gi = indices[i] IndexError: list index out of range
针对这个错误,给出以下排查和解决步骤:
检查数据集标注合法性
YOLO标注要求为class x_center y_center width height格式,且所有坐标值需归一化到0-1范围内:- 确认没有标注值超出0-1的情况(比如误写为像素值而非归一化值)
- 检查是否存在无标注的图片(对应标签文件为空)
- 确保标注的类别索引不超过模型配置文件(如
yolov7-w6.yaml)中nc字段定义的类别数
适配锚框与输入尺寸
YOLOv7-w6默认锚框是针对特定尺寸设计的,若自定义了img_size或数据集目标尺寸差异大,会导致锚框匹配失败:- 运行
python utils/autoanchor.py自动计算适配当前数据集的锚框,替换cfg/w6/yolov7-w6.yaml中的anchors字段 - 确保
img_size参数是32的整数倍(YOLO模型输入尺寸必须满足该要求)
- 运行
修复Python版本兼容警告
报错中的DeprecationWarning是Python 3.10+对randrange()参数的要求导致,修改train.py第353行:
原代码:sz = random.randrange(imgsz * 0.5, imgsz * 1.5 + gs) // gs * gs # size修改为:
sz = random.randrange(int(imgsz * 0.5), int(imgsz * 1.5 + gs)) // gs * gs # size验证数据集路径与配置
确认data.yaml中train、val路径正确,数据集结构符合YOLO标准:数据集根目录/ images/ train/ # 训练图片 val/ # 验证图片 labels/ train/ # 训练标签 val/ # 验证标签
内容的提问来源于stack exchange,提问作者Mohamed Hedeya
相关产品推荐
相关产品推荐

