split and save data def preparedata( root: str, respathfoler: str, auxinfo: str,…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
def prepare_data( root: str, res_path_foler: str, aux_info: str, val_rate: float = 0.15): random.seed(0) # 保证随机结果可复现 assert os.path.exists(root), "dataset root: {} does not exist.".format(root)
# 遍历文件夹,一个文件夹对应一个类别
classes = [cla for cla in os.listdir(root) if os.path.isdir(os.path.join(root, cla))]
# 排序,保证各平台顺序一致
classes.sort()
# 生成类别名称以及对应的数字索引
class_indices = dict((k, v) for v, k in enumerate(classes))
json_str = json.dumps(dict((val, key) for key, val in class_indices.items()), indent=4)
with open('class_indices.json', 'w') as json_file:
json_file.write(json_str)
train_images_path = [] # 存储训练集的所有图片路径
train_images_label = [] # 存储训练集图片对应索引信息
val_images_path = [] # 存储验证集的所有图片路径
val_images_label = [] # 存储验证集图片对应索引信息
every_class_num = [] # 存储每个类别的样本总数
supported = [".jpg", ".JPG", ".png", ".PNG"] # 支持的文件后缀类型
train_enhance_images_path = []
val_enhance_images_path = []
# 遍历每个文件夹下的文件
for cla in classes:
cla_path = os.path.join(root, cla)
# 遍历获取supported支持的所有文件路径
images = [os.path.join(root, cla, i) for i in os.listdir(cla_path)
if os.path.splitext(i)[-1] in supported]
# 排序,保证各平台顺序一致
images.sort()
# 获取该类别对应的索引
image_class = class_indices[cla]
# 记录该类别的样本数量
every_class_num.append(len(images))
# val_path_prefix = os.path.join(root, f"../{aux_info}_/{val_path_name}/{cla}") # <-
train_path_prefix = f"{res_path_foler}/{aux_info}_/TrainData/{cla}"
val_path_prefix = f"{res_path_foler}/{aux_info}_/ValData/{cla}"
train_enhance_path_prefix = f"{res_path_foler}/{aux_info}_/TrainDataEnhance/{cla}"
val_enhance_path_prefix = f"{res_path_foler}/{aux_info}_/ValDataEnhance/{cla}"
random.shuffle(images) # [val_data, train_data]
data_size = len(images)
for i in range(data_size):
if i < data_size * val_rate: # <- val_data
val_images_path.append(images[i])
if os.path.exists(val_path_prefix) is False:
os.makedirs(val_path_prefix)
shutil.copyfile(images[i], os.path.join(val_path_prefix, os.path.basename(images[i])))
else: # <- train_data
train_images_path.append(images[i])
if os.path.exists(train_path_prefix) is False:
os.makedirs(train_path_prefix)
shutil.copyfile(images[i], os.path.join(train_path_prefix, os.path.basename(images[i])))
# ------------------------------
source = val_path_prefix
dest = val_enhance_path_prefix
if os.path.exists(dest) is False: # <- 没有才增强
batch_enhance(source, dest)
images = [os.path.join(val_enhance_path_prefix, file) for file in os.listdir(val_enhance_path_prefix)]
label = [image_class for _ in range(len(images))]
images.sort()
val_enhance_images_path.extend(images)
val_images_label.extend(label)
# ------------------------------
source = train_path_prefix
dest = train_enhance_path_prefix
if os.path.exists(dest) is False: # <- 没有才增强
batch_enhance(source, dest)
images = [os.path.join(train_enhance_path_prefix, file) for file in os.listdir(train_enhance_path_prefix)]
label = [image_class for _ in range(len(images))]
images.sort()
train_enhance_images_path.extend(images)
train_images_label.extend(label)
print("{} images were found in the dataset.".format(sum(every_class_num)))
print("{} images for training.".format(len(train_images_path)))
print("{} images for validation.".format(len(val_images_path)))
print("{} enhanced images for training.".format(len(train_enhance_images_path)))
print("{} enhanced images for validation.".format(len(val_enhance_images_path)))
assert len(train_images_path) > 0, "number of training images must greater than 0."
assert len(val_images_path) > 0, "number of validation images must greater than 0."
return train_enhance_images_path, train_images_label, val_enhance_images_path, val_images_label
上面是我修改后的代码,我把数组增强(一张图增强成5张不同图片)放到划分数据之后了 下面是修改前的,是直接对数据增强后的来划分 请帮我详细区分一下两代码的逻辑变化 def preare_test_and_read_split_data( root: str, enforce_tag: str, val_path_name: str, test_path_name: str, aux_info: str, val_rate: float = 0.15, test_rate=0.0): random.seed(0) # 保证随机结果可复现 assert os.path.exists(root), "dataset root: {} does not exist.".format(root)
# 遍历文件夹,一个文件夹对应一个类别
flower_class = [cla for cla in os.listdir(root) if os.path.isdir(os.path.join(root, cla))]
# 排序,保证各平台顺序一致
flower_class.sort()
# 生成类别名称以及对应的数字索引
class_indices = dict((k, v) for v, k in enumerate(flower_class))
json_str = json.dumps(dict((val, key) for key, val in class_indices.items()), indent=4)
with open('class_indices.json', 'w') as json_file:
json_file.write(json_str)
train_images_path = [] # 存储训练集的所有图片路径
train_images_label = [] # 存储训练集图片对应索引信息
val_images_path = [] # 存储验证集的所有图片路径
val_images_label = [] # 存储验证集图片对应索引信息
every_class_num = [] # 存储每个类别的样本总数
supported = [".jpg", ".JPG", ".png", ".PNG"] # 支持的文件后缀类型
# 遍历每个文件夹下的文件
for cla in flower_class:
cla_path = os.path.join(root, cla)
# 遍历获取supported支持的所有文件路径
images = [os.path.join(root, cla, i) for i in os.listdir(cla_path)
if os.path.splitext(i)[-1] in supported]
# 排序,保证各平台顺序一致
images.sort()
# 获取该类别对应的索引
image_class = class_indices[cla]
# 记录该类别的样本数量
every_class_num.append(len(images))
val_path_prefix = os.path.join(root, f"../{aux_info}_/{val_path_name}_{enforce_tag}/{cla}") # <-
test_path_prefix = os.path.join(root, f"../{aux_info}_/{test_path_name}_{enforce_tag}/{cla}") # <-
random.shuffle(images) # [val_data, test_data, train_data]
data_size = len(images)
for i in range(data_size):
if i < data_size * val_rate: # <- val_data
val_images_path.append(images[i])
val_images_label.append(image_class)
if os.path.exists(val_path_prefix) is False:
os.makedirs(val_path_prefix)
shutil.copyfile(images[i], os.path.join(val_path_prefix, os.path.basename(images[i])))
elif i < data_size * val_rate + data_size * test_rate: # <- test_data
if os.path.exists(test_path_prefix) is False:
os.makedirs(test_path_prefix)
shutil.copyfile(images[i], os.path.join(test_path_prefix, os.path.basename(images[i])))
else: # <- train_data
train_images_path.append(images[i])
train_images_label.append(image_class)
print("{} images were found in the dataset.".format(sum(every_class_num)))
print("{} images for training.".format(len(train_images_path)))
print("{} images for validation.".format(len(val_images_path)))
assert len(train_images_path) > 0, "number of training images must greater than 0."
assert len(val_images_path) > 0, "number of validation images must greater than 0."
return train_images_path, train_images_label, val_images_path, val_images_label
两段代码的核心区别在于数据增强的时机和数据集的构成,以下是详细对比:
preare_test_and_read_split_data)直接处理原始数据
数据集构成
return train_images_path, train_images_label, val_images_path, val_images_label
关键流程
graph TD
A[原始数据] --> B[划分数据集]
B --> C[复制验证集]
B --> D[复制测试集]
B --> E[记录训练集路径]
C --> F[返回原始数据路径]
prepare_data)划分后增强
batch_enhance()生成增强图片(1→5)数据集构成
return train_enhance_images_path, train_images_label, val_enhance_images_path, val_images_label
增强触发条件
if os.path.exists(dest) is False:
batch_enhance(source, dest) # 仅当目标文件夹不存在时才增强
文件夹结构变化
res_path_folder/
└── aux_info_/
├── TrainData/ # 原始训练图片
├── ValData/ # 原始验证图片
├── TrainDataEnhance/ # 增强后的训练图片(5倍)
└── ValDataEnhance/ # 增强后的验证图片(5倍)
关键流程
graph TD
A[原始数据] --> B[划分并复制]
B --> C[训练集原始文件夹]
B --> D[验证集原始文件夹]
C --> E[数据增强] --> F[增强训练图片]
D --> G[数据增强] --> H[增强验证图片]
F --> I[返回增强训练路径]
H --> J[返回增强验证路径]
| 特性 | 修改前代码 | 修改后代码 |
|---|---|---|
| 增强时机 | 无增强 | 划分后增强 |
| 返回数据 | 原始图片路径 | 增强后的图片路径(5倍数量) |
| 数据量 | 原始数量 | 训练/验证集各扩大5倍 |
| 存储结构 | 单层文件夹 | 原始+增强的双层文件夹结构 |
| 增强触发 | 无 | 智能跳过已增强文件夹 |
| 训练/验证来源 | 直接使用原始数据 | 使用增强后的数据 |
修改后方案是更专业的机器学习数据预处理流程,符合工业级实践标准。尤其适合小样本数据集,通过增强显著提升数据多样性。