Member-only story
Stratified Sampling_1
4 min readDec 17, 2024
Hello Guys,
Press enter or click to view image in full size![]()
Stratified Sampling with Scikit-Learn
pythonCopy codefrom sklearn.model_selection import train_test_split
import pandas as pd
from collections import Counter# Example dataset
data = {
'Feature1': [10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
'Feature2': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'Category': ['A', 'B', 'A', 'A', 'B', 'B', 'A', 'B', 'B', 'A']
}
df = pd.DataFrame(data)# Perform stratified sampling
X = df[['Feature1', 'Feature2']] # Features
y = df['Category'] # Target (strata)X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, stratify=y, random_state=42
)# Check distribution of the target variable
print("Original Distribution:", Counter(y))
print("Train Distribution:", Counter(y_train))
print("Test Distribution:", Counter(y_test))
Stratified Sampling with Custom Function
This code allows more control when you need stratified sampling on a pandas DataFrame:
pythonCopy codeimport pandas as pd# Example dataset
data = {
'Feature1': [10, 20, 30, 40, 50…





