我想使用预定义的比率将列表分成3个子列表(训练、验证、测试)。应随机选择子列表中的项目,不得重复。 (我的第一个列表包含拆分后要处理的文件夹中的图像名称。) 我找到了一种工作方法,但似乎很复杂。我很好奇有没有更简单的方法? 我的方法是:
这是我的代码:
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]
我建议您查看sci工具包学习库,因为它包含为您执行此操作的
train_test_split
函数。但是,只使用random
库来回答您的问题我认为答案是不言自明的,所以我没有添加任何解释
相关问题 更多 >
编程相关推荐