将分类数据划分为训练集、测试集与验证集

    用于将指定路径下的 0-6 编号的 7 个文件夹中的数据按照 8:1:1 的比例划分到 train、val 和 test 这三个文件夹中。

1.代码功能说明

  1. 源文件夹路径:假设编号文件夹在 src_path 中,每个编号文件夹的名称为 0, 1, 2, ..., 6。
  2. 划分比例:默认按照 8:1:1 的比例划分,分别对应训练集、验证集和测试集。
  3. 数据打乱:使用 random.shuffle 将每个编号文件夹内的文件顺序打乱,确保划分均匀。
  4. 目标文件夹创建:在 dest_path 下创建 train、val 和 test 文件夹。
  5. 文件复制:使用 shutil.copy 将文件从源文件夹复制到目标文件夹。
python 复制代码
import os
import shutil
import random

def split_data(src_path, dest_path, split_ratio=(0.8, 0.1, 0.1)):
    # 创建目标文件夹结构
    for split in ['train', 'val', 'test']:
        split_path = os.path.join(dest_path, split)
        os.makedirs(split_path, exist_ok=True)
        for i in range(7):  # 创建 0-6 的子文件夹
            os.makedirs(os.path.join(split_path, str(i)), exist_ok=True)

    # 遍历编号文件夹(0-6)
    for folder in range(7):
        folder_path = os.path.join(src_path, str(folder))
        if not os.path.exists(folder_path):
            print(f"文件夹 {folder_path} 不存在,跳过...")
            continue

        # 获取文件列表并打乱顺序
        files = os.listdir(folder_path)
        random.shuffle(files)

        # 按照比例划分
        total_files = len(files)
        train_end = int(total_files * split_ratio[0])
        val_end = train_end + int(total_files * split_ratio[1])

        train_files = files[:train_end]
        val_files = files[train_end:val_end]
        test_files = files[val_end:]

        # 将文件复制到对应的目标文件夹
        for file in train_files:
            shutil.copy(os.path.join(folder_path, file), os.path.join(dest_path, "train", str(folder), file))
        for file in val_files:
            shutil.copy(os.path.join(folder_path, file), os.path.join(dest_path, "val", str(folder), file))
        for file in test_files:
            shutil.copy(os.path.join(folder_path, file), os.path.join(dest_path, "test", str(folder), file))

        print(f"文件夹 {folder_path} 已处理完成,训练集:{len(train_files)},验证集:{len(val_files)},测试集:{len(test_files)}")

# 使用
src_path = "/path/to/source/folders"  # 原始数据文件夹路径
dest_path = "/path/to/destination/folders"  # 目标文件夹路径
split_data(src_path, dest_path)
相关推荐
这就是佬们吗2 分钟前
不写Prompt,写Loop:AI编程的下一场范式迁移
人工智能·prompt·ai编程
用户9385156350716 分钟前
大模型记忆指南:从短时缓存到永久记忆,手把手带你吃透 LangChain Memory 管理
javascript·人工智能
武子康19 分钟前
机器人策略 90% 与 92%:为什么两个百分点通常不足以证明更
人工智能·llm·agent
阿里云大数据AI技术22 分钟前
PAI支持一键部署Qwen3.8-Flash-Next、GLM-5.3等最新开源模型
人工智能·开源·llm
SleepNW_POV23 分钟前
家居科普|床垫溜边塌陷成因解析与边缘加固床垫选购指南
人工智能·科技·智能家居·睡眠
FII工业富联科技服务23 分钟前
从 Vera Rubin NVL72 拆解高密度 AI 液冷:GPU 的热到底怎么被带走?
大数据·人工智能
磐时信息技术36 分钟前
SASETalk | 当智能驾驶驶入未知场景:谈谈关于SOTIF、AI安全与工程落地的思考
人工智能·安全·预期功能安全·sotif
147API1 小时前
蒸馏模型量化上线前,先查精度退化和算子兼容
大数据·人工智能·深度学习·机器学习·蒸馏
橙时数据 FineInsight1 小时前
AI 能回答数据问题,但能解释业务原因吗?
大数据·人工智能·数据分析·指标平台·fineinsight
CTA终结者1 小时前
示例、拆解和练习,要连成一条量化补课线
人工智能·python