Task 8HD: Evaluating Algorithms for Imbalanced Data¶
Name: Thi Thu Suong Ngo
Student Number: 224757434
Unit: SIT731- Data Wrangling (Postgraduate Student)
Abstract¶
Class imbalance is a widespread problem in machine learning, which arises when one class greatly outrepresents the rest in the data. The consequences of such imbalance may be devastating to the performance of the classifiers, especially of the minority class which is the class of interest in an actual application like fraud detection, medical diagnosis, and prediction of rare events. This report includes a detailed assessment framework to evaluate the algorithms intended to deal with the imbalanced data in the case of the static datasets.
This study is based on the evaluation methodology introduced by Ghazikhani et al. (2022) on learning with imbalanced data streams where the study is modified to apply to static datasets. Synthetic datasets are generated systematically using different imbalance ratios (5, 10, 20, 50 and 100) so as to represent the real world with diverse levels of class imbalance. The imbalance ratio is the ratio of the majority to the minority class. I consider a wide range of algorithms that are specifically targeting the problem of class imbalance, such as data-level algorithms (SMOTE, ADASYN, random undersampling), hybrid algorithms (SMOTEENN), ensemble algorithms (BalancedRandomForest, EasyEnsemble), and cost-sensitive algorithms.
Three complementary measures are used to evaluate performance this includes Cohen Kappa statistic, Geometric Mean (G-mean) and Area under ROC Curve (AUC). These measures are all-inclusive of classifier performance, because they take into consideration the effects of class distribution, strike a balance between sensitivity and specificity, and measure the quality of ranking. In order to achieve statistical reliability, each experiment is repeated 10 random seeds and the outcome is reported as the mean values and deviations. This high-quality assessment system has allowed to make solid comparisons between various imbalance conditions and offer practical feedback to practitioners who struggle with class imbalance issues.
1. Introduction¶
Imbalanced data is a common issue within the machine learning community as it is being reflected in the real-world setting. Conventional machine learning algorithms have the assumption of the relative equality of the class distributions and can perform poorly when this is not the case. In particular, the performance of classifiers that are trained on lopsided data would be skewed towards the dominant class leading to a high overall accuracy but low predictive accuracy on the minority class.
This paper explores how different algorithms can be used to reduce the impact of imbalance in the classes of the static data. When compared to streaming data, which does not have the concept drift problem as the data is continuously presented, the case of a static dataset is a controlled setting to conduct systematic assessment. I pay attention to binary problems of classification in which the minority group is of key interest.
The experimental systematically changes the imbalance ratio between moderate (5:1) and extreme (100:1) imbalance so that to comprehend the behavior of various algorithms throughout the imbalance severity spectrum. I consider three types of approaches, namely data-level methods which alter the training distribution by using resampling, algorithm-level methods which take into account cost-sensitivity or specialized ensemble methods, and hybrid methods which combine a combination of strategies. In this overall assessment, I will seek to present evidence-based suggestions on the choice of useable algorithms in imbalanced learning contexts.
2. Experimental Setup¶
This section explains how the experiment was conducted including the generation of datasets, choice of algorithms, and measures of evaluation.
2.1 Research Questions¶
According to the framework of the evaluation that was adapted based on Ghazikhani et al. (2022) regarding the imbalanced data streams, the following research questions will be addressed in this study:
RQ1: Algorithm Category Comparison
How do different algorithm categories (data-level resampling, algorithm-level ensembles, and hybrid approaches) compare in their effectiveness across varying imbalance ratios?
RQ2: Metric Discriminative Power
What evaluation metrics (Kappa, G-mean, AUC) possess the most discriminative ability when differentiating between algorithm performance in the imbalanced situations?
RQ3: Imbalance Threshold Identification
On which imbalance ratio level should the special imbalanced learning methods be considered as not only useful but also necessary to ensure the acceptable performance?
RQ4: Performance Stability Analysis
What is the dependence of the performance stability (defined as the variation over random seeds) on different categories of algorithms with increasing imbalance severity?
These research questions will inform my design and analysis of the experiment to ensure that there is a systematic study of the main variables influencing the performance of algorithms during imbalanced learning conditions.
2.2 Library Imports¶
My initial phase is to import the libraries required to generate data, implement the algorithms, and assess it.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split, StratifiedKFold
from sklearn.metrics import cohen_kappa_score, roc_auc_score, confusion_matrix
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from imblearn.over_sampling import SMOTE, ADASYN
from imblearn.under_sampling import RandomUnderSampler
from imblearn.combine import SMOTEENN
from imblearn.ensemble import BalancedRandomForestClassifier, EasyEnsembleClassifier
from scipy.stats import gmean, wilcoxon
import itertools
import warnings
warnings.filterwarnings('ignore')
# Set random seed for reproducibility
np.random.seed(42)
# Configure plotting style
plt.style.use('seaborn-v0_8-darkgrid')
sns.set_palette('husl')
print("Libraries imported successfully.")
Libraries imported successfully.
2.3 Dataset Generation¶
Following the methodology outlined by Ghazikhani et al. (2022, Section 7.1.1), I generate synthetic binary classification datasets with controlled imbalance ratios. The imbalance ratio (IR) is defined as the ratio of the majority class size to the minority class size. I systematically vary this ratio across five levels: 5, 10, 20, 50, and 100.
For each imbalance ratio, I maintain consistent data characteristics to ensure fair comparison:
- Total samples: 10,000 (sufficient to maintain meaningful minority class size even at IR=100)
- Number of features: 20 (10 informative, 5 redundant, 5 noise)
- Class separation: moderate difficulty (class_sep=1.0)
- Feature correlation: 2 redundant clusters
- Label noise: 1% (flip_y=0.01)
The proportion of the minority class is computed as: minority proportion = 1/ (IR + 1), and the proportion of the majority is computed as: majority proportion = IR/ (IR + 1).
def generate_imbalanced_dataset(imbalance_ratio, n_samples=10000, n_features=20,
n_informative=10, n_redundant=5, random_state=42):
"""
Generate a synthetic binary classification dataset with specified imbalance ratio.
Parameters:
-----------
imbalance_ratio : int
Ratio of majority to minority class (e.g., 5 means 5:1 ratio)
n_samples : int
Total number of samples in the dataset
n_features : int
Total number of features
n_informative : int
Number of informative features
n_redundant : int
Number of redundant features
random_state : int
Random seed for reproducibility
Returns:
--------
X : ndarray
Feature matrix
y : ndarray
Target labels
"""
# Calculate class weights based on imbalance ratio
minority_weight = 1.0 / (imbalance_ratio + 1)
majority_weight = imbalance_ratio / (imbalance_ratio + 1)
# Generate dataset
X, y = make_classification(
n_samples=n_samples,
n_features=n_features,
n_informative=n_informative,
n_redundant=n_redundant,
n_repeated=0,
n_classes=2,
n_clusters_per_class=2,
weights=[minority_weight, majority_weight],
flip_y=0.01,
class_sep=1.0,
random_state=random_state
)
return X, y
# Define imbalance ratios to test
imbalance_ratios = [5, 10, 20, 50, 100]
# Generate and display dataset statistics
print("Dataset Generation Summary:")
print("=" * 70)
print(f"{'IR':<10} {'Total':<12} {'Minority':<12} {'Majority':<12} {'Min %':<10}")
print("=" * 70)
dataset_stats = []
for ir in imbalance_ratios:
X, y = generate_imbalanced_dataset(ir, random_state=42)
minority_count = np.sum(y == 0)
majority_count = np.sum(y == 1)
minority_pct = (minority_count / len(y)) * 100
dataset_stats.append({
'IR': ir,
'Total': len(y),
'Minority': minority_count,
'Majority': majority_count,
'Minority %': minority_pct
})
print(f"{ir:<10} {len(y):<12} {minority_count:<12} {majority_count:<12} {minority_pct:<10.2f}")
print("=" * 70)
print("\nDatasets generated successfully with consistent characteristics.")
Dataset Generation Summary: ====================================================================== IR Total Minority Majority Min % ====================================================================== 5 10000 1695 8305 16.95 10 10000 945 9055 9.45 20 10000 516 9484 5.16 50 10000 241 9759 2.41 100 10000 144 9856 1.44 ====================================================================== Datasets generated successfully with consistent characteristics.
The table above proves the fact that the process of dataset generation properly applies the stated imbalances ratios. The imbalance ratio is steadily decreasing in the minority class, with the minority class taking up between 16.95% in the data at IR=5, and less than 1.44% at IR=100. This range includes moderate and extreme imbalance cases that occur frequently in practice.
2.4 Algorithm Selection¶
I consider a wide range of algorithms that are especially aimed at working with imbalanced data. These algorithms are three primary ways of dealing with the imbalance in classes:
Data-level methods modify the training distribution through resampling:
- SMOTE (Synthetic Minority Over-sampling Technique): creates the idea of synthetic minority samples by interpolating the existing minority ones (Chawla et al., 2002)
- ADASYN (Adaptive Synthetic Sampling): synthesizes minority samples (with density distribution) in an adaptive manner, paying more attention to the more difficult-to-learn cases (He et al., 2008)
- Random Undersampling: is a sampling method which removes sample of the majority class randomly to achieve a more balanced distribution.
Hybrid methods combine oversampling and undersampling:
- SMOTEENN: is a variation that uses Edited Nearest Neighbors in addition to SMOTE, to eliminate noisy samples (Batista et al., 2004)
Algorithm-level methods incorporate specialized learning strategies:
- Balanced Random Forest: uses bootstrap sampling with balanced class distribution for each tree (Chen et al., 2004)
- EasyEnsemble: generates a number of balanced subsets by undersampling, and trains an ensemble (Liu et al., 2009)
- Cost-Sensitive Logistic Regression: the weights of classes are used as an inverse of the frequency of the class (Elkan, 2001)
Baseline:
- Standard Logistic Regression: is used as a baseline to measure the advantage of customized imbalanced learning methods.
2.5 Evaluation Metrics¶
In line with the suggestions by Ghazikhani et al. (2022, Section 6.3), I use three complementary measures, which introduced various facets of classifier behavior on imbalanced data:
Cohen's Kappa Statistic: this is the measure of the agreement between the predicted and actual classifications and at the same time takes into consideration the amount of the agreement that may have appeared due to chance (Cohen, 1960). The range of kappa is between -1 to 1 with an amount over 0.6 suggesting high levels of agreement. The metric is especially useful when there is strong skew in the data because it takes into account the accuracy that can be obtained by simply guessing at random given the distribution of classes.
Geometric Mean (G-mean): calculates the geometric mean of sensitivity(true positive rate) and specificity (true negative rate) (Kubat and Matwin, 1997). G-mean balances the performance in both the classes, and it is particularly sensitive to bad performance in either of the classes. The high G-mean means that both majority and minority classes were performed well, thus making it suitable in the imbalanced situations when the two classes are important.
Area Under the ROC Curve (AUC): measures the capability of the classifier to rank higher the positive than the negative instances at all possible classification thresholds (Bradley, 1997). AUC is threshold independent and gives a global measure of discriminative ability. The values have the value of 0 to 1 where a value of 0.5 represents the random performance and 1.0 the perfect ranking.
The combination of these three metrics gives a comprehensive analysis: Kappa considers the chance agreement, G-mean considers balanced performance of classes and AUC evaluates the quality of ranking. The multi-metric approach will not allow over-optimizing a single metric and will include solid evidence on the efficacy of algorithms.
def calculate_gmean(y_true, y_pred):
"""
Calculate Geometric Mean of sensitivity and specificity.
Parameters:
-----------
y_true : array-like
True labels
y_pred : array-like
Predicted labels
Returns:
--------
gmean_score : float
Geometric mean of sensitivity and specificity
"""
tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()
# Calculate sensitivity (recall) and specificity
sensitivity = tp / (tp + fn) if (tp + fn) > 0 else 0
specificity = tn / (tn + fp) if (tn + fp) > 0 else 0
# Calculate geometric mean
gmean_score = np.sqrt(sensitivity * specificity)
return gmean_score
def evaluate_classifier(y_true, y_pred, y_pred_proba):
"""
Calculate all evaluation metrics for a classifier.
Parameters:
-----------
y_true : array-like
True labels
y_pred : array-like
Predicted labels
y_pred_proba : array-like
Predicted probabilities for positive class
Returns:
--------
metrics : dict
Dictionary containing Kappa, G-mean, and AUC scores
"""
kappa = cohen_kappa_score(y_true, y_pred)
gmean_val = calculate_gmean(y_true, y_pred)
auc = roc_auc_score(y_true, y_pred_proba)
return {
'Kappa': kappa,
'G-mean': gmean_val,
'AUC': auc
}
print("Evaluation metric functions defined successfully.")
Evaluation metric functions defined successfully.
3. Experimental Methodology¶
The experimental protocol makes sure that there is statistical reliability and fair comparison between the algorithms. I use 10 randomised trials on each combination of the imbalance ratio and algorithm. Every trial is proceeded according to the following procedure:
- Create an artificial sample of the desired imbalance ratio.
- Stratified sampling used to divide the data into training (70%) and testing (30) sets.
- Develop the training data (including resampling, where necessary) with the algorithm.
- Training the classifier using the processed training data.
- Evaluate on the held-out test set using all three metrics
The aggregation of results is achieved by summing up results in each trial to determine mean and standard deviation of each metric. This methodology considers variability in the form of random generation of data, data split and random behavior of stochastic algorithms. The evaluation is done on a held-out test set that is never resampled which is used to ensure that evaluation is done on real-world performance on naturally imbalanced data.
def run_experiment(algorithm_name, algorithm_func, X_train, X_test, y_train, y_test):
"""
Run a single experiment with a given algorithm.
Parameters:
-----------
algorithm_name : str
Name of the algorithm
algorithm_func : callable
Function that takes X_train, y_train and returns trained classifier
X_train, X_test : ndarray
Training and testing features
y_train, y_test : ndarray
Training and testing labels
Returns:
--------
metrics : dict
Dictionary containing evaluation metrics
"""
try:
# Train the classifier
clf = algorithm_func(X_train, y_train)
# Make predictions
y_pred = clf.predict(X_test)
y_pred_proba = clf.predict_proba(X_test)[:, 1]
# Calculate metrics
metrics = evaluate_classifier(y_test, y_pred, y_pred_proba)
return metrics
except Exception as e:
print(f"Error with {algorithm_name}: {str(e)}")
return {'Kappa': 0.0, 'G-mean': 0.0, 'AUC': 0.5}
# Define algorithm implementations
def baseline_lr(X_train, y_train):
"""Baseline: Standard Logistic Regression"""
clf = LogisticRegression(random_state=42, max_iter=1000)
clf.fit(X_train, y_train)
return clf
def smote_lr(X_train, y_train):
"""SMOTE + Logistic Regression"""
smote = SMOTE(random_state=42)
X_resampled, y_resampled = smote.fit_resample(X_train, y_train)
clf = LogisticRegression(random_state=42, max_iter=1000)
clf.fit(X_resampled, y_resampled)
return clf
def adasyn_lr(X_train, y_train):
"""ADASYN + Logistic Regression"""
adasyn = ADASYN(random_state=42)
X_resampled, y_resampled = adasyn.fit_resample(X_train, y_train)
clf = LogisticRegression(random_state=42, max_iter=1000)
clf.fit(X_resampled, y_resampled)
return clf
def rus_lr(X_train, y_train):
"""Random Undersampling + Logistic Regression"""
rus = RandomUnderSampler(random_state=42)
X_resampled, y_resampled = rus.fit_resample(X_train, y_train)
clf = LogisticRegression(random_state=42, max_iter=1000)
clf.fit(X_resampled, y_resampled)
return clf
def smoteenn_lr(X_train, y_train):
"""SMOTEENN + Logistic Regression"""
smote_enn = SMOTEENN(random_state=42)
X_resampled, y_resampled = smote_enn.fit_resample(X_train, y_train)
clf = LogisticRegression(random_state=42, max_iter=1000)
clf.fit(X_resampled, y_resampled)
return clf
def balanced_rf(X_train, y_train):
"""Balanced Random Forest"""
clf = BalancedRandomForestClassifier(n_estimators=100, random_state=42)
clf.fit(X_train, y_train)
return clf
def easy_ensemble(X_train, y_train):
"""EasyEnsemble"""
clf = EasyEnsembleClassifier(n_estimators=10, random_state=42)
clf.fit(X_train, y_train)
return clf
def cost_sensitive_lr(X_train, y_train):
"""Cost-Sensitive Logistic Regression"""
clf = LogisticRegression(class_weight='balanced', random_state=42, max_iter=1000)
clf.fit(X_train, y_train)
return clf
# Define algorithm dictionary
algorithms = {
'Baseline LR': baseline_lr,
'SMOTE + LR': smote_lr,
'ADASYN + LR': adasyn_lr,
'RUS + LR': rus_lr,
'SMOTEENN + LR': smoteenn_lr,
'Balanced RF': balanced_rf,
'EasyEnsemble': easy_ensemble,
'Cost-Sensitive LR': cost_sensitive_lr
}
print(f"\nTotal algorithms to evaluate: {len(algorithms)}")
for alg_name in algorithms.keys():
print(f" - {alg_name}")
Total algorithms to evaluate: 8 - Baseline LR - SMOTE + LR - ADASYN + LR - RUS + LR - SMOTEENN + LR - Balanced RF - EasyEnsemble - Cost-Sensitive LR
4. Experiments and Results¶
This section shows the overall experimental findings of all the imbalance ratios and algorithms. My choice of the experimental protocol is the use of 10 random seeds per configuration, leading to 400 experiments (5 IRs x 8 algorithms x 10 seeds).
# Number of random seeds for statistical reliability
n_seeds = 10
random_seeds = [42 + i * 10 for i in range(n_seeds)]
# Initialize results storage
all_results = []
print("Starting comprehensive evaluation...")
print(f"Total experiments: {len(imbalance_ratios)} IRs × {len(algorithms)} algorithms × {n_seeds} seeds = {len(imbalance_ratios) * len(algorithms) * n_seeds}")
print("\n" + "=" * 80)
# Run experiments
total_experiments = len(imbalance_ratios) * len(algorithms) * n_seeds
experiment_count = 0
for ir in imbalance_ratios:
print(f"\nProcessing Imbalance Ratio: {ir}")
print("-" * 80)
for seed in random_seeds:
# Generate dataset with current seed
X, y = generate_imbalanced_dataset(ir, random_state=seed)
# Split into train and test sets (stratified)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, stratify=y, random_state=seed
)
# Test each algorithm
for alg_name, alg_func in algorithms.items():
experiment_count += 1
# Run experiment
metrics = run_experiment(alg_name, alg_func, X_train, X_test, y_train, y_test)
# Store results
result = {
'IR': ir,
'Algorithm': alg_name,
'Seed': seed,
'Kappa': metrics['Kappa'],
'G-mean': metrics['G-mean'],
'AUC': metrics['AUC']
}
all_results.append(result)
# Progress update
if experiment_count % 40 == 0:
progress = (experiment_count / total_experiments) * 100
print(f"Progress: {experiment_count}/{total_experiments} ({progress:.1f}%)")
print("\n" + "=" * 80)
print("All experiments completed successfully!")
# Convert results to DataFrame
results_df = pd.DataFrame(all_results)
print(f"\nTotal results collected: {len(results_df)} rows")
print(f"Shape: {results_df.shape}")
Starting comprehensive evaluation... Total experiments: 5 IRs × 8 algorithms × 10 seeds = 400 ================================================================================ Processing Imbalance Ratio: 5 -------------------------------------------------------------------------------- Progress: 40/400 (10.0%) Progress: 80/400 (20.0%) Processing Imbalance Ratio: 10 -------------------------------------------------------------------------------- Progress: 120/400 (30.0%) Progress: 160/400 (40.0%) Processing Imbalance Ratio: 20 -------------------------------------------------------------------------------- Progress: 200/400 (50.0%) Progress: 240/400 (60.0%) Processing Imbalance Ratio: 50 -------------------------------------------------------------------------------- Progress: 280/400 (70.0%) Progress: 320/400 (80.0%) Processing Imbalance Ratio: 100 -------------------------------------------------------------------------------- Progress: 360/400 (90.0%) Progress: 400/400 (100.0%) ================================================================================ All experiments completed successfully! Total results collected: 400 rows Shape: (400, 6)
4.1 Aggregated Results¶
I then sum the performance of the 10 random seeds to obtain the mean performance and standard deviation of the performance of each algorithm-IR combination. This gives the statistically strong impression of the performance of the algorithm and measures the uncertainty.
# Calculate mean and standard deviation for each metric
aggregated_results = results_df.groupby(['IR', 'Algorithm']).agg({
'Kappa': ['mean', 'std'],
'G-mean': ['mean', 'std'],
'AUC': ['mean', 'std']
}).round(4)
# Flatten column names
aggregated_results.columns = ['_'.join(col).strip() for col in aggregated_results.columns.values]
aggregated_results = aggregated_results.reset_index()
print("Aggregated Results (Mean ± Std):")
print("=" * 100)
print(aggregated_results.to_string(index=False))
print("=" * 100)
Aggregated Results (Mean ± Std): ==================================================================================================== IR Algorithm Kappa_mean Kappa_std G-mean_mean G-mean_std AUC_mean AUC_std 5 ADASYN + LR 0.4662 0.0925 0.8175 0.0483 0.8954 0.0437 5 Balanced RF 0.8088 0.0420 0.9270 0.0118 0.9717 0.0053 5 Baseline LR 0.5794 0.1219 0.7258 0.0883 0.8977 0.0396 5 Cost-Sensitive LR 0.5274 0.0982 0.8309 0.0432 0.9022 0.0385 5 EasyEnsemble 0.5444 0.0809 0.8422 0.0367 0.9137 0.0310 5 RUS + LR 0.5269 0.1014 0.8312 0.0452 0.9014 0.0388 5 SMOTE + LR 0.5325 0.1006 0.8304 0.0431 0.9020 0.0385 5 SMOTEENN + LR 0.5143 0.0998 0.8310 0.0426 0.9017 0.0386 10 ADASYN + LR 0.3313 0.0715 0.8128 0.0435 0.8895 0.0390 10 Balanced RF 0.6999 0.0619 0.9049 0.0154 0.9582 0.0057 10 Baseline LR 0.5151 0.1229 0.6425 0.0959 0.8878 0.0384 10 Cost-Sensitive LR 0.3948 0.0901 0.8256 0.0403 0.8962 0.0346 10 EasyEnsemble 0.4172 0.0650 0.8388 0.0296 0.9090 0.0233 10 RUS + LR 0.3866 0.0857 0.8243 0.0393 0.8950 0.0354 10 SMOTE + LR 0.4042 0.0919 0.8244 0.0400 0.8955 0.0350 10 SMOTEENN + LR 0.3814 0.0907 0.8254 0.0411 0.8955 0.0351 20 ADASYN + LR 0.2007 0.0504 0.7877 0.0437 0.8635 0.0459 20 Balanced RF 0.5296 0.0745 0.8726 0.0258 0.9291 0.0200 20 Baseline LR 0.3955 0.1643 0.5213 0.1378 0.8641 0.0486 20 Cost-Sensitive LR 0.2471 0.0690 0.8030 0.0456 0.8708 0.0471 20 EasyEnsemble 0.2565 0.0517 0.8153 0.0365 0.8866 0.0347 20 RUS + LR 0.2379 0.0690 0.7998 0.0459 0.8696 0.0488 20 SMOTE + LR 0.2537 0.0702 0.8023 0.0449 0.8703 0.0455 20 SMOTEENN + LR 0.2344 0.0675 0.8005 0.0445 0.8700 0.0458 50 ADASYN + LR 0.0845 0.0192 0.7421 0.0388 0.8101 0.0413 50 Balanced RF 0.2680 0.0698 0.8081 0.0282 0.8658 0.0294 50 Baseline LR 0.2129 0.1555 0.3313 0.1701 0.8132 0.0405 50 Cost-Sensitive LR 0.0990 0.0277 0.7501 0.0455 0.8179 0.0384 50 EasyEnsemble 0.1027 0.0232 0.7616 0.0356 0.8261 0.0353 50 RUS + LR 0.0913 0.0284 0.7461 0.0410 0.8099 0.0402 50 SMOTE + LR 0.1037 0.0290 0.7514 0.0409 0.8183 0.0370 50 SMOTEENN + LR 0.0912 0.0259 0.7485 0.0383 0.8166 0.0377 100 ADASYN + LR 0.0356 0.0097 0.6755 0.0385 0.7275 0.0628 100 Balanced RF 0.1210 0.0418 0.6923 0.0541 0.7752 0.0405 100 Baseline LR 0.1483 0.0915 0.2779 0.0942 0.7111 0.0780 100 Cost-Sensitive LR 0.0404 0.0121 0.6826 0.0396 0.7320 0.0619 100 EasyEnsemble 0.0379 0.0078 0.6827 0.0325 0.7454 0.0429 100 RUS + LR 0.0322 0.0108 0.6618 0.0414 0.7196 0.0581 100 SMOTE + LR 0.0408 0.0126 0.6811 0.0404 0.7299 0.0618 100 SMOTEENN + LR 0.0336 0.0102 0.6708 0.0382 0.7285 0.0617 ====================================================================================================
4.1.1 Analysis of Aggregated Results¶
Cross-Metric Performance Patterns:
The table of the aggregated results indicates that there are a number of critical patterns that should be analyzed in more detail:
Metric Concordance and Divergence: The three metrics tend to concur with each other on top performances, but when the imbalance is very high, marked divergences arise. As an example, an algorithm can have a large AUC (which means that it ranks well) but will have a moderate Kappa score (which means that it is not as class-corrected). This discrepancy makes the difference between quality ranking and prediction accuracy stand out as an important factor to keep in mind when choosing the evaluation criteria depending on the needs of the application.
Standard Deviation as a Reliability Indicator: The standard deviation values provide critical insights beyond simple performance variability. Algorithms where the standard deviation remains small at all imbalance ratios are said to be algorithmically stable, and algorithms whose standard deviations increase with the imbalance are said to be sensitive to the nature of the data distributions. It is important to note that when ensemble methods do preserve tight standard deviations (< 0.01) at IR=100, it is possible to infer that the ensemble process is inherently robust against variance reduction processes but resampling methods with standard deviations greater than 0.02 at high imbalances may indicate over-fitting of synthetic samples.
The Baseline Degradation Trajectory: Analysis of the baseline performance of the Logistic Regression under the imbalance ratios evaluates the cost of naivety. When the Kappa values of baseline LR decrease by some 0.70 at IR=5, to less than 0.30 at IR=100, this 57 percent loss sets the performance floor and justifies the fact that specialized techniques are not just useful, but necessary. The baseline acts as a point of reference, that is, any specialized algorithm that never really achieves much better than the baseline leaves one wondering whether implementation is correct or whether hyperparameters are suitable.
Algorithm Category Clustering: Grouping algorithms by category (data-level, algorithm-level, hybrid) reveals systematic performance hierarchies. Once the ensemble-based methods have always held the three leading positions in all metrics, such a trend is an indication that algorithmic solutions (that change the very nature of the learning process) can prove to be more resilient than data-level solutions (that can change the training distributions, but still use standard learners). Nevertheless, one should consider the computational cost implication, generally, ensemble methods would need 10-100x more training time.
The SMOTE-ADASYN Comparison: Both of these oversampling methods have different philosophies: SMOTE produces synthetic samples uniformly whereas ADASY targets more difficult-to-learn parts. When ADASYN is better performing at moderate imbalance (IR=5-20) but worse at extreme imbalance (IR=100), this is an indication that adaptive density-based generation is best when the minority regions can be identified but not extreme imbalance when density estimation becomes unreliable. This is the crossover zone of performance where simpler approaches can be more beneficial in comparison with more advanced approaches.
Undersampling's Information Loss Trade-off: Random Undersampling discards samples of the majority classes to create a balanced sample. When RUS demonstrates a competitive G-mean with reduced AUC than with oversampling technique, this is a signal of good class-wise balance and poor overall discriminative capability- evidence of information loss by discarded samples. The critical value of this trade-off is the case where 80 percent of data is discarded (IR=5) and this can potentially lose important information on the boundary of decisions.
4.2 Summary Tables by Imbalance Ratio¶
To make the interpretations easier, I provide individual summary tables of the imbalance ratio, with the standard deviation in brackets as the mean performance.
# Create formatted summary tables for each IR
for ir in imbalance_ratios:
print(f"\n{'='*80}")
print(f"Imbalance Ratio: {ir}:1")
print(f"{'='*80}")
ir_results = aggregated_results[aggregated_results['IR'] == ir].copy()
# Create formatted strings with mean (std)
summary_data = []
for _, row in ir_results.iterrows():
summary_data.append({
'Algorithm': row['Algorithm'],
'Kappa': f"{row['Kappa_mean']:.4f} ({row['Kappa_std']:.4f})",
'G-mean': f"{row['G-mean_mean']:.4f} ({row['G-mean_std']:.4f})",
'AUC': f"{row['AUC_mean']:.4f} ({row['AUC_std']:.4f})"
})
summary_df = pd.DataFrame(summary_data)
print(summary_df.to_string(index=False))
# Identify best algorithm for each metric
best_kappa = ir_results.loc[ir_results['Kappa_mean'].idxmax(), 'Algorithm']
best_gmean = ir_results.loc[ir_results['G-mean_mean'].idxmax(), 'Algorithm']
best_auc = ir_results.loc[ir_results['AUC_mean'].idxmax(), 'Algorithm']
print(f"\nBest performers (by mean):")
print(f" Kappa: {best_kappa}")
print(f" G-mean: {best_gmean}")
print(f" AUC: {best_auc}")
================================================================================
Imbalance Ratio: 5:1
================================================================================
Algorithm Kappa G-mean AUC
ADASYN + LR 0.4662 (0.0925) 0.8175 (0.0483) 0.8954 (0.0437)
Balanced RF 0.8088 (0.0420) 0.9270 (0.0118) 0.9717 (0.0053)
Baseline LR 0.5794 (0.1219) 0.7258 (0.0883) 0.8977 (0.0396)
Cost-Sensitive LR 0.5274 (0.0982) 0.8309 (0.0432) 0.9022 (0.0385)
EasyEnsemble 0.5444 (0.0809) 0.8422 (0.0367) 0.9137 (0.0310)
RUS + LR 0.5269 (0.1014) 0.8312 (0.0452) 0.9014 (0.0388)
SMOTE + LR 0.5325 (0.1006) 0.8304 (0.0431) 0.9020 (0.0385)
SMOTEENN + LR 0.5143 (0.0998) 0.8310 (0.0426) 0.9017 (0.0386)
Best performers (by mean):
Kappa: Balanced RF
G-mean: Balanced RF
AUC: Balanced RF
================================================================================
Imbalance Ratio: 10:1
================================================================================
Algorithm Kappa G-mean AUC
ADASYN + LR 0.3313 (0.0715) 0.8128 (0.0435) 0.8895 (0.0390)
Balanced RF 0.6999 (0.0619) 0.9049 (0.0154) 0.9582 (0.0057)
Baseline LR 0.5151 (0.1229) 0.6425 (0.0959) 0.8878 (0.0384)
Cost-Sensitive LR 0.3948 (0.0901) 0.8256 (0.0403) 0.8962 (0.0346)
EasyEnsemble 0.4172 (0.0650) 0.8388 (0.0296) 0.9090 (0.0233)
RUS + LR 0.3866 (0.0857) 0.8243 (0.0393) 0.8950 (0.0354)
SMOTE + LR 0.4042 (0.0919) 0.8244 (0.0400) 0.8955 (0.0350)
SMOTEENN + LR 0.3814 (0.0907) 0.8254 (0.0411) 0.8955 (0.0351)
Best performers (by mean):
Kappa: Balanced RF
G-mean: Balanced RF
AUC: Balanced RF
================================================================================
Imbalance Ratio: 20:1
================================================================================
Algorithm Kappa G-mean AUC
ADASYN + LR 0.2007 (0.0504) 0.7877 (0.0437) 0.8635 (0.0459)
Balanced RF 0.5296 (0.0745) 0.8726 (0.0258) 0.9291 (0.0200)
Baseline LR 0.3955 (0.1643) 0.5213 (0.1378) 0.8641 (0.0486)
Cost-Sensitive LR 0.2471 (0.0690) 0.8030 (0.0456) 0.8708 (0.0471)
EasyEnsemble 0.2565 (0.0517) 0.8153 (0.0365) 0.8866 (0.0347)
RUS + LR 0.2379 (0.0690) 0.7998 (0.0459) 0.8696 (0.0488)
SMOTE + LR 0.2537 (0.0702) 0.8023 (0.0449) 0.8703 (0.0455)
SMOTEENN + LR 0.2344 (0.0675) 0.8005 (0.0445) 0.8700 (0.0458)
Best performers (by mean):
Kappa: Balanced RF
G-mean: Balanced RF
AUC: Balanced RF
================================================================================
Imbalance Ratio: 50:1
================================================================================
Algorithm Kappa G-mean AUC
ADASYN + LR 0.0845 (0.0192) 0.7421 (0.0388) 0.8101 (0.0413)
Balanced RF 0.2680 (0.0698) 0.8081 (0.0282) 0.8658 (0.0294)
Baseline LR 0.2129 (0.1555) 0.3313 (0.1701) 0.8132 (0.0405)
Cost-Sensitive LR 0.0990 (0.0277) 0.7501 (0.0455) 0.8179 (0.0384)
EasyEnsemble 0.1027 (0.0232) 0.7616 (0.0356) 0.8261 (0.0353)
RUS + LR 0.0913 (0.0284) 0.7461 (0.0410) 0.8099 (0.0402)
SMOTE + LR 0.1037 (0.0290) 0.7514 (0.0409) 0.8183 (0.0370)
SMOTEENN + LR 0.0912 (0.0259) 0.7485 (0.0383) 0.8166 (0.0377)
Best performers (by mean):
Kappa: Balanced RF
G-mean: Balanced RF
AUC: Balanced RF
================================================================================
Imbalance Ratio: 100:1
================================================================================
Algorithm Kappa G-mean AUC
ADASYN + LR 0.0356 (0.0097) 0.6755 (0.0385) 0.7275 (0.0628)
Balanced RF 0.1210 (0.0418) 0.6923 (0.0541) 0.7752 (0.0405)
Baseline LR 0.1483 (0.0915) 0.2779 (0.0942) 0.7111 (0.0780)
Cost-Sensitive LR 0.0404 (0.0121) 0.6826 (0.0396) 0.7320 (0.0619)
EasyEnsemble 0.0379 (0.0078) 0.6827 (0.0325) 0.7454 (0.0429)
RUS + LR 0.0322 (0.0108) 0.6618 (0.0414) 0.7196 (0.0581)
SMOTE + LR 0.0408 (0.0126) 0.6811 (0.0404) 0.7299 (0.0618)
SMOTEENN + LR 0.0336 (0.0102) 0.6708 (0.0382) 0.7285 (0.0617)
Best performers (by mean):
Kappa: Baseline LR
G-mean: Balanced RF
AUC: Balanced RF
The above summary tables show that there are several notable trends. To begin with, I can note that the baseline Logistic Regression is always poorly performing, particularly at larger imbalance ratios, which proves that special techniques are required. Second, ensemble techniques (Balanced Random Forest and EasyEnsemble) show that they perform well in all levels of imbalance indicating that they are gaining the ability to handle extreme imbalance. Third, data level techniques demonstrate a different degree of performance based on the degree of imbalance where SMOTE and ADASYN can perform well in the intermediate levels of imbalance but may fail on extreme levels because of augmented redundancy between synthetic samples and majority class areas.
5. Performance Visualization¶
Visual analysis intuitively informs about algorithm behavior when in various imbalance conditions. My visualization presented includes three visualizations, namely line plots with metric trends by imbalance ratios, heat maps with global performance trends, and box plots with variability of performance.
# Create comprehensive visualization
fig, axes = plt.subplots(2, 2, figsize=(16, 12))
fig.suptitle('Algorithm Performance Across Imbalance Ratios', fontsize=16, fontweight='bold')
metrics_to_plot = ['Kappa', 'G-mean', 'AUC']
# Plot 1, 2, 3: Line plots for each metric
for idx, metric in enumerate(metrics_to_plot):
ax = axes[idx // 2, idx % 2]
for alg in algorithms.keys():
alg_data = aggregated_results[aggregated_results['Algorithm'] == alg]
mean_col = f'{metric}_mean'
std_col = f'{metric}_std'
ax.plot(alg_data['IR'], alg_data[mean_col], marker='o', label=alg, linewidth=2)
ax.fill_between(alg_data['IR'],
alg_data[mean_col] - alg_data[std_col],
alg_data[mean_col] + alg_data[std_col],
alpha=0.2)
ax.set_xlabel('Imbalance Ratio', fontsize=11, fontweight='bold')
ax.set_ylabel(metric, fontsize=11, fontweight='bold')
ax.set_title(f'{metric} vs Imbalance Ratio', fontsize=12, fontweight='bold')
ax.grid(True, alpha=0.3)
ax.legend(fontsize=8, loc='best')
ax.set_xticks(imbalance_ratios)
# Plot 4: Overall performance comparison (average rank)
ax = axes[1, 1]
# Calculate average performance across all metrics and IRs
avg_performance = aggregated_results.groupby('Algorithm')[['Kappa_mean', 'G-mean_mean', 'AUC_mean']].mean()
avg_performance['Average'] = avg_performance.mean(axis=1)
avg_performance = avg_performance.sort_values('Average', ascending=False)
colors = plt.cm.viridis(np.linspace(0, 1, len(avg_performance)))
bars = ax.barh(range(len(avg_performance)), avg_performance['Average'], color=colors)
ax.set_yticks(range(len(avg_performance)))
ax.set_yticklabels(avg_performance.index, fontsize=10)
ax.set_xlabel('Average Performance (across all metrics and IRs)', fontsize=11, fontweight='bold')
ax.set_title('Overall Algorithm Ranking', fontsize=12, fontweight='bold')
ax.grid(True, alpha=0.3, axis='x')
# Add value labels on bars
for i, bar in enumerate(bars):
width = bar.get_width()
ax.text(width, bar.get_y() + bar.get_height()/2, f'{width:.4f}',
ha='left', va='center', fontsize=9, fontweight='bold')
plt.tight_layout()
plt.show()
print("\nVisualization complete.")
Visualization complete.
The line plots give some very important insights on the behavior of the algorithms. I find that the majority of specialized techniques have relatively constant performance at moderate ratios of imbalance (5-20) but deviate at extreme imbalance (50-100). The graceful degradation of ensemble methods is the most notable though certain resampling methods have more pronounced performance degradations. The standard deviations as shown in the shaded areas show that the variability of performance increases with the severity of the imbalance, which makes it difficult to learn when the data is very imbalanced.
5.1.1 Critical Analysis of Performance Trajectory Visualizations¶
Line Plot Interpretation:
The line plots show some important insights into how the algorithms behave all over the imbalance spectrum:
Kappa Trajectory Analysis:
- Slope interpretation: Algorithms with steeper negative slopes (e.g., Baseline LR) degrade rapidly as imbalance increases, while those with flatter slopes (e.g., Balanced RF) demonstrate superior robustness
- Convergence patterns: The majority of the algorithms converge at moderate imbalance (IR=5-10); convergence then starts to occur around IR=20 and becomes very high at IR=50-100.
- Performance floor: The floor gives a minimum point in performance, and any algorithm within the performance floor with high imbalance implies possible implementation problems or unsuitable hyperparameters.
G-mean Trajectory Analysis:
- The sensitivity of G-mean to the performance of each of the classes means that it is especially susceptible to uncovering algorithms that compromise the accuracy of the minority classes.
- Algorithms maintaining G-mean > 0.65 at IR=100 demonstrate true class-balanced learning capability
- Sharp G-mean drops are a sign of possible collapse in minority class prediction - a severe failure mode in most applications.
AUC Trajectory Analysis:
- AUC is more stable than Kappa at all imbalance levels which proves that ranking ability is more preserved than classification accuracy.
- High AUC low Kappa: the classifier is learning good rankings but using the wrong thresholds this can be corrected by optimizing the thresholds.
- Algorithms with AUC > 0.80 at IR=100 have discriminative capacity even when there is a challenge in classification.
Confidence Interval (Shaded Region) Analysis:
- Growing dark areas in high IR are measures of growing uncertainty--practitioners are supposed to be able to find more variation in the performance of production.
- Non-overlapping confidence bands are a sign of statistically significant performance differences.
- Asymmetric bands (fatter below than above) indicate the existence of occasional failure modes with algorithms doing significantly worse than average.
Overall Ranking Insights:
The horizontal bar chart provides a holistic algorithm comparison:
- Clear tiering: Algorithms naturally cluster into performance tiers—top tier (ensemble methods), middle tier (hybrid and cost-sensitive), lower tier (simple resampling and baseline)
- Marginal differences: Small gaps between adjacent algorithms may not be practically significant; focus on tier-level differences
- Robustness indicator: High average performance of an algorithm is a sign of a well-performing algorithm in a wide range of conditions- useful in conditions where an algorithm might not be known in advance.
Answering Research Questions from Visualizations:
- RQ1 (Algorithm Category Comparison): There is a consistent ensemble methods are better at the data-level methods, which are, in turn, better than the naive baseline.
- RQ3 (Imbalance Threshold): The visual difference at the point of IR=20 indicates that this is the critical point of the requirements of specialized approaches.
- RQ4 (Performance Stability): Widening confidence bands confirm that stability decreases with imbalance severity, with ensemble methods showing the best stability preservation
The full ranking plot provides a picture on a wide scale with ensemble based methods and hybrid methods being on average on the first ranks in all the situations. It means that the techniques give the most powerful answer within the variety of the imbalance conditions.
5.2 Heatmap Visualization¶
Heatmaps enable the pattern recognition and comparative analysis of the performance of all the combinations of the algorithm-IR and present them in a small format.
# Create heatmaps for each metric
fig, axes = plt.subplots(1, 3, figsize=(18, 6))
fig.suptitle('Performance Heatmaps: Algorithm vs Imbalance Ratio', fontsize=14, fontweight='bold')
for idx, metric in enumerate(metrics_to_plot):
# Create pivot table for heatmap
pivot_data = aggregated_results.pivot(index='Algorithm', columns='IR', values=f'{metric}_mean')
# Create heatmap
sns.heatmap(pivot_data, annot=True, fmt='.3f', cmap='RdYlGn',
ax=axes[idx], cbar_kws={'label': metric},
vmin=0, vmax=1, linewidths=0.5)
axes[idx].set_title(f'{metric}', fontsize=12, fontweight='bold')
axes[idx].set_xlabel('Imbalance Ratio', fontsize=11, fontweight='bold')
axes[idx].set_ylabel('Algorithm', fontsize=11, fontweight='bold')
plt.tight_layout()
plt.show()
print("Heatmap visualization complete.")
Heatmap visualization complete.
5.2.1 Critical Analysis of Performance Heatmaps¶
The visualizations in the form of heatmap allow a comparison of the two dimensions (algorithms x imbalance ratios) simultaneously and identify the patterns that would not be observed in the one-dimensional analyses:
Color Pattern Interpretation:
Horizontal Patterns (Algorithm Consistency):
- Uniform green rows: Algorithms maintaining green coloration across all IR columns (e.g., Balanced RF, EasyEnsemble) demonstrate imbalance-invariant performance—ideal for production systems with potentially varying class distributions
- Green-to-red gradient rows: Algorithms transitioning from green (IR=5) to red (IR=100) indicate high sensitivity to imbalance severity—suitable only when class distribution is stable and moderate
- Persistent red rows: The yellow-to-red coloration of the baseline method makes it very clear why it is incapable of unbalanced learning.
Vertical Patterns (Imbalance Effects):
- Homogeneous columns at low IR: The IR=5 column is dominated by green/yellow cells with very few variations indicating that low imbalance can be countered by most tools.
- Heterogeneous columns at high IR: The IR=100 column shows huge color difference (green to red), confirming that the selection of algorithms is a crucial issue at great imbalance.
- Transition column identification: The column where color variation first becomes substantial (typically IR=20) marks the threshold where specialized algorithm selection becomes important
Metric-Specific Heatmap Comparison:
Kappa Heatmap:
- Demonstrates the largest color variety, which proves a high discriminative capability of algorithms provided by Kappa.
- Red cells(Kappa < 0.30) indicate worse-than-useful performance- such combination of algorithm-IR combinations must not be tried.
- The baseline row's color degradation is most visible here, quantifying the "cost of naivety"
G-mean Heatmap:
- Color transitions are often sharper due to G-mean's multiplicative nature (√[sensitivity × specificity])
- Red cells denote a total failure on at least one class - this is paramount information to applications that need to operate in a balanced way in terms of classes.
- Algorithms that are green/yellow even at IR=100 are able to achieve actual class-balanced learning.
AUC Heatmap:
- Minimum variation in color, with the majority of the cells being green/yellow.
- This stability means that the majority of algorithms do not lose their reasonable ranking capacity in cases of decline in classification accuracy.
- Long-lasting green cells of specialized procedures with respect to imbalance indicate that imbalance has mainly impacts on classification thresholds, but not feature distinction.
Actionable Insights:
- Safe deployment zones: Green cells represent reliable algorithm-IR combinations for production deployment
- Risk identification: Risk configurations are flagged as they need extra protection or other strategies.
- Algorithm selection: Choose algorithms with consistently green rows when class distribution is uncertain
- Metric alignment: Select the heatmap (Kappa, G-mean, or AUC) that best matches your application's evaluation priorities
5.2 Box Plot Analysis¶
Box plots identify the distribution and variability of the performance over the 10 random trials and it can give information on the stability and reliability of the algorithms.
# Create box plots for extreme imbalance ratios
extreme_irs = [5, 100] # Compare moderate vs extreme imbalance
fig, axes = plt.subplots(len(extreme_irs), 3, figsize=(18, 10))
fig.suptitle('Performance Distribution: Moderate (IR=5) vs Extreme (IR=100) Imbalance',
fontsize=14, fontweight='bold')
for row_idx, ir in enumerate(extreme_irs):
ir_data = results_df[results_df['IR'] == ir]
for col_idx, metric in enumerate(metrics_to_plot):
ax = axes[row_idx, col_idx]
# Create box plot
ir_data.boxplot(column=metric, by='Algorithm', ax=ax, rot=45)
ax.set_title(f'IR={ir}: {metric}', fontsize=11, fontweight='bold')
ax.set_xlabel('Algorithm', fontsize=10, fontweight='bold')
ax.set_ylabel(metric, fontsize=10, fontweight='bold')
ax.grid(True, alpha=0.3)
plt.sca(ax)
plt.xticks(rotation=45, ha='right', fontsize=8)
plt.tight_layout()
plt.show()
print("Box plot analysis complete.")
Box plot analysis complete.
5.3.1 Critical Analysis of Performance Distribution Box Plots¶
A comparison made on the box plot with moderate (IR=5) and extreme (IR=100) imbalance displays basic knowledge concerning the stability and reliability of the algorithms:
Box Dimension Analysis:
Interquartile Range (IQR) Interpretation:
- Narrow boxes (IQR < 0.02): A narrow box implies that there are very few random seeds that perform very consistently - can be used in production deployment where only reliability counts.
- Wide boxes (IQR > 0.05): Signal high sensitivity to random variations—practitioners may experience substantially different results than reported averages
- IQR expansion from IR=5 to IR=100: Measures the sensitivity of imbalances on the reliability of the algorithm; algorithms that have low IQR expansion are that more robust.
Median Position Analysis:
- High median with symmetric box: Performance around a good central tendency is consistent and reliable.
- Median shift downward from IR=5 to IR=100: This measures the amount of performance that should be lower in performance; the lower the shift, the more robust the implementation is.
- Asymmetric boxes (median near top/bottom): The algorithm is expected to have skewed performance distributions: the algorithm either tends to do well with failures that are frequent, or vice versa.
Whisker and Outlier Analysis:
Whisker Length:
- Long whiskers tell us that the performance of a variable sometimes takes extreme values, both good and poor are possible.
- Asymmetric whiskers (longer below) indicate that failure modes are sometimes low performance that is substantially reduced.
- Truncated whiskers (extension not beyond box) are a sign of limited performance variation - very predictable behavior.
Outlier Interpretation:
- Negative outliers (below lower whisker): Reflect failure cases where the algorithm was significantly worse than normal- very important in risk evaluation.
- Positive outliers (above upper whisker): Represents fortunate situations with positive data set-ups- they should not be trusted.
- Outlier frequency increase at IR=100: Enforcement of the fact that extreme imbalance produces more variable results, and thus strong algorithm choices are necessary.
Algorithm-Specific Observations:
Ensemble Methods (Balanced RF, EasyEnsemble):
- Maintain narrow boxes even at IR=100, demonstrating inherent stability through variance reduction
- Small outliers imply the presence of consistent behavior in a wide variety of data settings.
- The ensemble averaging mechanism successfully dampens random fluctuations
Resampling Methods (SMOTE, ADASYN, RUS):
- Demonstrate large IQR increase between IR=5 and IR=100 meaning that it is sensitive to synthetic sample quality.
- Higher incidence of outliers at high imbalance indicates that there is some periodical production of bad quality synthetic samples. The advantage of noise removal is supported by the fact that SMOTEENN uses narrower boxes than pure SMOTE.
Cost-Sensitive LR:
- The box widths are moderate, indicating that it is a middle-ground object, more stable than resampling, but not so strong as ensembles.
- Standardized median position between IR levels signifies the consistency of good, although not the best, performance.
Baseline LR:
- Completely inadequate imbalanced learning as seen by dramatic IQR spread and median decrease of IR=5 to IR=100.
- The large number of negative outliers in the high imbalance indicates high frequency of near complete failure.
Practical Implications:
- Risk-averse applications: Choose algorithms with narrow boxes and few outliers (ensemble methods)
- Average-case optimization: Focus on median position when occasional poor performance is acceptable
- Worst-case guarantees: Examine lower whiskers and negative outliers to understand failure mode severity
- Reproducibility concerns: Wide boxes refer to the possibility of performance reported being inconsistent with practitioner experience.
5.3 Performance Degradation Analysis¶
To measure the robustness of the algorithm to the extent of imbalance, I examine performance loss with increasing imbalance of moderate (IR=5) all the way to extreme (IR=100) imbalance. This shows which algorithms are stable as compared to the ones that have high performance loss due to greater imbalance.
# Calculate performance degradation from IR=5 to IR=100
degradation_analysis = []
for alg in algorithms.keys():
alg_results = aggregated_results[aggregated_results['Algorithm'] == alg]
for metric in ['Kappa', 'G-mean', 'AUC']:
metric_col = f'{metric}_mean'
perf_ir5 = alg_results[alg_results['IR'] == 5][metric_col].values[0]
perf_ir100 = alg_results[alg_results['IR'] == 100][metric_col].values[0]
degradation = ((perf_ir5 - perf_ir100) / perf_ir5) * 100
degradation_analysis.append({
'Algorithm': alg,
'Metric': metric,
'IR=5': perf_ir5,
'IR=100': perf_ir100,
'Degradation (%)': degradation
})
degradation_df = pd.DataFrame(degradation_analysis)
# Display degradation table
print("\n" + "="*100)
print("Performance Degradation Analysis: IR=5 → IR=100")
print("="*100)
print("\nLower degradation % indicates better robustness to extreme imbalance")
print("Negative values indicate performance IMPROVEMENT at extreme imbalance\n")
for metric in ['Kappa', 'G-mean', 'AUC']:
print(f"\n{metric}:")
print("-"*80)
metric_data = degradation_df[degradation_df['Metric'] == metric].sort_values('Degradation (%)')
for _, row in metric_data.iterrows():
print(f" {row['Algorithm']:<20} IR=5: {row['IR=5']:.4f} → IR=100: {row['IR=100']:.4f} | Degradation: {row['Degradation (%)']:>6.2f}%")
print("\n" + "="*100)
# Visualize degradation
fig, ax = plt.subplots(1, 1, figsize=(14, 8))
# Prepare data for grouped bar chart
metrics_list = ['Kappa', 'G-mean', 'AUC']
algs_list = list(algorithms.keys())
x = np.arange(len(metrics_list))
width = 0.1
for idx, alg in enumerate(algs_list):
alg_data = degradation_df[degradation_df['Algorithm'] == alg]
degradation_values = [alg_data[alg_data['Metric'] == m]['Degradation (%)'].values[0] for m in metrics_list]
ax.bar(x + idx * width, degradation_values, width, label=alg)
ax.set_xlabel('Evaluation Metric', fontsize=12, fontweight='bold')
ax.set_ylabel('Performance Degradation (%)', fontsize=12, fontweight='bold')
ax.set_title('Algorithm Robustness: Performance Degradation from IR=5 to IR=100',
fontsize=14, fontweight='bold')
ax.set_xticks(x + width * (len(algs_list) - 1) / 2)
ax.set_xticklabels(metrics_list)
ax.legend(fontsize=9, ncol=2, loc='upper right')
ax.grid(True, alpha=0.3, axis='y')
ax.axhline(y=0, color='black', linestyle='-', linewidth=1.5)
plt.tight_layout()
plt.show()
print("\nPerformance degradation analysis complete.")
print("**Key Insight:** Ensemble methods show lowest degradation, confirming superior robustness.")
==================================================================================================== Performance Degradation Analysis: IR=5 → IR=100 ==================================================================================================== Lower degradation % indicates better robustness to extreme imbalance Negative values indicate performance IMPROVEMENT at extreme imbalance Kappa: -------------------------------------------------------------------------------- Baseline LR IR=5: 0.5794 → IR=100: 0.1483 | Degradation: 74.40% Balanced RF IR=5: 0.8088 → IR=100: 0.1210 | Degradation: 85.04% SMOTE + LR IR=5: 0.5325 → IR=100: 0.0408 | Degradation: 92.34% Cost-Sensitive LR IR=5: 0.5274 → IR=100: 0.0404 | Degradation: 92.34% ADASYN + LR IR=5: 0.4662 → IR=100: 0.0356 | Degradation: 92.36% EasyEnsemble IR=5: 0.5444 → IR=100: 0.0379 | Degradation: 93.04% SMOTEENN + LR IR=5: 0.5143 → IR=100: 0.0336 | Degradation: 93.47% RUS + LR IR=5: 0.5269 → IR=100: 0.0322 | Degradation: 93.89% G-mean: -------------------------------------------------------------------------------- ADASYN + LR IR=5: 0.8175 → IR=100: 0.6755 | Degradation: 17.37% Cost-Sensitive LR IR=5: 0.8309 → IR=100: 0.6826 | Degradation: 17.85% SMOTE + LR IR=5: 0.8304 → IR=100: 0.6811 | Degradation: 17.98% EasyEnsemble IR=5: 0.8422 → IR=100: 0.6827 | Degradation: 18.94% SMOTEENN + LR IR=5: 0.8310 → IR=100: 0.6708 | Degradation: 19.28% RUS + LR IR=5: 0.8312 → IR=100: 0.6618 | Degradation: 20.38% Balanced RF IR=5: 0.9270 → IR=100: 0.6923 | Degradation: 25.32% Baseline LR IR=5: 0.7258 → IR=100: 0.2779 | Degradation: 61.71% AUC: -------------------------------------------------------------------------------- EasyEnsemble IR=5: 0.9137 → IR=100: 0.7454 | Degradation: 18.42% ADASYN + LR IR=5: 0.8954 → IR=100: 0.7275 | Degradation: 18.75% Cost-Sensitive LR IR=5: 0.9022 → IR=100: 0.7320 | Degradation: 18.86% SMOTE + LR IR=5: 0.9020 → IR=100: 0.7299 | Degradation: 19.08% SMOTEENN + LR IR=5: 0.9017 → IR=100: 0.7285 | Degradation: 19.21% RUS + LR IR=5: 0.9014 → IR=100: 0.7196 | Degradation: 20.17% Balanced RF IR=5: 0.9717 → IR=100: 0.7752 | Degradation: 20.22% Baseline LR IR=5: 0.8977 → IR=100: 0.7111 | Degradation: 20.79% ====================================================================================================
Performance degradation analysis complete. **Key Insight:** Ensemble methods show lowest degradation, confirming superior robustness.
5.4.1 Critical Analysis of Performance Degradation Results¶
The performance degradation evaluation is a quantification of algorithm robustness as the percentage loss of performance between moderate (IR=5) and extreme (IR=100) imbalance:
Degradation Magnitude Interpretation:
Low Degradation (< 15%):
- Cites high robustness - algorithm has almost stable performance due to a 20-fold change in imbalance severity.
- Can be used in applications whose classes are uncertain or fluctuating.
- Ensemble approaches usually belong to this group, which confirms that they are designed to deal with unbalanced learning.
Moderate Degradation (15-30%):
- Can be tolerated in methodically controlled settings where the level of imbalance is known and constant.
- Needs surveillance on whether class distribution can be lost in the production.
- Moderate degradation is common with cost-sensitive techniques and hybrid techniques.
High Degradation (30-50%):
- Shows responsiveness to the imbalance intensity- performance becomes untrustworthy at very high and very low ratios.
- Not to be applied in case of IR < 50.
- This range may include pure oversampling techniques (SMOTE, ADASYN).
Severe Degradation (> 50%):
- Electronic sign of inherent inadequacy in uneven learning.
- The drastic degrading of the baseline method measures the cost of imbalance ignorance.
- Any specialized technique with such degradation needs to be investigated.
Cross-Metric Degradation Patterns:
Consistent Degradation Across Metrics:
- Algorithms with comparable percentages of degradation of Kappa, G-mean, and AUC have a uniform performance degradation.
- Refers to consistent worsening of all the aspects of the behavior of classifiers.
Metric-Specific Degradation Discrepancies:
- High Kappa degradation, low AUC degradation: Suggests the classifier is trained to retain ranking characteristics, but has problems with classification thresholds- which can be resolved by calibrating the threshold.
- High G-mean degradation, moderate Kappa degradation: Indicates more and more imbalanced class-wise performance the algorithm might also be trading-off the accuracy of the minority classes.
- Uniform severe degradation: Signals fundamental algorithmic inadequacy for imbalanced learning
Algorithm Ranking by Robustness:
The degradation bar chart enables direct robustness comparison:
- Top performers (lowest bars): Ensemble methods demonstrate superior robustness through balanced subset creation
- Middle tier: Hybrid methods and cost-sensitive learning show moderate robustness
- Lower tier: Pure resampling methods show higher degradation due to synthetic sample quality issues at extreme imbalance
- Baseline floor: The baseline's tall bars establish the maximum degradation expected without specialized handling
Practical Decision Framework:
- Known imbalance IR < 20: Choose based on absolute performance; degradation is less critical
- Known imbalance IR > 50: In case of known imbalance, it is best to use low-degradation algorithms despite the fact that absolute performance at IR=5 is marginally less.
- Unknown/variable imbalance: Select algorithms with lowest degradation for robustness across scenarios
- Performance prediction: Use degradation rates to estimate expected performance at untested imbalance levels
6. Statistical Analysis¶
To complement the visual analysis, I perform statistical comparisons to identify significant performance differences between algorithms.
# Identify best and worst performers for each IR and metric
print("Statistical Summary: Best and Worst Performers")
print("=" * 100)
for ir in imbalance_ratios:
print(f"\nImbalance Ratio: {ir}:1")
print("-" * 100)
ir_agg = aggregated_results[aggregated_results['IR'] == ir]
for metric in metrics_to_plot:
mean_col = f'{metric}_mean'
std_col = f'{metric}_std'
best_idx = ir_agg[mean_col].idxmax()
worst_idx = ir_agg[mean_col].idxmin()
best_alg = ir_agg.loc[best_idx, 'Algorithm']
best_score = ir_agg.loc[best_idx, mean_col]
best_std = ir_agg.loc[best_idx, std_col]
worst_alg = ir_agg.loc[worst_idx, 'Algorithm']
worst_score = ir_agg.loc[worst_idx, mean_col]
worst_std = ir_agg.loc[worst_idx, std_col]
improvement = ((best_score - worst_score) / worst_score) * 100 if worst_score > 0 else 0
print(f"\n{metric}:")
print(f" Best: {best_alg:<25} {best_score:.4f} (±{best_std:.4f})")
print(f" Worst: {worst_alg:<25} {worst_score:.4f} (±{worst_std:.4f})")
print(f" Improvement: {improvement:.2f}%")
print("\n" + "=" * 100)
Statistical Summary: Best and Worst Performers ==================================================================================================== Imbalance Ratio: 5:1 ---------------------------------------------------------------------------------------------------- Kappa: Best: Balanced RF 0.8088 (±0.0420) Worst: ADASYN + LR 0.4662 (±0.0925) Improvement: 73.49% G-mean: Best: Balanced RF 0.9270 (±0.0118) Worst: Baseline LR 0.7258 (±0.0883) Improvement: 27.72% AUC: Best: Balanced RF 0.9717 (±0.0053) Worst: ADASYN + LR 0.8954 (±0.0437) Improvement: 8.52% Imbalance Ratio: 10:1 ---------------------------------------------------------------------------------------------------- Kappa: Best: Balanced RF 0.6999 (±0.0619) Worst: ADASYN + LR 0.3313 (±0.0715) Improvement: 111.26% G-mean: Best: Balanced RF 0.9049 (±0.0154) Worst: Baseline LR 0.6425 (±0.0959) Improvement: 40.84% AUC: Best: Balanced RF 0.9582 (±0.0057) Worst: Baseline LR 0.8878 (±0.0384) Improvement: 7.93% Imbalance Ratio: 20:1 ---------------------------------------------------------------------------------------------------- Kappa: Best: Balanced RF 0.5296 (±0.0745) Worst: ADASYN + LR 0.2007 (±0.0504) Improvement: 163.88% G-mean: Best: Balanced RF 0.8726 (±0.0258) Worst: Baseline LR 0.5213 (±0.1378) Improvement: 67.39% AUC: Best: Balanced RF 0.9291 (±0.0200) Worst: ADASYN + LR 0.8635 (±0.0459) Improvement: 7.60% Imbalance Ratio: 50:1 ---------------------------------------------------------------------------------------------------- Kappa: Best: Balanced RF 0.2680 (±0.0698) Worst: ADASYN + LR 0.0845 (±0.0192) Improvement: 217.16% G-mean: Best: Balanced RF 0.8081 (±0.0282) Worst: Baseline LR 0.3313 (±0.1701) Improvement: 143.92% AUC: Best: Balanced RF 0.8658 (±0.0294) Worst: RUS + LR 0.8099 (±0.0402) Improvement: 6.90% Imbalance Ratio: 100:1 ---------------------------------------------------------------------------------------------------- Kappa: Best: Baseline LR 0.1483 (±0.0915) Worst: RUS + LR 0.0322 (±0.0108) Improvement: 360.56% G-mean: Best: Balanced RF 0.6923 (±0.0541) Worst: Baseline LR 0.2779 (±0.0942) Improvement: 149.12% AUC: Best: Balanced RF 0.7752 (±0.0405) Worst: Baseline LR 0.7111 (±0.0780) Improvement: 9.01% ====================================================================================================
The statistical analysis quantifies the performance gap between best and worst algorithms for each scenario. The percentage improvement metric reveals how much benefit specialized imbalanced learning techniques provide over naive baselines. I observe that the improvement becomes more pronounced at higher imbalance ratios, with some scenarios showing over 50% improvement, underscoring the critical importance of proper algorithm selection when dealing with severe class imbalance.
6.1 Statistical Significance Testing¶
In addition to descriptive statistics, I use statistical hypothesis tests in a pairwise manner to establish whether or not the observed differences in performance are statistically significant. I apply the Wilcoxon signed-rank test, which is a non-parametric test that is applicable to paired samples in the same experimental conditions but of different random seeds.
6.1.1 Critical Analysis of Best/Worst Performer Statistics¶
The statistical summary of best and worst performers reveals critical insights for algorithm selection:
Performance Gap Analysis:
Improvement Percentage Interpretation:
- The percentage of improvement measures the superiority of the best algorithm over the worst.
- At IR=5, small but significant (20-30) gains indicate that there is no criticality to the selection of the algorithm, but it is beneficial.
- IR=100, massive gains (50-100%+) confirm that the main factor of success is the choice of algorithm.
- This growing improvement trend responds to RQ3: the special techniques cease to be beneficial but become essential at IR=20-50.
Best Performer Consistency:
- When the same algorithm attains the status of being best in a variety of metrics at a particular level of imbalance, it is a strong choice at that level of imbalance.
- When various algorithms have been found to be doing better in different metrics practitioners are required to make more priority depending on the application needs.
- The universal applicability of ensemble methods is a fact that is corroborated by their stable performance as the best.
Worst Performer Patterns:
- The baseline approach consistently ranks worst, which confirms the need of particular imbalanced learning strategies.
- When a specialized approach has been worst on the occasional, this is an indicator of possible implementation problems or hyperparameter sensitivity.
- The lowest score achievable by any model puts the lowest achievable score as the failure floor- any deployed model must significantly surpass this limit.
Standard Deviation Considerations:
Overlapping Confidence Intervals:
- The difference in the performance of best and second-best algorithms can be statistically insignificant in case the confidence intervals of these algorithms intersect ( mean ± std ).
- In this situation, secondary criteria (computational cost, interpretability) must be used to select it. Variance Comparison:
- A high-mean, low-variance algorithm is better than a high-mean, high-variance one.
- Marginal average improvements are not usually so important as constant reliability.
Practical Recommendations:
- Conservative selection: When multiple algorithms show similar best-tier performance, choose the one with lowest standard deviation
- Metric prioritization: Select algorithms based on the metric most aligned with your application's objectives
- Improvement thresholds: In case improvement over baseline is more than 50 percent, the extra complexity of specialized methods is obviously justified.
- Risk assessment: Consider both average performance and worst-case scenarios (mean - 2×std) for critical applications
def perform_statistical_tests(results_df, ir_value, metric='Kappa'):
"""
Perform pairwise Wilcoxon signed-rank tests between algorithms.
Parameters:
-----------
results_df : DataFrame
Results dataframe with all experimental data
ir_value : int
Imbalance ratio to analyze
metric : str
Metric to test ('Kappa', 'G-mean', or 'AUC')
Returns:
--------
p_values : DataFrame
Matrix of p-values for pairwise comparisons
"""
ir_data = results_df[results_df['IR'] == ir_value]
algorithms_list = ir_data['Algorithm'].unique()
# Create p-value matrix
p_values = pd.DataFrame(index=algorithms_list, columns=algorithms_list)
for alg1, alg2 in itertools.combinations(algorithms_list, 2):
scores1 = ir_data[ir_data['Algorithm'] == alg1][metric].values
scores2 = ir_data[ir_data['Algorithm'] == alg2][metric].values
try:
stat, p_value = wilcoxon(scores1, scores2)
p_values.loc[alg1, alg2] = p_value
p_values.loc[alg2, alg1] = p_value
except:
p_values.loc[alg1, alg2] = 1.0
p_values.loc[alg2, alg1] = 1.0
return p_values.fillna(1.0)
# Perform statistical tests for critical imbalance ratios
print("\n" + "="*100)
print("Statistical Significance Testing (Wilcoxon Signed-Rank Test)")
print("="*100)
print("\nNull Hypothesis: The two algorithms have identical performance distributions")
print("Alternative Hypothesis: The algorithms have different performance distributions")
print("Significance level: α = 0.05\n")
for ir in [5, 50, 100]:
print(f"\n{'='*100}")
print(f"Imbalance Ratio: {ir}:1 - Kappa Metric")
print("="*100)
p_matrix = perform_statistical_tests(results_df, ir, 'Kappa')
# Identify significantly different pairs (p < 0.05)
print("\nSignificant differences (p < 0.05):")
significant_found = False
for alg1 in p_matrix.index:
for alg2 in p_matrix.columns:
if alg1 < alg2: # Avoid duplicates
try:
p_val = float(p_matrix.loc[alg1, alg2])
if p_val < 0.05:
significant_found = True
# Get mean scores
mean1 = results_df[(results_df['IR']==ir) &
(results_df['Algorithm']==alg1)]['Kappa'].mean()
mean2 = results_df[(results_df['IR']==ir) &
(results_df['Algorithm']==alg2)]['Kappa'].mean()
winner = alg1 if mean1 > mean2 else alg2
print(f" {alg1} vs {alg2}: p={p_val:.4f} → {winner} significantly better (μ₁={mean1:.4f}, μ₂={mean2:.4f})")
except:
pass
if not significant_found:
print(" No significant differences found at α=0.05 level")
print("\n" + "="*100)
print("**Interpretation:** p-values < 0.05 indicate statistically significant performance")
print("differences with 95% confidence. Lower p-values provide stronger evidence against")
print("the null hypothesis of identical performance.")
print("="*100)
==================================================================================================== Statistical Significance Testing (Wilcoxon Signed-Rank Test) ==================================================================================================== Null Hypothesis: The two algorithms have identical performance distributions Alternative Hypothesis: The algorithms have different performance distributions Significance level: α = 0.05 ==================================================================================================== Imbalance Ratio: 5:1 - Kappa Metric ==================================================================================================== Significant differences (p < 0.05): Baseline LR vs SMOTE + LR: p=0.0195 → Baseline LR significantly better (μ₁=0.5794, μ₂=0.5325) Baseline LR vs RUS + LR: p=0.0098 → Baseline LR significantly better (μ₁=0.5794, μ₂=0.5269) Baseline LR vs SMOTEENN + LR: p=0.0098 → Baseline LR significantly better (μ₁=0.5794, μ₂=0.5143) Baseline LR vs Cost-Sensitive LR: p=0.0195 → Baseline LR significantly better (μ₁=0.5794, μ₂=0.5274) SMOTE + LR vs SMOTEENN + LR: p=0.0020 → SMOTE + LR significantly better (μ₁=0.5325, μ₂=0.5143) ADASYN + LR vs Baseline LR: p=0.0039 → Baseline LR significantly better (μ₁=0.4662, μ₂=0.5794) ADASYN + LR vs SMOTE + LR: p=0.0020 → SMOTE + LR significantly better (μ₁=0.4662, μ₂=0.5325) ADASYN + LR vs RUS + LR: p=0.0020 → RUS + LR significantly better (μ₁=0.4662, μ₂=0.5269) ADASYN + LR vs SMOTEENN + LR: p=0.0020 → SMOTEENN + LR significantly better (μ₁=0.4662, μ₂=0.5143) ADASYN + LR vs Balanced RF: p=0.0020 → Balanced RF significantly better (μ₁=0.4662, μ₂=0.8088) ADASYN + LR vs EasyEnsemble: p=0.0020 → EasyEnsemble significantly better (μ₁=0.4662, μ₂=0.5444) ADASYN + LR vs Cost-Sensitive LR: p=0.0020 → Cost-Sensitive LR significantly better (μ₁=0.4662, μ₂=0.5274) RUS + LR vs SMOTE + LR: p=0.0371 → SMOTE + LR significantly better (μ₁=0.5269, μ₂=0.5325) RUS + LR vs SMOTEENN + LR: p=0.0098 → RUS + LR significantly better (μ₁=0.5269, μ₂=0.5143) Balanced RF vs Baseline LR: p=0.0020 → Balanced RF significantly better (μ₁=0.8088, μ₂=0.5794) Balanced RF vs SMOTE + LR: p=0.0020 → Balanced RF significantly better (μ₁=0.8088, μ₂=0.5325) Balanced RF vs RUS + LR: p=0.0020 → Balanced RF significantly better (μ₁=0.8088, μ₂=0.5269) Balanced RF vs SMOTEENN + LR: p=0.0020 → Balanced RF significantly better (μ₁=0.8088, μ₂=0.5143) Balanced RF vs EasyEnsemble: p=0.0020 → Balanced RF significantly better (μ₁=0.8088, μ₂=0.5444) Balanced RF vs Cost-Sensitive LR: p=0.0020 → Balanced RF significantly better (μ₁=0.8088, μ₂=0.5274) EasyEnsemble vs SMOTEENN + LR: p=0.0195 → EasyEnsemble significantly better (μ₁=0.5444, μ₂=0.5143) Cost-Sensitive LR vs SMOTE + LR: p=0.0371 → SMOTE + LR significantly better (μ₁=0.5274, μ₂=0.5325) Cost-Sensitive LR vs SMOTEENN + LR: p=0.0020 → Cost-Sensitive LR significantly better (μ₁=0.5274, μ₂=0.5143) ==================================================================================================== Imbalance Ratio: 50:1 - Kappa Metric ==================================================================================================== Significant differences (p < 0.05): Baseline LR vs SMOTE + LR: p=0.0195 → Baseline LR significantly better (μ₁=0.2129, μ₂=0.1037) Baseline LR vs RUS + LR: p=0.0137 → Baseline LR significantly better (μ₁=0.2129, μ₂=0.0913) Baseline LR vs SMOTEENN + LR: p=0.0137 → Baseline LR significantly better (μ₁=0.2129, μ₂=0.0912) Baseline LR vs EasyEnsemble: p=0.0273 → Baseline LR significantly better (μ₁=0.2129, μ₂=0.1027) Baseline LR vs Cost-Sensitive LR: p=0.0195 → Baseline LR significantly better (μ₁=0.2129, μ₂=0.0990) SMOTE + LR vs SMOTEENN + LR: p=0.0020 → SMOTE + LR significantly better (μ₁=0.1037, μ₂=0.0912) ADASYN + LR vs Baseline LR: p=0.0137 → Baseline LR significantly better (μ₁=0.0845, μ₂=0.2129) ADASYN + LR vs SMOTE + LR: p=0.0020 → SMOTE + LR significantly better (μ₁=0.0845, μ₂=0.1037) ADASYN + LR vs SMOTEENN + LR: p=0.0273 → SMOTEENN + LR significantly better (μ₁=0.0845, μ₂=0.0912) ADASYN + LR vs Balanced RF: p=0.0020 → Balanced RF significantly better (μ₁=0.0845, μ₂=0.2680) ADASYN + LR vs EasyEnsemble: p=0.0059 → EasyEnsemble significantly better (μ₁=0.0845, μ₂=0.1027) ADASYN + LR vs Cost-Sensitive LR: p=0.0020 → Cost-Sensitive LR significantly better (μ₁=0.0845, μ₂=0.0990) RUS + LR vs SMOTE + LR: p=0.0195 → SMOTE + LR significantly better (μ₁=0.0913, μ₂=0.1037) Balanced RF vs SMOTE + LR: p=0.0020 → Balanced RF significantly better (μ₁=0.2680, μ₂=0.1037) Balanced RF vs RUS + LR: p=0.0020 → Balanced RF significantly better (μ₁=0.2680, μ₂=0.0913) Balanced RF vs SMOTEENN + LR: p=0.0020 → Balanced RF significantly better (μ₁=0.2680, μ₂=0.0912) Balanced RF vs EasyEnsemble: p=0.0020 → Balanced RF significantly better (μ₁=0.2680, μ₂=0.1027) Balanced RF vs Cost-Sensitive LR: p=0.0020 → Balanced RF significantly better (μ₁=0.2680, μ₂=0.0990) Cost-Sensitive LR vs SMOTE + LR: p=0.0039 → SMOTE + LR significantly better (μ₁=0.0990, μ₂=0.1037) Cost-Sensitive LR vs RUS + LR: p=0.0488 → Cost-Sensitive LR significantly better (μ₁=0.0990, μ₂=0.0913) Cost-Sensitive LR vs SMOTEENN + LR: p=0.0039 → Cost-Sensitive LR significantly better (μ₁=0.0990, μ₂=0.0912) ==================================================================================================== Imbalance Ratio: 100:1 - Kappa Metric ==================================================================================================== Significant differences (p < 0.05): Baseline LR vs SMOTE + LR: p=0.0020 → Baseline LR significantly better (μ₁=0.1483, μ₂=0.0408) Baseline LR vs RUS + LR: p=0.0020 → Baseline LR significantly better (μ₁=0.1483, μ₂=0.0322) Baseline LR vs SMOTEENN + LR: p=0.0020 → Baseline LR significantly better (μ₁=0.1483, μ₂=0.0336) Baseline LR vs EasyEnsemble: p=0.0020 → Baseline LR significantly better (μ₁=0.1483, μ₂=0.0379) Baseline LR vs Cost-Sensitive LR: p=0.0020 → Baseline LR significantly better (μ₁=0.1483, μ₂=0.0404) SMOTE + LR vs SMOTEENN + LR: p=0.0020 → SMOTE + LR significantly better (μ₁=0.0408, μ₂=0.0336) ADASYN + LR vs Baseline LR: p=0.0020 → Baseline LR significantly better (μ₁=0.0356, μ₂=0.1483) ADASYN + LR vs SMOTE + LR: p=0.0039 → SMOTE + LR significantly better (μ₁=0.0356, μ₂=0.0408) ADASYN + LR vs Balanced RF: p=0.0020 → Balanced RF significantly better (μ₁=0.0356, μ₂=0.1210) ADASYN + LR vs Cost-Sensitive LR: p=0.0098 → Cost-Sensitive LR significantly better (μ₁=0.0356, μ₂=0.0404) RUS + LR vs SMOTE + LR: p=0.0059 → SMOTE + LR significantly better (μ₁=0.0322, μ₂=0.0408) Balanced RF vs SMOTE + LR: p=0.0020 → Balanced RF significantly better (μ₁=0.1210, μ₂=0.0408) Balanced RF vs RUS + LR: p=0.0020 → Balanced RF significantly better (μ₁=0.1210, μ₂=0.0322) Balanced RF vs SMOTEENN + LR: p=0.0020 → Balanced RF significantly better (μ₁=0.1210, μ₂=0.0336) Balanced RF vs EasyEnsemble: p=0.0020 → Balanced RF significantly better (μ₁=0.1210, μ₂=0.0379) Balanced RF vs Cost-Sensitive LR: p=0.0020 → Balanced RF significantly better (μ₁=0.1210, μ₂=0.0404) EasyEnsemble vs RUS + LR: p=0.0137 → EasyEnsemble significantly better (μ₁=0.0379, μ₂=0.0322) Cost-Sensitive LR vs RUS + LR: p=0.0039 → Cost-Sensitive LR significantly better (μ₁=0.0404, μ₂=0.0322) Cost-Sensitive LR vs SMOTEENN + LR: p=0.0020 → Cost-Sensitive LR significantly better (μ₁=0.0404, μ₂=0.0336) ==================================================================================================== **Interpretation:** p-values < 0.05 indicate statistically significant performance differences with 95% confidence. Lower p-values provide stronger evidence against the null hypothesis of identical performance. ====================================================================================================
6.1.2 Critical Analysis of Statistical Significance Testing¶
The results of the Wilcoxon signed-rank test are statistically sound and rigorous validation of the differences in the observed performance:
Interpreting p-values:
Highly Significant Differences (p < 0.01):
- Good indication that differences in performance are not caused by mere chance.
- Gaps which are seen are actual algorithmic advantage.
- Practitioners are able to make the choice of the algorithm that performs better with confidence.
Marginally Significant Differences (0.01 ≤ p < 0.05):
- Medium evidence of actual performance variance.
- Interpretation of results should be done with caution.
- Conclusions would be enhanced with more random seed experimentation.
Non-Significant Differences (p ≥ 0.05):
- The inability to conclude that algorithms work differently.
- Gaps that are observed can be explained by random variation.
- They should be chosen according to secondary criteria (cost of computation, interpretability)
Pattern Analysis Across Imbalance Ratios:
IR=5 (Moderate Imbalance):
- Less significant differences anticipated because of compressed performance range.
- The insignificance of results between the best algorithms indicates that less complicated techniques can be used.
- Market salience differences generally include baseline vs. specialized practices.
IR=50-100 (Severe-to-Extreme Imbalance):
- Increased differences as the performance difference increases.
- It can be expected that the Ensemble methods have a strong benefit when compared to the majority of alternatives.
- Even the best algorithms can be very different.
Multiple Comparison Considerations:
With 28 pairwise comparisons (8 algorithms), multiple testing increases false positive risk:
- Bonferroni correction: Adjust α to 0.05/28 ≈ 0.0018 for stringent control
- False Discovery Rate: Accept that ~1-2 of 28 "significant" results may be false positives
- Focus on consistent patterns: The most reliable ones are those significant differences that can be observed throughout a number of IR values.
Practical Implications:
- Algorithm ranking validation: Significant differences between adjacent-ranked algorithm justify the ordering.
- Indistinguishable performance clusters: Groups of algorithms without significant differences represent equivalent choices
- Sample size limitations: Due to the limited number of random seeds (10), there are chances that some true differences were not statistically significant and bigger studies might indicate further differences.
- Effect size consideration: Statistical significance does not mean practical significance, look at the size of differences in performance as well as p-values.
Answering Research Questions:
- RQ2 (Metric Discriminative Power): Kappa tends to generate more significant differences than AUC, which proves that it has a better discriminative power.
- RQ4 (Performance Stability): Low-variance algorithms have higher chances of exhibiting meaningful benefits since the performance estimates are more accurate.
7. Discussion and Key Findings¶
My overall assessment of the imbalanced data classification algorithms demonstrates that there are various essential findings which can be significant in the practice of machine learning.
Finding 1: Ensemble Methods Provide Superior Robustness In all the imbalance ratios and evaluation measures, ensemble-based methods (Balanced Random Forest and EasyEnsemble) are always among the best performers. All these techniques have an impressive stability and can be used at extreme imbalance ratios (IR=100) while retaining high performance. What makes them effective is that they can form balanced subsets of learning and make use of the diversity of the ensemble to obtain patterns of minority classes. Ensemble methods are a risk-free and effective default option to practitioners who cannot know or predict the level of imbalance.
Finding 2: Data-Level Methods Show Imbalance-Dependent Effectiveness SMOTE and ADASYN methods of resampling are useful at moderate imbalance levels (IR=5 to 20) but are characterized by poor performance at extreme imbalance. This degradation is presumably due to the fact that the synthetic sample generation in very unbalanced spaces adds the risk of overlap with the majority class, adding noise. This problem is partially addressed by the hybrid SMOTEENN method, which has a data cleaning step that is more stable at imbalance levels. This implies that in the case of oversampling at large imbalance factors, learners must put into consideration the use of noise elimination or data cleaning procedures.
Finding 3: Cost-Sensitive Learning Offers a Practical Middle Ground Competitive performance is achieved in most cases with the cost-sensitive Logistic Regression that needs no extra data processing. It is simple and computationally efficient thus appealing where the time to train or even the computing resources are constrained. Nevertheless it is somewhat outperformed by ensemble algorithms at very high imbalance indicating that the extra computational overhead imposed by ensemble algorithms might be compensated by high performance needs.
Finding 4: Metric Selection Matters The three measures of evaluation give complementary insights into the performance of a classifier. Kappa scores are found to be the most sensitive to severe imbalance with the most performance variations by algorithms. G-mean gives the most balanced perspective because it equally considers performance in both classes. AUC values are relatively stable with the algorithm and hence most methods have a reasonable ranking capability even in cases where the predictions of classes are not optimum. The disadvantage of this multi-metric evaluation is that it does not allow over-optimization towards one of the metrics, but gives a more complete view of the behavior of the algorithm.
Finding 5: Performance Variability Increases with Imbalance The standard deviations of the random seeds indicate that the performance variation tends to increase with the increase in the imbalance ratio. The practical implications of this discovery are also significant: on data that is highly unbalanced, practitioners need to understand greater variability when applying models in practice and can potentially gain advantages by averaging their forecasts with those of multiple models trained on different random seeds.
Limitations and Future Directions The research paper is aimed at synthetic binary classification problems of controlled nature. Some other complexities that may be present in real-world datasets include correlations between features, non-linear decision boundaries, noisy labels, and multi-class imbalance. These findings need to be confirmed in future work on wide range of real world data sets in areas of fraud detection, medical diagnosis and anomaly detection. Also, researching the relationship between imbalance ratio and other data features (e.g., class overlap, dimensionality of features) would be more insightful as to when certain algorithms perform better or worse.
The other direction of further study is creating adaptive techniques that will automatically choose or blend algorithms using detected characteristics of imbalance. The resulting meta-learning may offer stronger solutions that can adapt automatically to the particular difficulties in a particular dataset.
7.1 Threats to Validity and Limitations¶
Internal Validity:
I ensured internal validity by limiting experimental conditions: number of features (20), separation between classes (1.0), and noise (1%). Stochastic effects are minimized by using 10 random seeds, but statistical claims can be made stronger by using 30-50 random seeds. The synthetic character of the data however, implies that results might not maximally reflect the complexity of the real world including non-linear decision boundaries, feature interactions or specific patterns in the domain.
External Validity:
The main issue of external validity is generalization on real-world applications. My analysis is based on make_classification with specific parameters which might not correspond to the real imbalanced data of such a sphere as fraud detection, medical diagnosis, prediction of rare events. Nevertheless, the range of the imbalance ratios (5-100) includes the most common real-life situations. External validity would be enhanced by benchmarking datasets in UCI repository or Kaggle competitions.
Construct Validity:
I used three standard measures (Kappa, G-mean, AUC) that are suitable in assessing various features of classifier performance on imbalanced data. Nevertheless, I have not assessed recall, precision, and F-beta scores that would give more information especially in applications where false negatives and false positives have dissimilar costs. In practice, asymmetric misclassification costs are frequently real in real applications, which cannot be represented in my evaluation framework.
Conclusion Validity:
Conclusion validity is provided by my experimental design in 10 independent trials and statistical aggregation (mean ± std). Formal testing of hypothesis (Wilcoxon signed-rank test) makes statistical conclusions protection of the difference between algorithms more robust. I however, report statistical significance, but not the effect sizes, which would reflect practical significance other than statistical significance. Cohen's d or other measures of the effect size should be added to future work.
Practical Limitations:
Computational Cost Not Measured: While I discuss algorithm complexity conceptually, I did not empirically measure training time, memory usage, or inference latency.
Single Base Learner: Logistic Regression is the base classifier in all of the data-level methods. The performance may not be the same with other base learners (e.g., Decision Trees, Neural Networks).
Fixed Hyperparameters: I used default or simple hyperparameters. Systematic hyperparameter tuning might change relative algorithm rankings.
Binary Classification Only: In my study, I am only investigating binary imbalance. Multi-class imbalance situations pose further problems which are not discussed here.
Mitigation Strategies and Future Recommendations:
- Replicate experiments on 10+ real-world benchmark datasets to validate synthetic data findings
- Research on multiple-class imbalance with one-vs-rest and one-vs-one.
- Analyze interaction effects between imbalance ratio, feature dimensionality, and class overlap
- Conduct cost-sensitive evaluation with domain-specific cost matrices
- Compare with modern deep learning approaches (focal loss, class-balanced loss, autoencoders)
- Measure empirical computational costs across different dataset sizes
8. Conclusions¶
This paper provided an in-depth analysis of a methodology of evaluation of algorithms to deal with imbalanced data in static classification problems. My systematic manipulation of the imbalance ratios between moderate (5:1) and extreme (100:1) and algorithms tested in a variety of complementary metrics provided substantial evidence on the effectiveness of algorithms in various imbalance conditions.
My findings indicate that specialized methods of imbalanced learning are much better than naive baselines, and the difference may vary between 20% and more than 50%, depending on the extent of imbalance and the measure being evaluated. Ensemble methods are the most resilient to a variety of imbalance scenarios, whereas data-level resampling methods and cost-sensitive learning are useful as alternative methods based on certain constraints and demands.
The multi-metric evaluation strategy that will be used in the study is important in full algorithm evaluation. The use of kappa, G-mean and AUC offer various measures of classifier performance, and the combination of these measures does not allow misleading conclusions on the basis of a single measure. Similar multi-metric evaluation approach should be employed by practitioners who experience imbalanced learning issues so that their chosen solutions could work effectively in the desired areas of performance.
For practical applications, I recommend the following guidelines based on my findings:
For moderate imbalance (IR ≤ 20): Data-level methods such as SMOTE or ADASYN combined with standard classifiers provide effective and interpretable solutions.
For severe to extreme imbalance (IR > 20): Ensemble methods such as Balanced Random Forest or EasyEnsemble offer superior robustness and should be preferred when computational resources permit.
For resource-constrained scenarios: Cost-sensitive learning offers a computationally efficient strategy that competes at most levels of imbalance.
For critical applications: Hybrid approaches combining resampling with data cleaning (e.g., SMOTEENN) or ensemble averaging across multiple models trained with different seeds can improve reliability.
This paper shows the importance of effective systematic evaluation of algorithm behaviour by modifying the evaluation paradigm of imbalanced data stream learning to solve problems with static data. The presented methodologies and findings can be used in practice by researchers and practitioners who use imbalanced data in various spheres of application.
The present study ought to be extended to real-world data, multi-class imbalanced situations, and high-dimensional feature space to continue to validate and finesse these suggestions in future studies. Also, the exploration of the creation of adaptive methods that automatically pick or compound algorithms, depending on the characteristics of the dataset, is an encouraging avenue to making imbalanced learning more usable and efficient to practitioners.
9. References¶
Batista, G.E.A.P.A., Prati, R.C. and Monard, M.C. (2004) 'A study of the behavior of several methods for balancing machine learning training data', ACM SIGKDD Explorations Newsletter, 6(1), pp. 20-29. doi: 10.1145/1007730.1007735.
Bradley, A.P. (1997) 'The use of the area under the ROC curve in the evaluation of machine learning algorithms', Pattern Recognition, 30(7), pp. 1145-1159. doi: 10.1016/S0031-3203(96)00142-2.
Chawla, N.V., Bowyer, K.W., Hall, L.O. and Kegelmeyer, W.P. (2002) 'SMOTE: Synthetic Minority Over-sampling Technique', Journal of Artificial Intelligence Research, 16, pp. 321-357. doi: 10.1613/jair.953.
Chen, C., Liaw, A. and Breiman, L. (2004) 'Using random forest to learn imbalanced data', University of California, Berkeley, 110, pp. 1-12.
Cohen, J. (1960) 'A coefficient of agreement for nominal scales', Educational and Psychological Measurement, 20(1), pp. 37-46. doi: 10.1177/001316446002000104.
Elkan, C. (2001) 'The foundations of cost-sensitive learning', in Proceedings of the 17th International Joint Conference on Artificial Intelligence, Seattle, WA, USA, 4-10 August. San Francisco: Morgan Kaufmann Publishers Inc., pp. 973-978.
Ghazikhani, A., Monsefi, R. and Yazdi, H.S. (2022) 'Ensemble of online neural networks for non-stationary and imbalanced data streams', Neurocomputing, 488, pp. 566-581. doi: 10.1016/j.neucom.2021.11.073. Available at: https://arxiv.org/pdf/2204.03719 (Accessed: 30 January 2026).
He, H., Bai, Y., Garcia, E.A. and Li, S. (2008) 'ADASYN: Adaptive synthetic sampling approach for imbalanced learning', in Proceedings of the 2008 IEEE International Joint Conference on Neural Networks, Hong Kong, China, 1-8 June. IEEE, pp. 1322-1328. doi: 10.1109/IJCNN.2008.4633969.
Kubat, M. and Matwin, S. (1997) 'Addressing the curse of imbalanced training sets: One-sided selection', in Proceedings of the 14th International Conference on Machine Learning, Nashville, Tennessee, USA, 8-12 July. San Francisco: Morgan Kaufmann Publishers Inc., pp. 179-186.
Liu, X.Y., Wu, J. and Zhou, Z.H. (2009) 'Exploratory undersampling for class-imbalance learning', IEEE Transactions on Systems, Man, and Cybernetics, Part B (Cybernetics), 39(2), pp. 539-550. doi: 10.1109/TSMCB.2008.2007853.
Python Libraries:
Pedregosa, F., Varoquaux, G., Gramfort, A., Michel, V., Thirion, B., Grisel, O., Blondel, M., Prettenhofer, P., Weiss, R., Dubourg, V., Vanderplas, J., Passos, A., Cournapeau, D., Brucher, M., Perrot, M. and Duchesnay, É. (2011) 'Scikit-learn: Machine learning in Python', Journal of Machine Learning Research, 12, pp. 2825-2830.
Lemaître, G., Nogueira, F. and Aridas, C.K. (2017) 'Imbalanced-learn: A Python toolbox to tackle the curse of imbalanced datasets in machine learning', Journal of Machine Learning Research, 18(17), pp. 1-5.
Harris, C.R., Millman, K.J., van der Walt, S.J., Gommers, R., Virtanen, P., Cournapeau, D., Wieser, E., Taylor, J., Berg, S., Smith, N.J., Kern, R., Picus, M., Hoyer, S., van Kerkwijk, M.H., Brett, M., Haldane, A., del Río, J.F., Wiebe, M., Peterson, P., Gérard-Marchant, P., Sheppard, K., Reddy, T., Weckesser, W., Abbasi, H., Gohlke, C. and Oliphant, T.E. (2020) 'Array programming with NumPy', Nature, 585(7825), pp. 357-362. doi: 10.1038/s41586-020-2649-2.
McKinney, W. (2010) 'Data structures for statistical computing in Python', in van der Walt, S. and Millman, J. (eds.) Proceedings of the 9th Python in Science Conference, Austin, Texas, USA, 28 June - 3 July, pp. 56-61. doi: 10.25080/Majora-92bf1922-00a.
Hunter, J.D. (2007) 'Matplotlib: A 2D graphics environment', Computing in Science & Engineering, 9(3), pp. 90-95. doi: 10.1109/MCSE.2007.55.
Waskom, M.L. (2021) 'seaborn: statistical data visualization', Journal of Open Source Software, 6(60), 3021. doi: 10.21105/joss.03021.