- Notifications
You must be signed in to change notification settings - Fork 1.3k
[WIP] Rose #750
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
[WIP] Rose #750
Changes from all commits
Commits
Show all changes
20 commits Select commit Hold shift + click to select a range
53c7a8d
Created empty test units
183c03f
added ROSE empty class, modified __init__.py
0a3307b
implemented ROSE, still some failed test
886694f
PEP8 cleaning
07731c4
PEP8 linting
c0d7473
fixed linting errors.
013f7cc
updated documentation and bibliography
2b34f47
cleaned ROSE test
8d0e99e
added an exception for non binary datasets
8bbbd2e
multiclass oversampling
9ac2797
removed non-binary exception
b41b06a
removed unused import
d2dd6f4
minor fixes
b31a5c3
linting
d5ca24c
linting
b6e95aa
linting
6f7f8e1
linting
c391ec3
removed explicit pandas dataframe management
93ac868
added check_X_y() parsing
bdffda3
removed check_X_y test
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,139 @@ | ||
"""Class to perform over-sampling using ROSE.""" | ||
| ||
import numpy as np | ||
from scipy import sparse | ||
from sklearn.utils import check_random_state | ||
from .base import BaseOverSampler | ||
from ..utils._validation import _deprecate_positional_args | ||
# from sklearn.utils import check_X_y | ||
| ||
| ||
class ROSE(BaseOverSampler): | ||
| ||
"""Oversample using Random OverSampling Examples (ROSE) algorithm. | ||
| ||
The algorithm generates new samples by a smoothed bootstrap approach. | ||
The generation of new examples corresponds to the generation of data from | ||
the kernel density estimate of f(x|Y_i), with a smoothing matrix H_j. | ||
A shrinking matrix can be provided, to set the bandwidth of the gaussian | ||
kernel. | ||
| ||
Read more in the :ref:`User Guide <rose>`. | ||
| ||
Parameters | ||
---------- | ||
{sampling_strategy} | ||
{random_state} | ||
shrink_factors : dict of {classes: shrinkfactors} couples, applied to | ||
the gaussian kernels | ||
{n_jobs} | ||
| ||
Notes | ||
----- | ||
TODO: Support for multi-class resampling. A one-vs.one scheme is used. | ||
References | ||
---------- | ||
.. [1] N. Lunardon, G. Menardi, N.Torelli, "ROSE: A Package for Binary | ||
Imbalanced Learning," R Journal, 6(1), 2014. | ||
| ||
.. [2] G Menardi, N. Torelli, "Training and assessing classification | ||
rules with imbalanced data," Data Mining and Knowledge | ||
Discovery, 28(1), pp.92-122, 2014. | ||
""" | ||
| ||
@_deprecate_positional_args | ||
def __init__(self, *, sampling_strategy="auto", shrink_factors=None, | ||
random_state=None, n_jobs=None): | ||
super().__init__(sampling_strategy=sampling_strategy) | ||
self.random_state = random_state | ||
self.shrink_factors = shrink_factors | ||
self.n_jobs = n_jobs | ||
| ||
def _make_samples(self, | ||
X, | ||
class_indices, | ||
n_class_samples, | ||
h_shrink): | ||
""" A support function that returns artificial samples constructed | ||
from a random subsample of the data, by adding a multiviariate | ||
gaussian kernel and sampling from this distribution. An optional | ||
shrink factor can be included, to compress/dilate the kernel. | ||
| ||
Parameters | ||
---------- | ||
X : {array-like, sparse matrix}, shape (n_samples, n_features) | ||
Observations from which the samples will be created. | ||
| ||
class_indices : ndarray, shape (n_class_samples,) | ||
The target class indices | ||
| ||
n_class_samples : int | ||
The total number of samples per class to generate | ||
| ||
h_shrink : int | ||
the shrink factor | ||
| ||
Returns | ||
------- | ||
X_new : {ndarray, sparse matrix}, shape (n_samples, n_features) | ||
Synthetically generated samples. | ||
| ||
y_new : ndarray, shape (n_samples,) | ||
Target values for synthetic samples. | ||
| ||
""" | ||
# get number of features | ||
number_of_features = X.shape[1] | ||
# import random state from API | ||
random_state = check_random_state(self.random_state) | ||
# get random subsample of data with replacement | ||
samples_indices = random_state.choice( | ||
class_indices, size=n_class_samples, replace=True) | ||
# compute optimal min(AMISE) | ||
minimize_amise = (4 / ((number_of_features + 2) * len( | ||
class_indices))) ** (1 / (number_of_features + 4)) | ||
# create a diagonal matrix with the st.dev. of all classes | ||
variances = np.std(np.diagflat(X[class_indices, :]), | ||
axis=0, | ||
ddof=1) | ||
# compute H_optimal | ||
h_opt = h_shrink * minimize_amise * variances | ||
# (sample from multivariate normal)* h_opt + original values | ||
Xrose = np.random.standard_normal( | ||
size=(n_class_samples, | ||
number_of_features)) @ h_opt + X[samples_indices, :] | ||
| ||
return Xrose | ||
| ||
def _fit_resample(self, X, y): | ||
| ||
# X, y = check_X_y(X, y) | ||
X_resampled = np.empty((0, X.shape[1]), dtype=X.dtype) | ||
y_resampled = np.empty((0), dtype=X.dtype) | ||
| ||
if self.shrink_factors is None: | ||
self.shrink_factors = { | ||
key: 0.5 for key in self.sampling_strategy_.keys() | ||
} | ||
| ||
for class_sample, n_samples in self.sampling_strategy_.items(): | ||
# get indices of all y's with a given class n | ||
class_indices = np.flatnonzero(y == class_sample) | ||
# compute final n. of samples, by n. of elements + n_samples | ||
n_class_samples = len(class_indices) + n_samples | ||
| ||
# resample | ||
X_new = self._make_samples(X, | ||
class_indices, | ||
n_class_samples, | ||
self.shrink_factors[class_sample]) | ||
y_new = np.array([class_sample] * n_class_samples) | ||
| ||
if sparse.issparse(X_new): | ||
X_resampled = sparse.vstack([X_resampled, X_new]) | ||
else: | ||
X_resampled = np.vstack((X_resampled, X_new)) | ||
| ||
y_resampled = np.hstack((y_resampled, y_new)) | ||
| ||
return X_resampled.astype(X.dtype), y_resampled.astype(y.dtype) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
"""Test the module ROSE.""" | ||
# Authors: Andrea Lorenzon <andrelorenzon@gmail.com> | ||
# License: MIT | ||
| ||
import numpy as np | ||
| ||
from imblearn.over_sampling import ROSE | ||
| ||
| ||
def test_rose(): | ||
| ||
"""Check ROSE use""" | ||
| ||
RND_SEED = 0 | ||
| ||
X = np.array([[1., 1., 1., 0], | ||
[2., 2., 2., 0], | ||
[3., 3., 3., 0], | ||
[0.9, 0.9, 0.9, 0], | ||
[1.8, 1.8, 1.8, 0], | ||
[2.7, 2.7, 2.7, 0], | ||
[1.1, 1.1, 1.1, 0], | ||
[2.2, 2.2, 2.2, 0], | ||
[3.3, 3.3, 3.3, 0]]) | ||
Y = np.array([1, 2, 3, 1, 2, 3, 1, 2, 3]) | ||
X_res, y_res = ROSE(random_state=RND_SEED).fit_resample(X, Y) |
Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
These are great to include. References should be referenced from the main docstring for the class. A short summary of the method would also be good.
Here's an example from the
BorderlineSMOTE
class:imbalanced-learn/imblearn/over_sampling/_smote.py
Lines 219 to 224 in 0acd717
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I added a better description in the docstring.
I would like to add more complete information on the maths in the docs too, but I'm not familiar with Sphinx. Could you point me to some instructions or metadocumentation?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Math typesetting should look familiar if you've seen LaTeX before, here's a short guide from sphinx's docs: https://www.sphinx-doc.org/en/1.0/ext/math.html. Syntax is based on reStructuredText, which feels similar to markdown but has a powerful directive system.
Nothing specific to imblearn. If you want to learn more, sphinx's "Getting Started" guide is a good place to start. (I'd recommend it regardless. Sphinx is used for a huge number of projects, so the skill is extremely transferable).
Our
Makefile
andconf.py
in thedocs/
directory are fairly standard. Building local documentation then looks like:cd docs/ make html xdg-open _build/html/index.html
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ok. I will just have some problem with plots, but I'll manage to add everything to the docs.
I have another issue: failing checks, see below. It's not very clear to me what they do address at, and what to fix.