File size: 3,982 Bytes
3e6ca52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#!/usr/bin/env python3
"""
Script để chia dataset thành train/val/test
"""

import os
import glob
import shutil
import random
from pathlib import Path

# Cấu hình
PROCESSED_DIR = "processed"
TRAIN_DIR = "train"
VAL_DIR = "val"
TEST_DIR = "test"

# Tỷ lệ chia dataset
TRAIN_RATIO = 0.8
VAL_RATIO = 0.1
TEST_RATIO = 0.1

def split_dataset(source_dir, train_dir, val_dir, test_dir, 
                  train_ratio=0.8, val_ratio=0.1, test_ratio=0.1, 
                  seed=42):
    """
    Chia dataset thành train/val/test
    
    Args:
        source_dir: Thư mục chứa dữ liệu đã xử lý
        train_dir: Thư mục lưu dữ liệu training
        val_dir: Thư mục lưu dữ liệu validation
        test_dir: Thư mục lưu dữ liệu test
        train_ratio: Tỷ lệ training (mặc định 0.8)
        val_ratio: Tỷ lệ validation (mặc định 0.1)
        test_ratio: Tỷ lệ test (mặc định 0.1)
        seed: Random seed để đảm bảo reproducibility
    """
    # Tạo thư mục nếu chưa có
    os.makedirs(train_dir, exist_ok=True)
    os.makedirs(val_dir, exist_ok=True)
    os.makedirs(test_dir, exist_ok=True)
    
    # Kiểm tra tỷ lệ
    if abs(train_ratio + val_ratio + test_ratio - 1.0) > 0.01:
        print("Cảnh báo: Tổng tỷ lệ không bằng 1.0, sẽ được chuẩn hóa")
        total = train_ratio + val_ratio + test_ratio
        train_ratio /= total
        val_ratio /= total
        test_ratio /= total
    
    # Lấy tất cả file .txt
    pattern = os.path.join(source_dir, "*.txt")
    files = glob.glob(pattern)
    
    if not files:
        print(f"Không tìm thấy file .txt trong {source_dir}")
        return
    
    # Shuffle với seed cố định
    random.seed(seed)
    random.shuffle(files)
    
    # Tính số file cho mỗi phần
    total_files = len(files)
    num_train = int(total_files * train_ratio)
    num_val = int(total_files * val_ratio)
    num_test = total_files - num_train - num_val  # Phần còn lại
    
    print(f"Tổng số file: {total_files}")
    print(f"Train: {num_train} files ({train_ratio*100:.1f}%)")
    print(f"Val: {num_val} files ({val_ratio*100:.1f}%)")
    print(f"Test: {num_test} files ({test_ratio*100:.1f}%)")
    
    # Chia file
    train_files = files[:num_train]
    val_files = files[num_train:num_train + num_val]
    test_files = files[num_train + num_val:]
    
    # Copy file vào thư mục tương ứng
    def copy_files(file_list, dest_dir, label):
        for file_path in file_list:
            filename = os.path.basename(file_path)
            dest_path = os.path.join(dest_dir, filename)
            shutil.copy2(file_path, dest_path)
        print(f"Đã copy {len(file_list)} file vào {dest_dir}/ ({label})")
    
    copy_files(train_files, train_dir, "train")
    copy_files(val_files, val_dir, "val")
    copy_files(test_files, test_dir, "test")
    
    print("\nHoàn thành chia dataset!")

def main():
    """Hàm chính"""
    # Kiểm tra thư mục processed
    if not os.path.exists(PROCESSED_DIR):
        print(f"Thư mục {PROCESSED_DIR} không tồn tại!")
        print("Vui lòng chạy process_data.py trước để xử lý dữ liệu.")
        return
    
    # Kiểm tra có file không
    pattern = os.path.join(PROCESSED_DIR, "*.txt")
    files = glob.glob(pattern)
    
    if not files:
        print(f"Không tìm thấy file .txt trong {PROCESSED_DIR}")
        print("Vui lòng chạy process_data.py trước để xử lý dữ liệu.")
        return
    
    # Chia dataset
    split_dataset(
        PROCESSED_DIR,
        TRAIN_DIR,
        VAL_DIR,
        TEST_DIR,
        TRAIN_RATIO,
        VAL_RATIO,
        TEST_RATIO
    )
    
    print(f"\nDataset đã được chia:")
    print(f"  - Training: {TRAIN_DIR}/")
    print(f"  - Validation: {VAL_DIR}/")
    print(f"  - Test: {TEST_DIR}/")

if __name__ == "__main__":
    main()