|
| 1 | +"""Class to perform random over-sampling.""" |
| 2 | +from __future__ import print_function |
| 3 | +from __future__ import division |
| 4 | + |
| 5 | +import numpy as np |
| 6 | + |
| 7 | +from collections import Counter |
| 8 | + |
| 9 | +from sklearn.neighbors import NearestNeighbors |
| 10 | +from sklearn.utils import check_X_y |
| 11 | + |
| 12 | +from .over_sampler import OverSampler |
| 13 | + |
| 14 | + |
| 15 | +class ADASYN(OverSampler): |
| 16 | + """Perform over-sampling using ADASYN. |
| 17 | +
|
| 18 | + Perform over-sampling using Adaptive Synthetic Sampling Approach for |
| 19 | + Imbalanced Learning. |
| 20 | +
|
| 21 | + Parameters |
| 22 | + ---------- |
| 23 | + ratio : str or float, optional (default='auto') |
| 24 | + If 'auto', the ratio will be defined automatically to balance |
| 25 | + the dataset. Otherwise, the ratio is defined as the number |
| 26 | + of samples in the minority class over the the number of samples |
| 27 | + in the majority class. |
| 28 | +
|
| 29 | + random_state : int or None, optional (default=None) |
| 30 | + Seed for random number generation. |
| 31 | +
|
| 32 | + verbose : bool, optional (default=True) |
| 33 | + Whether or not to print information about the processing. |
| 34 | +
|
| 35 | + k : int, optional (default=5) |
| 36 | + Number of nearest neighbours to used to construct synthetic samples. |
| 37 | +
|
| 38 | + n_jobs : int, optional (default=-1) |
| 39 | + Number of threads to run the algorithm when it is possible. |
| 40 | +
|
| 41 | + Attributes |
| 42 | + ---------- |
| 43 | + ratio : str or float |
| 44 | + If 'auto', the ratio will be defined automatically to balance |
| 45 | + the dataset. Otherwise, the ratio is defined as the number |
| 46 | + of samples in the minority class over the the number of samples |
| 47 | + in the majority class. |
| 48 | +
|
| 49 | + random_state : int or None |
| 50 | + Seed for random number generation. |
| 51 | +
|
| 52 | + min_c_ : str or int |
| 53 | + The identifier of the minority class. |
| 54 | +
|
| 55 | + max_c_ : str or int |
| 56 | + The identifier of the majority class. |
| 57 | +
|
| 58 | + stats_c_ : dict of str/int : int |
| 59 | + A dictionary in which the number of occurences of each class is |
| 60 | + reported. |
| 61 | +
|
| 62 | + X_shape_ : tuple of int |
| 63 | + Shape of the data `X` during fitting. |
| 64 | +
|
| 65 | + Notes |
| 66 | + ----- |
| 67 | + Does not support multi-class. |
| 68 | +
|
| 69 | + The implementation is based on [1]_. |
| 70 | +
|
| 71 | + References |
| 72 | + ---------- |
| 73 | + .. [1] He, Haibo, Yang Bai, Edwardo A. Garcia, and Shutao Li. "ADASYN: |
| 74 | + Adaptive synthetic sampling approach for imbalanced learning," In IEEE |
| 75 | + International Joint Conference on Neural Networks (IEEE World Congress |
| 76 | + on Computational Intelligence), pp. 1322-1328, 2008. |
| 77 | +
|
| 78 | + """ |
| 79 | + |
| 80 | + def __init__(self, ratio='auto', random_state=None, verbose=True, k=5, |
| 81 | + n_jobs=-1): |
| 82 | + """Initialize this object and its instance variables. |
| 83 | +
|
| 84 | + Parameters |
| 85 | + ---------- |
| 86 | + ratio : str or float, optional (default='auto') |
| 87 | + If 'auto', the ratio will be defined automatically to balance |
| 88 | + the dataset. Otherwise, the ratio is defined as the number |
| 89 | + of samples in the minority class over the the number of samples |
| 90 | + in the majority class. |
| 91 | +
|
| 92 | + random_state : int or None, optional (default=None) |
| 93 | + Seed for random number generation. |
| 94 | +
|
| 95 | + verbose : bool, optional (default=True) |
| 96 | + Whether or not to print information about the processing. |
| 97 | +
|
| 98 | + k : int, optional (default=5) |
| 99 | + Number of nearest neighbours to used to construct synthetic |
| 100 | + samples. |
| 101 | +
|
| 102 | + n_jobs : int, optional (default=-1) |
| 103 | + Number of threads to run the algorithm when it is possible. |
| 104 | +
|
| 105 | + Returns |
| 106 | + ------- |
| 107 | + None |
| 108 | +
|
| 109 | + """ |
| 110 | + super(ADASYN, self).__init__(ratio=ratio, |
| 111 | + random_state=random_state, |
| 112 | + verbose=verbose) |
| 113 | + self.k = k |
| 114 | + self.n_jobs = n_jobs |
| 115 | + self.nearest_neighbour = NearestNeighbors(n_neighbors=self.k + 1, |
| 116 | + n_jobs=self.n_jobs) |
| 117 | + |
| 118 | + def fit(self, X, y): |
| 119 | + """Find the classes statistics before to perform sampling. |
| 120 | +
|
| 121 | + Parameters |
| 122 | + ---------- |
| 123 | + X : ndarray, shape (n_samples, n_features) |
| 124 | + Matrix containing the data which have to be sampled. |
| 125 | +
|
| 126 | + y : ndarray, shape (n_samples, ) |
| 127 | + Corresponding label for each sample in X. |
| 128 | +
|
| 129 | + Returns |
| 130 | + ------- |
| 131 | + self : object, |
| 132 | + Return self. |
| 133 | +
|
| 134 | + """ |
| 135 | + # Check the consistency of X and y |
| 136 | + X, y = check_X_y(X, y) |
| 137 | + |
| 138 | + # Call the parent function |
| 139 | + super(ADASYN, self).fit(X, y) |
| 140 | + |
| 141 | + return self |
| 142 | + |
| 143 | + def sample(self, X, y): |
| 144 | + """Resample the dataset. |
| 145 | +
|
| 146 | + Parameters |
| 147 | + ---------- |
| 148 | + X : ndarray, shape (n_samples, n_features) |
| 149 | + Matrix containing the data which have to be sampled. |
| 150 | +
|
| 151 | + y : ndarray, shape (n_samples, ) |
| 152 | + Corresponding label for each sample in X. |
| 153 | +
|
| 154 | + Returns |
| 155 | + ------- |
| 156 | + X_resampled : ndarray, shape (n_samples_new, n_features) |
| 157 | + The array containing the resampled data. |
| 158 | +
|
| 159 | + y_resampled : ndarray, shape (n_samples_new) |
| 160 | + The corresponding label of `X_resampled` |
| 161 | +
|
| 162 | + """ |
| 163 | + # Check the consistency of X and y |
| 164 | + X, y = check_X_y(X, y) |
| 165 | + |
| 166 | + # Call the parent function |
| 167 | + super(ADASYN, self).sample(X, y) |
| 168 | + |
| 169 | + # Keep the samples from the majority class |
| 170 | + X_resampled = X[y == self.maj_c_] |
| 171 | + y_resampled = y[y == self.maj_c_] |
| 172 | + |
| 173 | + # Define the number of sample to create |
| 174 | + # We handle only two classes problem for the moment. |
| 175 | + if self.ratio == 'auto': |
| 176 | + num_samples = (self.stats_c_[self.maj_c_] - |
| 177 | + self.stats_c_[self.min_c_]) |
| 178 | + else: |
| 179 | + num_samples = int((self.ratio * self.stats_c_[self.maj_c_]) - |
| 180 | + self.stats_c_[self.min_c_]) |
| 181 | + |
| 182 | + # Start by separating minority class features and target values. |
| 183 | + X_min = X[y == self.min_c_] |
| 184 | + |
| 185 | + # Print if verbose is true |
| 186 | + if self.verbose: |
| 187 | + print('Finding the {} nearest neighbours...'.format(self.k)) |
| 188 | + |
| 189 | + # Look for k-th nearest neighbours, excluding, of course, the |
| 190 | + # point itself. |
| 191 | + self.nearest_neighbour.fit(X) |
| 192 | + |
| 193 | + # Get the distance to the NN |
| 194 | + dist_nn, ind_nn = self.nearest_neighbour.kneighbors(X_min) |
| 195 | + |
| 196 | + # Compute the ratio of majority samples next to minority samples |
| 197 | + ratio_nn = np.sum(y[ind_nn[:, 1:]] == self.maj_c_, axis=1) / self.k |
| 198 | + # Normalize the ratio |
| 199 | + ratio_nn /= np.sum(ratio_nn) |
| 200 | + |
| 201 | + # Compute the number of sample to be generated |
| 202 | + num_samples_nn = np.round(ratio_nn * num_samples).astype(int) |
| 203 | + |
| 204 | + # For each minority samples |
| 205 | + for x_i, x_i_nn, num_sample_i in zip(X_min, ind_nn, num_samples_nn): |
| 206 | + # Fix the the seed |
| 207 | + np.random.seed(self.random_state) |
| 208 | + # Pick-up the neighbors wanted |
| 209 | + nn_zs = np.random.randint(1, high=self.k + 1, size=num_sample_i) |
| 210 | + |
| 211 | + # Create a new sample |
| 212 | + for nn_z in nn_zs: |
| 213 | + step = np.random.uniform() |
| 214 | + x_gen = x_i + step * (x_i - X[x_i_nn[nn_z], :]) |
| 215 | + X_resampled = np.vstack((X_resampled, x_gen)) |
| 216 | + y_resampled = np.hstack((y_resampled, self.min_c_)) |
| 217 | + |
| 218 | + if self.verbose: |
| 219 | + print("Over-sampling performed: {}".format(Counter(y_resampled))) |
| 220 | + |
| 221 | + return X_resampled, y_resampled |
0 commit comments