Imbalanced-Learn module in Python
Last Updated :
11 Dec, 2020
Imbalanced-Learn is a Python module that helps in balancing the datasets which are highly skewed or biased towards some classes. Thus, it helps in resampling the classes which are otherwise oversampled or undesampled. If there is a greater imbalance ratio, the output is biased to the class which has a higher number of examples. The following dependencies need to be installed to use imbalanced-learn:
- scipy(>=0.19.1)
- numpy(>=1.13.3)
- scikit-learn(>=0.23)
- joblib(>=0.11)
- keras 2 (optional)
- tensorflow (optional)
To install imbalanced-learn just type in :
pip install imbalanced-learn
The resampling of data is done in 2 parts:
Estimator: It implements a fit method which is derived from scikit-learn. The data and targets are both in the form of a 2D array
estimator = obj.fit(data, targets)
Resampler: The fit_resample method resample the data and targets into a dictionary with a key-value pair of data_resampled and targets_resampled.
data_resampled, targets_resampled = obj.fit_resample(data, targets)
The Imbalanced Learn module has different algorithms for oversampling and undersampling:
We will use the built-in dataset called the make_classification dataset which return
- x: a matrix of n_samples*n_features and
- y: an array of integer labels.
Click dataset to get the dataset used.
Python3
from sklearn.datasets import make_classification
x, y = make_classification(n_samples=10000,
weights=[0.99],
flip_y=0)
print('x:\n', X)
print('y:\n', y)
|
Output:

Below are some programs in which depict how to apply oversampling and undersampling to the dataset:
Oversampling
- Random Over Sampler: It is a naive method where classes that have low examples are generated and randomly resampled.
Syntax:
from imblearn.over_sampling import RandomOverSampler
Parameters(optional): sampling_strategy=’auto’, return_indices=False, random_state=None, ratio=None
Implementation:
oversample = RandomOverSampler(sampling_strategy=’minority’)
X_oversample,Y_oversample=oversample.fit_resample(X,Y)
Return Type:a matrix with the shape of n_samples*n_features
Example:
Python3
from sklearn.datasets import make_classification
from imblearn.over_sampling import RandomOverSampler
x, y = make_classification(n_samples=10000,
weights=[0.99],
flip_y=0)
oversample = RandomOverSampler(sampling_strategy='minority')
x_over, y_over = oversample.fit_resample(x, y)
print('x_over:\n', x_over)
print('y_over:\n', y_over)
|
Output:

- SMOTE, ADASYN: Synthetic Minority Oversampling Technique (SMOTE) and the Adaptive Synthetic (ADASYN) are 2 methods used in oversampling. These also generate low examples but ADASYN takes into account the density of distribution to distribute the data points evenly.
Syntax:
from imblearn.over_sampling import SMOTE, ADASYN
Parameters(optional):*, sampling_strategy=’auto’, random_state=None, n_neighbors=5, n_jobs=None
Implementation:
smote = SMOTE(ratio=’minority’)
X_smote,Y_smote=smote.fit_resample(X,Y)
Return Type:a matrix with the shape of n_samples*n_features
Example:
Python3
from sklearn.datasets import make_classification
from imblearn.over_sampling import SMOTE
x, y = make_classification(n_samples=10000, weights=[0.99], flip_y=0)
smote = SMOTE()
x_smote, y_smote = smote.fit_resample(x, y)
print('x_smote:\n', x_smote)
print('y_smote:\n', y_smote)
|
Output:

Undersampling
- Edited Nearest Neighbours: This algorithm removes any sample which has labels different from those of its adjoining classes.
Syntax:
from imblearn.under_sampling import EditedNearestNeighbours
Parameters(optional): sampling_strategy=’auto’, return_indices=False, random_state=None, n_neighbors=3, kind_sel=’all’, n_jobs=1, ratio=None
Implementation:
en = EditedNearestNeighbours()
X_en,Y_en=en.fit_resample(X, y)
Return Type:a matrix with the shape of n_samples*n_features
Example:
Python3
from sklearn.datasets import make_classification
from imblearn.under_sampling import EditedNearestNeighbours
x, y = make_classification(n_samples=10000, weights=[0.99], flip_y=0)
en = EditedNearestNeighbours()
x_en, y_en = en.fit_resample(x, y)
print('x_en:\n', x_en)
print('y_en:\n', y_en)
|
Output:

- Random Under Sampler: It involves sampling any random class with or without any replacement.
Syntax:
from imblearn.under_sampling import RandomUnderSampler
Parameters(optional): sampling_strategy=’auto’, return_indices=False, random_state=None, replacement=False, ratio=None
Implementation:
undersample = RandomUnderSampler()
X_under, y_under = undersample.fit_resample(X, y)
Return Type: a matrix with the shape of n_samples*n_features
Example:
Python3
from sklearn.datasets import make_classification
from imblearn.under_sampling import RandomUnderSampler
x, y = make_classification(n_samples=10000,
weights=[0.99],
flip_y=0)
undersample = RandomUnderSampler()
x_under, y_under = undersample.fit_resample(x, y)
print('x_under:\n', x_under)
print('y_under:\n', y_under)
|
Output:

