python - 有没有一种更简单的方法可以将列表随机拆分为子列表而不在 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]
解决方案
我认为答案是不言自明的,所以我没有添加任何解释。
import random
random.shuffle(files)
k = test_count
set1 = files[:k]
set2 = files[k:1.5k]
set3 = files[1.5k:]
推荐阅读
- angular - Angular 7 中注入服务与单例服务的内存和性能比较
- vb.net - 用数据集填充组合框
- java - 如何使用 java servlet 输出 SQL 查询的结果
- nsis - 我想知道如何使用 NSIS 从 C++ 可执行文件中调用函数
- sql-server - sql server中的复合主键
- android - 尝试设置 chaquopy 时出现错误(错误显示:启动失败(org.gradle.process.internal.ExecException)
- r - 我正在定义的函数的“错误:意外符号”,但我无法确定错误的来源
- python - TensorFlow Python 3.7
- python - pytorch:无法理解 model.forward 函数
- php - 上传时重命名PDF PHP