|
"""
|
|
imbalance_coefficient.py
|
|
|
|
Provides a function `imb_coef` to quantify imbalance in regression targets
|
|
for both continuous and discrete settings. It estimates the deviation of the
|
|
empirical distribution from the uniform distribution using KDE or frequency analysis.
|
|
|
|
Author: Samuel Stocksieker
|
|
License: MIT or CC-BY-4.0
|
|
Date: 2025-08-06
|
|
"""
|
|
|
|
import numpy as np
|
|
import pandas as pd
|
|
import matplotlib.pyplot as plt
|
|
from scipy.stats import gaussian_kde, uniform
|
|
from scipy.integrate import quad
|
|
|
|
|
|
def imb_coef(
|
|
y,
|
|
bdw='scott',
|
|
n_map=100_000,
|
|
distfunc='pdf',
|
|
disttype='cont',
|
|
plot=False,
|
|
p=1,
|
|
k=1,
|
|
w=None,
|
|
scale=True,
|
|
save=False,
|
|
rep='',
|
|
):
|
|
"""
|
|
Computes an imbalance coefficient for a target variable in regression tasks.
|
|
|
|
Parameters:
|
|
----------
|
|
y : array-like
|
|
Target variable (continuous or discrete).
|
|
bdw : str or float
|
|
Bandwidth for KDE ('scott' or float).
|
|
n_map : int
|
|
Number of points for KDE evaluation.
|
|
distfunc : str
|
|
Not used currently (placeholder).
|
|
disttype : str
|
|
'cont' for continuous, 'dis' for discrete targets.
|
|
plot : bool
|
|
Whether to plot distribution comparison.
|
|
p : int
|
|
Exponent for penalizing deviations in discrete mode.
|
|
k : int
|
|
Index for saving figures (used in filenames).
|
|
w : array-like or None
|
|
Optional weights per observation.
|
|
scale : bool
|
|
Whether to scale `y` to [0, 1] in continuous mode.
|
|
save : bool
|
|
Whether to save plot as PNG.
|
|
rep : str
|
|
Folder path prefix for saving plots.
|
|
|
|
Returns:
|
|
-------
|
|
imb_ratio : float
|
|
imbalance coefficient in percentage.
|
|
"""
|
|
|
|
y = np.array(y)
|
|
|
|
if disttype == 'cont':
|
|
|
|
if scale:
|
|
y = (y - y.min()) / (y.max() - y.min())
|
|
|
|
min_y, max_y = y.min(), y.max()
|
|
map_vals = np.linspace(min_y, max_y, n_map)
|
|
|
|
|
|
weights = (
|
|
np.ones(n_map) if w is None else np.interp(map_vals, y, w,
|
|
left=min(w[y == min_y]),
|
|
right=min(w[y == max_y]))
|
|
)
|
|
|
|
kde = gaussian_kde(y, bw_method=bdw)
|
|
kde_vals = kde(map_vals)
|
|
d_best = uniform.pdf(map_vals, loc=min_y, scale=max_y - min_y)
|
|
|
|
kde_func = lambda x: np.interp(x, map_vals, kde_vals)
|
|
weight_func = lambda x: np.interp(x, map_vals, weights)
|
|
|
|
if w is None:
|
|
integrand = lambda x: max(0, 1 - kde_func(x))
|
|
imb_ratio = round(quad(integrand, min_y, max_y, epsabs=1e-5)[0], 4) * 100
|
|
else:
|
|
num = quad(lambda x: max(0, 1 - kde_func(x)) * weight_func(x), min_y, max_y, epsabs=1e-5)[0]
|
|
den = quad(lambda x: weight_func(x), min_y, max_y, epsabs=1e-5)[0]
|
|
imb_ratio = round(num / den, 4) * 100
|
|
|
|
if plot:
|
|
plt.figure(figsize=(10, 5))
|
|
plt.hist(y, bins=100, density=True, color='gray', alpha=0.6, label='Histogram')
|
|
plt.plot(map_vals, kde_vals, label='KDE', color='darkred')
|
|
plt.plot(map_vals, d_best, label='Uniform', color='darkgreen')
|
|
plt.title(f"{imb_ratio:.2f}%", fontsize=16, color='darkred')
|
|
plt.xlabel("Target values")
|
|
plt.ylabel("Density")
|
|
plt.legend()
|
|
if save:
|
|
plt.savefig(f"{rep}imbMetric_dens_{k}.png", bbox_inches='tight')
|
|
plt.show()
|
|
|
|
return imb_ratio
|
|
|
|
elif disttype == 'dis':
|
|
|
|
y = y.astype(int)
|
|
map_vals = np.arange(y.min(), y.max() + 1)
|
|
|
|
if w is None:
|
|
weights = np.ones_like(map_vals)
|
|
else:
|
|
df_w = pd.DataFrame({'map': y, 'w1': w})
|
|
w_agg = df_w.groupby('map')['w1'].mean().reset_index()
|
|
w_all = pd.DataFrame({'map': map_vals})
|
|
w_all = w_all.merge(w_agg, on='map', how='left').fillna(0)
|
|
weights = w_all['w1'].values
|
|
|
|
freqs = pd.Series(y).value_counts(normalize=True).reindex(map_vals, fill_value=0).values
|
|
d_best = np.ones_like(map_vals) / len(map_vals)
|
|
|
|
error = np.abs(freqs - d_best) ** p * (freqs < d_best) * weights
|
|
imb_ratio = round(np.sum(error[weights > 0]) / np.sum(d_best * weights), 4) * 100
|
|
if np.isnan(imb_ratio):
|
|
imb_ratio = 100
|
|
|
|
if plot:
|
|
df_plot = pd.DataFrame({
|
|
'map': list(map_vals) * 2,
|
|
'freq': list(freqs) + list(d_best),
|
|
'dist': ['Emp'] * len(map_vals) + ['Uni'] * len(map_vals)
|
|
})
|
|
plt.figure(figsize=(10, 5))
|
|
for label, group in df_plot.groupby('dist'):
|
|
plt.bar(group['map'], group['freq'], alpha=0.5, label=label)
|
|
plt.title(f"{imb_ratio:.2f}%", fontsize=16, color='darkred')
|
|
plt.xlabel("Target values")
|
|
plt.ylabel("Frequency")
|
|
plt.legend()
|
|
if save:
|
|
plt.savefig(f"{rep}imbMetric_mass_{k}.png", bbox_inches='tight')
|
|
plt.show()
|
|
|
|
return imb_ratio
|
|
|
|
return None
|
|
|