有没有一种更简单的方法在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]


这对我来说看起来足够干净。 - coderoftheday
那么,问题是什么? - mece1390
@mece1390,楼主想要一种更简洁的方法来完成它。 - coderoftheday
清洁工说“我找到了一个可行的方法,但它很复杂”,这句话的意思是什么? 什么因素使它更加简洁? 什么因素使它变得复杂? - mece1390
你好,感谢您的评论。我已经得到了两个更简单和优雅的答案,这正是我的目标。感谢您的回答! - user14421092
3个回答

3

我认为答案已经很清楚了,所以我不会添加任何解释。

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

1
我建议您查看sci-kit learn库,因为它包含了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%


0

我希望这能帮助到某些人。Sklearn有一个库可以轻松实现:

from sklearn.model_selection import train_test_split

X = np.arange(15).reshape((5, 3))
>>> X
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11],
       [12, 13, 14]])

X_train, X_test =train_test_split(X, test_size=0.3, random_state=42)

>>> X_train
array([[ 6,  7,  8],
       [ 0,  1,  2],
       [ 9, 10, 11]])

>>> X_test
array([[ 3,  4,  5],
       [12, 13, 14]])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接