我想将一个列表分成三个子列表(训练,验证,测试),使用预定义的比例。项目应该随机选择并且不重复地分配到子列表中。
(我的第一个列表包含要处理的文件夹中图像的名称,在拆分后需要对其进行处理。)
我找到了一种可行的方法,但它似乎很复杂。我想知道是否有更简单的方法来完成这个任务?
我的方法是:
- 列出文件夹中的文件,
- 定义子列表的所需大小,
- 随机填充第一个子列表,
- 从原始列表中删除已使用的项,
- 从剩余列表中随机填充第二个子列表,
- 删除已用项目以获取第三个子列表。
import random
import os
# list files in folder
files = os.listdir("C:/.../my_folder")
# define the size of the sets: ~30% validation, ~20% test, ~50% training (remaining goes to training set)
validation_count = int(0.3 * len(files))
test_count = int(0.2 * len(files))
training_count = len(files) - validation_count - test_count
# randomly choose ~20% of files to test set
test_set = random.sample(files, k = test_count)
# remove already chosen files from original list
files_wo_test_set = [f for f in files if f not in test_set]
# randomly chose ~30% of remaining files to validation set
validation_set = random.sample(files_wo_test_set, k = validation_count)
# the remaining files going into the training set
training_set = [f for f in files_wo_test_set if f not in validation_set]