Get IBM Certification and a 90% fee refund on completing 90% course in 90 days! Take the Three 90 Challenge today.
Master Machine Learning, Data Science & AI with this complete program and also get a 90% refund. What more motivation do you need? Start the challenge right away!
Similar Reads
Imbalanced-Learn module in Python
Imbalanced-Learn is a Python module that helps in balancing the datasets which are highly skewed or biased towards some classes. Thus, it helps in resampling the classes which are otherwise oversampled or undesampled. If there is a greater imbalance ratio, the output is biased to the class which has
3 min read
Keyword Module in Python
Python provides an in-built module keyword that allows you to know about the reserved keywords of python. The keyword module allows you the functionality to know about the reserved words or keywords of Python and to check whether the value of a variable is a reserved word or not. In case you are una
2 min read
Create and Import modules in Python
In Python, a module is a self-contained Python file that contains Python statements and definitions, like a file named GFG.py, can be considered as a module named GFG which can be imported with the help of import statement. However, one might get confused about the difference between modules and pac
3 min read
AlgebraOnMatrix Module in Python
AlgebraOnMatrix module is that library of python which helps you to perform basic matrix algebra such as addition of two matrices, subtraction of two matrices, multiplication of two matrices, transpose of matrix . Installing Library This module does not come built-in with Python. You need to install
3 min read
External Modules in Python
Python is one of the most popular programming languages because of its vast collection of modules which make the work of developers easy and save time from writing the code for a particular task for their program. Python provides various types of modules which include built-in modules and external m
5 min read
__future__ Module in Python
__future__ module is a built-in module in Python that is used to inherit new features that will be available in the new Python versions.. This module includes all the latest functions which were not present in the previous version in Python. And we can use this by importing the __future__ module. It
4 min read
Python Fire Module
Python Fire is a library to create CLI applications. It can automatically generate command line Interfaces from any object in python. It is not limited to this, it is a good tool for debugging and development purposes. With the help of Fire, you can turn existing code into CLI. In this article, we w
3 min read
Basics Of Python Modules
A library refers to a collection of modules that together cater to a specific type of needs or application. Module is a file(.py file) containing variables, class definitions statements, and functions related to a particular task. Python modules that come preloaded with Python are called standard li
3 min read
Python and Jupyter Installation
Install the python in windows. Step1: Firstly open internet browser like chrome or firefox etc Step2: In the search tab type this link "python" Step3: Look for the downloads link in that website ,click on it to download the latest version of the python Step4: After it gets downloaded we can install
2 min read
How to create modules in Python 3 ?
Modules are simply python code having functions, classes, variables. Any python file with .py extension can be referenced as a module. Although there are some modules available through the python standard library which are installed through python installation, Other modules can be installed using t
4 min read
Import Modules From Another Folder in Python
In this article, we are going to see how to import a module from another folder, While working on big projects we may confront a situation where we want to import a module from a different directory, here we will see the different ways to import a module form different folder. It can be done in two
2 min read
Installing Python telnetlib module
In this article, we are going to see how to install the telnetlib library in Python. The telnetlib module provides a Telnet class that implements the Telnet protocol. If you have Python installed, the telnetlib library is already installed, but if it isn't, we can use the pip command to install it.
1 min read
Pylint module in Python
We often get stuck in the middle or encounter errors when we code/run some programs. We usually surf the internet for help and make our code run. But how do we understand the published code on the internet? Some of the typical answers to this question are docstrings, articles written above that code
4 min read
Python Exit handlers (atexit)
atexit is a module in python which contains two functions register() and unregister(). The main role of this module is to perform clean up upon interpreter termination. Functions that are registered are automatically executed upon interpreter termination. Whenever a program is killed by a signal not
2 min read
How to Dynamically Load Modules or Classes in Python
Python provides a feature to create and store classes and methods and store them for further use. The file containing these sets of methods and classes is called a module. A module can have other modules inside it. Note: For more information, refer to Python Modules Example: A simple example of impo
3 min read
Lazy import in Python
In this article, we will learn how to do Lazy import in Python. For this, let's first understand the lazy import. What is Lazy Import? It is a feature of the Pyforest module that allows the user to perform the task without adding libraries to the code snippet as the task of this function is to add t
5 min read
Data Classes in Python | An Introduction
dataclass module is introduced in Python 3.7 as a utility tool to make structured classes specially for storing data. These classes hold certain properties and functions to deal specifically with the data and its representation.DataClasses in widely used Python3.6 Although the module was introduced
3 min read
Python Modules
Python Module is a file that contains built-in functions, classes,its and variables. There are many Python modules, each with its specific work. In this article, we will cover all about Python modules, such as How to create our own simple module, Import Python modules, From statements in Python, we
7 min read
How to locate a particular module in Python?
In this article, we will see how to locate a particular module in Python. Locating a module means finding the directory from which the module is imported. When we import a module the Python interpreter searches for the module in the following manner: First, it searches for the module in the current
3 min read