File size: 5,379 Bytes
1a31610 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 |
"""
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', # 'cont' for continuous, 'dis' for discrete
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':
# Continuous target
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)
# Weight setup
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':
# Discrete target
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
|