You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

YOLOv9自定义模型训练时data.yaml相对路径异常问题

解决YOLOv9 data.yaml相对路径重复拼接问题

问题核心

使用相对路径配置data.yaml时,YOLO解析路径出现重复拼接,导致找不到数据集目录;改用绝对路径可正常训练,但无法适配多机器环境。

修复方案

1. 简化data.yaml的路径配置

将data.yaml中的路径改为相对于自身所在目录的短路径,避免重复前缀:

# data.yaml 位于 OIT_model/customOIT/customdatasetyolo/ 目录下
path: ./  # 表示当前yaml文件所在目录,也可直接删除该行
train: train
val: val
nc: 1
names: ['5']

原理:YOLO会自动将path字段与train/val字段拼接。原配置中path和train/val都写了完整相对路径,导致拼接后路径重复,最终生成错误的多层嵌套路径。

2. 确保脚本路径解析稳定

在训练脚本中,将传入的data.yaml路径转换为绝对路径,避免因工作目录变化导致的路径解析错误:

import os
from ultralytics import YOLO
import shutil

def train_custom_dataset_yolo(data_path, epochs=100, imgsz=64, verbose=True):
    # 转换为绝对路径,消除工作目录影响
    data_path = os.path.abspath(data_path)
    model = YOLO("OIT_model/yolov9c.pt")
    save_dir = 'OIT_model/customOIT/yolocustomtrainoutput'
    
    # 清空并重建保存目录
    if os.path.exists(save_dir):
        for file in os.listdir(save_dir):
            file_path = os.path.join(save_dir, file)
            if os.path.isfile(file_path) or os.path.islink(file_path):
                os.unlink(file_path)
            elif os.path.isdir(file_path):
                shutil.rmtree(file_path)
    os.makedirs(save_dir, exist_ok=True)
    
    model.train(data=data_path, epochs=epochs, imgsz=imgsz, verbose=verbose, save_dir=save_dir)
    return

train_custom_dataset_yolo('OIT_model/customOIT/customdatasetyolo/data.yaml', epochs=1, imgsz=64, verbose=True)

验证逻辑

修改后,YOLO会以data.yaml所在目录为根,直接读取train/val子目录,生成的正确路径为:
C:\GitHub\Anomaly_detection_combine\OIT_model\customOIT\customdatasetyolo\val
与期望的有效路径完全一致。

内容的提问来源于stack exchange,提问作者OLLY

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 11:23:21