将jaffe划分为训练集,验证集和测试集的代码
时间: 2023-10-08 16:07:59 浏览: 58
以下是将Jaffe数据集划分为训练集、验证集和测试集的Python代码:
```python
import os
import random
import shutil
# 数据集路径
data_dir = 'jaffe'
# 划分比例
train_ratio = 0.6
val_ratio = 0.2
test_ratio = 0.2
# 获取数据集列表
data_list = os.listdir(data_dir)
random.shuffle(data_list)
# 计算划分点
num_data = len(data_list)
num_train = int(num_data * train_ratio)
num_val = int(num_data * val_ratio)
num_test = num_data - num_train - num_val
# 划分数据集
train_list = data_list[:num_train]
val_list = data_list[num_train:num_train+num_val]
test_list = data_list[num_train+num_val:]
# 创建目标文件夹
train_dir = os.path.join(data_dir, 'train')
val_dir = os.path.join(data_dir, 'val')
test_dir = os.path.join(data_dir, 'test')
os.makedirs(train_dir, exist_ok=True)
os.makedirs(val_dir, exist_ok=True)
os.makedirs(test_dir, exist_ok=True)
# 复制文件到目标文件夹
for filename in train_list:
src_path = os.path.join(data_dir, filename)
dst_path = os.path.join(train_dir, filename)
shutil.copy(src_path, dst_path)
for filename in val_list:
src_path = os.path.join(data_dir, filename)
dst_path = os.path.join(val_dir, filename)
shutil.copy(src_path, dst_path)
for filename in test_list:
src_path = os.path.join(data_dir, filename)
dst_path = os.path.join(test_dir, filename)
shutil.copy(src_path, dst_path)
```
以上代码首先设置了数据集路径 `data_dir` 和划分比例 `train_ratio`、`val_ratio`、`test_ratio`。然后随机打乱数据集列表,并根据比例计算训练集、验证集和测试集的数量。接着创建目标文件夹,并将文件根据划分写入到对应的目标文件夹中。
阅读全文