|
| 1 | +import numpy as np |
| 2 | + |
| 3 | + |
| 4 | +def train_test_split(*arrays, test_size=None, train_size=None, random_state=None, shuffle=True, stratify=None): |
| 5 | + """Split arrays or matrices into random train and test subsets""" |
| 6 | + if random_state is not None: |
| 7 | + np.random.seed(random_state) |
| 8 | + n_samples = len(arrays[0]) |
| 9 | + if test_size is None and train_size is None: |
| 10 | + test_size = 0.25 |
| 11 | + if train_size is not None: |
| 12 | + n_train = int(train_size * n_samples) if isinstance(train_size, float) else train_size |
| 13 | + n_test = n_samples - n_train |
| 14 | + else: |
| 15 | + n_test = int(test_size * n_samples) if isinstance(test_size, float) else test_size |
| 16 | + n_train = n_samples - n_test |
| 17 | + indices = np.arange(n_samples) |
| 18 | + if shuffle: |
| 19 | + if stratify is not None: |
| 20 | + unique_classes, class_indices = np.unique(stratify, return_inverse=True) |
| 21 | + train_indices, test_indices = [], [] |
| 22 | + for i in range(len(unique_classes)): |
| 23 | + cls_indices = indices[class_indices == i] |
| 24 | + np.random.shuffle(cls_indices) |
| 25 | + n_cls_test = int(n_test * len(cls_indices) / n_samples) |
| 26 | + test_indices.extend(cls_indices[:n_cls_test]) |
| 27 | + train_indices.extend(cls_indices[n_cls_test:]) |
| 28 | + indices = np.array(train_indices + test_indices) |
| 29 | + n_train = len(train_indices) |
| 30 | + else: |
| 31 | + np.random.shuffle(indices) |
| 32 | + res = [] |
| 33 | + for arr in arrays: |
| 34 | + if isinstance(arr, list): |
| 35 | + res.append([arr[i] for i in indices[:n_train]]) |
| 36 | + res.append([arr[i] for i in indices[n_train:]]) |
| 37 | + else: |
| 38 | + res.append(arr[indices[:n_train]]) |
| 39 | + res.append(arr[indices[n_train:]]) |
| 40 | + return res |
| 41 | + |
| 42 | + |
| 43 | +def resample(*arrays, n_samples=None, random_state=None, replace=True): |
| 44 | + """Resample arrays or matrices in a consistent way""" |
| 45 | + if random_state is not None: |
| 46 | + np.random.seed(random_state) |
| 47 | + n_samples = n_samples or len(arrays[0]) |
| 48 | + indices = np.random.choice(len(arrays[0]), size=n_samples, replace=replace) |
| 49 | + res = [] |
| 50 | + for arr in arrays: |
| 51 | + if isinstance(arr, list): |
| 52 | + res.append([arr[i] for i in indices]) |
| 53 | + else: |
| 54 | + res.append(arr[indices]) |
| 55 | + return res[0] if len(res) == 1 else res |
0 commit comments