randomundersampler
imblearn
machinelearning
samplingtechniques
python

How to get sample indices from RandomUnderSampler in imblearn

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

If you want to know which original samples RandomUnderSampler kept, the attribute you need is sample_indices_. After calling fit_resample, imbalanced-learn stores the indices of the selected samples on the sampler object. That is the most direct way to map the resampled dataset back to the original rows.

Use sample_indices_ After fit_resample

According to the current imbalanced-learn API reference, RandomUnderSampler exposes sample_indices_ as the indices of the samples selected. The attribute is available after fitting or resampling.

python
1from collections import Counter
2from sklearn.datasets import make_classification
3from imblearn.under_sampling import RandomUnderSampler
4
5X, y = make_classification(
6    n_classes=2,
7    weights=[0.1, 0.9],
8    n_features=5,
9    n_samples=100,
10    random_state=42,
11)
12
13rus = RandomUnderSampler(random_state=42)
14X_res, y_res = rus.fit_resample(X, y)
15
16print(Counter(y))
17print(Counter(y_res))
18print(rus.sample_indices_)

That last line prints the indices from the original dataset that were kept in the resampled result.

Use the Indices With pandas

If your input started as a pandas DataFrame, those indices let you recover the selected original rows directly.

python
1import pandas as pd
2from imblearn.under_sampling import RandomUnderSampler
3
4
5df = pd.DataFrame({
6    "feature": [10, 11, 12, 13, 14, 15],
7    "target":  [0, 1, 1, 1, 0, 1],
8})
9
10X = df[["feature"]]
11y = df["target"]
12
13rus = RandomUnderSampler(random_state=0)
14X_res, y_res = rus.fit_resample(X, y)
15selected_rows = df.iloc[rus.sample_indices_]
16
17print(selected_rows)

This is useful when you want to audit which records were retained or when you need to carry extra metadata columns alongside the resampled features.

Why the Indices Matter

Knowing the selected sample indices helps with more than debugging. It is useful for:

  • auditing class-balancing decisions
  • tracing resampled training rows back to raw records
  • carrying metadata that was not part of X
  • analyzing which majority-class samples survived the undersampling step

Without sample_indices_, you would have to reconstruct that relationship manually, which is awkward and error-prone.

Recover the Matching Labels or Metadata

Because the indices refer to the original input rows, you can use them to recover anything that was aligned with the original dataset, not just the sampled feature matrix.

python
selected_y = y.iloc[rus.sample_indices_] if hasattr(y, "iloc") else y[rus.sample_indices_]
print(selected_y)

The same pattern works for timestamps, IDs, or other side-channel metadata stored alongside the training data.

Be Careful About Order

The resampled arrays X_res and y_res correspond to the order of sample_indices_. That means if you use df.iloc[rus.sample_indices_], the resulting row order lines up with the resampled output.

This matters if you later join predictions, sample weights, or metadata back to the sampled rows.

Fit Versus fit_resample

In practice, you should use fit_resample, not fit alone, for this workflow. The imbalanced-learn documentation explicitly recommends fit_resample in normal usage.

python
rus = RandomUnderSampler(random_state=42)
X_res, y_res = rus.fit_resample(X, y)
indices = rus.sample_indices_

That is the standard pattern.

Common Pitfalls

The most common mistake is trying to read sample_indices_ before fitting the sampler. The attribute does not exist until the sampler has been fitted or resampled.

Another issue is losing track of the original dataset order and then assuming the resampled rows map back by position automatically. Use sample_indices_ instead of guessing.

Developers also sometimes inspect only X_res and y_res and forget that extra metadata columns are no longer attached. The indices are how you recover those rows from the original data source.

Finally, remember that the selected indices reflect the sampler's random state. If you want reproducible results, set random_state explicitly.

Summary

  • After fit_resample, RandomUnderSampler exposes the kept-row indices in sample_indices_.
  • Use those indices to map resampled data back to the original dataset.
  • 'df.iloc[rus.sample_indices_] is the usual pandas pattern.'
  • Call fit_resample, not only fit, for normal resampling workflows.
  • Set random_state if you want reproducible selected indices.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.