yolov5只划分训练集和验证集
时间: 2025-01-10 20:35:16 浏览: 43
### 划分训练集和验证集
在YOLOv5中,为了更高效地利用数据资源并简化流程,在某些情况下可能只需要划分训练集和验证集而不需要单独设立测试集。具体操作可以通过编写脚本实现自动化处理。
对于已经完成标注的数据集(通常保存为XML格式),可以采用Python编程语言来读取这些文件路径列表,并按照设定的比例将其分配到不同的子集中去。下面给出了一段用于此目的的代码片段:
```python
import os
from sklearn.model_selection import train_test_split
import shutil
def split_dataset(image_dir, label_dir, output_train_dir, output_val_dir, ratio=0.8):
images = [os.path.join(root, name) for root, dirs, files in os.walk(image_dir) for name in files if name.endswith('.jpg')]
labels = []
for img_path in images:
base_name = os.path.splitext(os.path.basename(img_path))[0]
xml_file = f"{base_name}.xml"
possible_paths = [
os.path.join(label_dir, xml_file),
*[os.path.join(root, xml_file) for root, _, _ in os.walk(label_dir)]
]
found_label_files = list(filter(lambda p: os.path.exists(p), possible_paths))
if not found_label_files:
continue
labels.append(found_label_files[0])
X_train, X_val, y_train, y_val = train_test_split(images, labels, test_size=(1-ratio))
ensure_directory(output_train_dir)
ensure_directory(output_val_dir)
copy_files(X_train, y_train, output_train_dir)
copy_files(X_val, y_val, output_val_dir)
def ensure_directory(directory):
if not os.path.isdir(directory):
os.makedirs(directory)
def copy_files(src_images, src_labels, dst_dir):
image_dst = os.path.join(dst_dir, "images")
label_dst = os.path.join(dst_dir, "labels")
ensure_directory(image_dst)
ensure_directory(label_dst)
for i, l in zip(src_images, src_labels):
shutil.copy(i, image_dst)
shutil.copy(l, label_dst)
split_dataset("/path/to/images", "/path/to/xmls", "./train", "./val") # 调用函数进行分割
```
上述代码实现了基于给定图像目录`image_dir`及其对应的标签目录`label_dir`下的所有样本对训练集与验证集进行了拆分[^2]。通过调整参数ratio可改变两者之间的比例,默认设置为80%作为训练集,剩余部分则构成验证集。
值得注意的是,当不涉及独立的测试阶段时,这种做法能够使得整个开发周期内的评估过程更为紧凑;然而,在最终部署前仍建议预留一部分未见过的真实场景图片作为实际性能评测依据。
阅读全文
相关推荐


















