所以我有一个主文件夹,其中包含子文件夹,这些子文件夹又包含数据集的图像,如下所示。
-main_db
---CLASS_1
-----img_1
-----img_2
-----img_3
-----img_4
---CLASS_2
-----img_1
-----img_2
-----img_3
-----img_4
---CLASS_3
-----img_1
-----img_2
-----img_3
-----img_4
我需要将此数据集分成两部分,即训练数据(70%)和测试数据(30%)。下面是我想要实现的层次结构
-main_db
---training_data
-----CLASS_1
--------img_1
--------img_2
--------img_3
--------img_4
---CLASS_2
--------img_1
--------img_2
--------img_3
--------img_4
---测试数据
-----CLASS_1
--------img_5
--------img_6
--------img_7
--------img_8
---CLASS_2
--------img_5
--------img_6
--------img_7
--------img_8
任何帮助表示赞赏。谢谢
我试过这个模块。但这对我不起作用。这个模块根本没有被导入。
https://github.com/jfilter/split-folders
这正是我想要的。
最佳答案
这应该这样做。它将计算每个文件夹中有多少图像,然后相应地拆分它们,将测试数据保存在具有相同结构的不同文件夹中。
将代码保存在main.py
中文件并运行命令:python3 main.py ----data_path=/path1 --test_data_path_to_save=/path2 --train_ratio=0.7
import shutil
import os
import numpy as np
import argparse
def get_files_from_folder(path):
files = os.listdir(path)
return np.asarray(files)
def main(path_to_data, path_to_test_data, train_ratio):
# get dirs
_, dirs, _ = next(os.walk(path_to_data))
# calculates how many train data per class
data_counter_per_class = np.zeros((len(dirs)))
for i in range(len(dirs)):
path = os.path.join(path_to_data, dirs[i])
files = get_files_from_folder(path)
data_counter_per_class[i] = len(files)
test_counter = np.round(data_counter_per_class * (1 - train_ratio))
# transfers files
for i in range(len(dirs)):
path_to_original = os.path.join(path_to_data, dirs[i])
path_to_save = os.path.join(path_to_test_data, dirs[i])
#creates dir
if not os.path.exists(path_to_save):
os.makedirs(path_to_save)
files = get_files_from_folder(path_to_original)
# moves data
for j in range(int(test_counter[i])):
dst = os.path.join(path_to_save, files[j])
src = os.path.join(path_to_original, files[j])
shutil.move(src, dst)
def parse_args():
parser = argparse.ArgumentParser(description="Dataset divider")
parser.add_argument("--data_path", required=True,
help="Path to data")
parser.add_argument("--test_data_path_to_save", required=True,
help="Path to test data where to save")
parser.add_argument("--train_ratio", required=True,
help="Train ratio - 0.7 means splitting data in 70 % train and 30 % test")
return parser.parse_args()
if __name__ == "__main__":
args = parse_args()
main(args.data_path, args.test_data_path_to_save, float(args.train_ratio))
关于python-3.x - 将图像数据集拆分为训练测试数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57394135/