有没有一种更简单的方法可以将列表随机拆分为子列表,而不必在python中重复元素?

2024-04-24 10:36:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用预定义的比率将列表分成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]


Tags: oftheto方法intest列表len
2条回答

我建议您查看sci工具包学习库,因为它包含为您执行此操作的train_test_split函数。但是,只使用random库来回答您的问题

# First shuffle the list randomly
files = os.listdir("C:/.../my_folder")
random.shuffle(files) 

# Then just slice
ratio = int(len(files)/5) # 20%
test_set = files[:ratio]
val_set = files[ratio:1.5*ratio] #30%

我认为答案是不言自明的,所以我没有添加任何解释

import random
random.shuffle(files)
k = test_count
set1 = files[:k]
set2 = files[k:1.5k]
set3 = files[1.5k:]

相关问题 更多 >