Skip to main content
Ctrl+K
Version 0.14.dev0 - Home Version 0.14.dev0 - Home
  • Getting Started
  • User Guide
  • API reference
  • Examples
  • Release history
    • About us
  • GitHub
  • Getting Started
  • User Guide
  • API reference
  • Examples
  • Release history
  • About us
  • GitHub

Section Navigation

  • Examples showing API imbalanced-learn usage
    • How to use sampling_strategy in imbalanced-learn
  • Examples based on real world datasets
    • Multiclass classification with under-sampling
    • Example of topic classification in text documents
    • Customized sampler to implement an outlier rejections estimator
    • Benchmark over-sampling methods in a face recognition task
    • Porto Seguro: balancing samples in mini-batches with Keras
    • Fitting model on imbalanced datasets and how to fight bias
  • Examples using combine class methods
    • Compare sampler combining over- and under-sampling
  • Dataset examples
    • Create an imbalanced dataset
  • Example using ensemble class methods
    • Bagging classifiers using sampler
    • Compare ensemble classifiers using resampling
  • Evaluation examples
    • Evaluate classification by compiling a report
    • Metrics specific to imbalanced learning
  • Model Selection
    • Plotting Validation Curves
  • Example using over-sampling class methods
    • Sample generator used in SMOTE-like samplers
    • Effect of the shrinkage factor in random over-sampling
    • Compare over-sampling samplers
  • Pipeline examples
    • Usage of pipeline embedding samplers
  • Example using under-sampling class methods
    • Illustration of the definition of a Tomek link
    • Sample selection in NearMiss
    • Compare under-sampling samplers
  • Examples
  • Example using under-sampling class methods
  • Illustration of the definition of a Tomek link

Note

Go to the end to download the full example code.

Illustration of the definition of a Tomek link#

This example illustrates what is a Tomek link.

# Authors: Guillaume Lemaitre <g.lemaitre58@gmail.com>
# License: MIT
print(__doc__)

import matplotlib.pyplot as plt
import seaborn as sns

sns.set_context("poster")

This function allows to make nice plotting

def make_plot_despine(ax):
    sns.despine(ax=ax, offset=10)
    ax.set_xlim([0, 3])
    ax.set_ylim([0, 3])
    ax.set_xlabel(r"$X_1$")
    ax.set_ylabel(r"$X_2$")
    ax.legend(loc="lower right")

We will generate some toy data that illustrates how TomekLinks is used to clean a dataset.

import numpy as np

rng = np.random.RandomState(18)

X_minority = np.transpose(
    [[1.1, 1.3, 1.15, 0.8, 0.55, 2.1], [1.0, 1.5, 1.7, 2.5, 0.55, 1.9]]
)
X_majority = np.transpose(
    [
        [2.1, 2.12, 2.13, 2.14, 2.2, 2.3, 2.5, 2.45],
        [1.5, 2.1, 2.7, 0.9, 1.0, 1.4, 2.4, 2.9],
    ]
)

In the figure above, the samples highlighted in green form a Tomek link since they are of different classes and are nearest neighbors of each other.

fig, ax = plt.subplots(figsize=(8, 8))
ax.scatter(
    X_minority[:, 0],
    X_minority[:, 1],
    label="Minority class",
    s=200,
    marker="_",
)
ax.scatter(
    X_majority[:, 0],
    X_majority[:, 1],
    label="Majority class",
    s=200,
    marker="+",
)

# highlight the samples of interest
ax.scatter(
    [X_minority[-1, 0], X_majority[1, 0]],
    [X_minority[-1, 1], X_majority[1, 1]],
    label="Tomek link",
    s=200,
    alpha=0.3,
)
make_plot_despine(ax)
fig.suptitle("Illustration of a Tomek link")
fig.tight_layout()
Illustration of a Tomek link

We can run the TomekLinks sampling to remove the corresponding samples. If sampling_strategy='auto' only the sample from the majority class will be removed. If sampling_strategy='all' both samples will be removed.

from imblearn.under_sampling import TomekLinks

fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(16, 8))

samplers = {
    "Removing only majority samples": TomekLinks(sampling_strategy="auto"),
    "Removing all samples": TomekLinks(sampling_strategy="all"),
}

for ax, (title, sampler) in zip(axs, samplers.items()):
    X_res, y_res = sampler.fit_resample(
        np.vstack((X_minority, X_majority)),
        np.array([0] * X_minority.shape[0] + [1] * X_majority.shape[0]),
    )
    ax.scatter(
        X_res[y_res == 0][:, 0],
        X_res[y_res == 0][:, 1],
        label="Minority class",
        s=200,
        marker="_",
    )
    ax.scatter(
        X_res[y_res == 1][:, 0],
        X_res[y_res == 1][:, 1],
        label="Majority class",
        s=200,
        marker="+",
    )

    # highlight the samples of interest
    ax.scatter(
        [X_minority[-1, 0], X_majority[1, 0]],
        [X_minority[-1, 1], X_majority[1, 1]],
        label="Tomek link",
        s=200,
        alpha=0.3,
    )

    ax.set_title(title)
    make_plot_despine(ax)
fig.tight_layout()

plt.show()
Removing only majority samples, Removing all samples

Total running time of the script: (0 minutes 2.241 seconds)

Estimated memory usage: 199 MB

Download Jupyter notebook: plot_illustration_tomek_links.ipynb

Download Python source code: plot_illustration_tomek_links.py

Download zipped: plot_illustration_tomek_links.zip

Gallery generated by Sphinx-Gallery

previous

Example using under-sampling class methods

next

Sample selection in NearMiss

Edit on GitHub

This Page

  • Show Source

© Copyright 2014-2025, The imbalanced-learn developers.

Created using Sphinx 8.1.3.

Built with the PyData Sphinx Theme 0.16.1.