#ml #classification #imblance #generation #synthetic #controlled #calibration
АНОНС
Работа с синтетическими данными - контролируемый эксперимент, позволяющий проникнуть мыслью в глубины DS процесса. У меня и раньше возникали подозрения, что общепринятые метрики оценки качества классификации в условиях дисбаланса классов нехороши. Сегодня я подкрепляю эти соображения численными экспериментами и предлагаю метрику классификации, хорошо дискриминирующую качественные модели от никчёмных, в том числе при несбалансированных классах и даже при слабой принципиальной прогнозируемости (например, когда львиная доля влияния на таргет осуществляется недоступными для наблюдения факторами из неизвестного домена).
АНОНС
Работа с синтетическими данными - контролируемый эксперимент, позволяющий проникнуть мыслью в глубины DS процесса. У меня и раньше возникали подозрения, что общепринятые метрики оценки качества классификации в условиях дисбаланса классов нехороши. Сегодня я подкрепляю эти соображения численными экспериментами и предлагаю метрику классификации, хорошо дискриминирующую качественные модели от никчёмных, в том числе при несбалансированных классах и даже при слабой принципиальной прогнозируемости (например, когда львиная доля влияния на таргет осуществляется недоступными для наблюдения факторами из неизвестного домена).
✍2💅1
#ml #classification #imblance #generation #synthetic #controlled #calibration
In this article I’d like to share with you my findings about inconsistency of traditional ML metrics when it comes to imbalanced binary classification, and propose a superior metric from calibration domain that works well and possesses high discriminative power not only in cases of class imbalance, but also when the predictability itself is fundamentally weak (i.e., when factors most predictive to the target are unknown or not reachable, and everything we can hope is to explain at least some part of target’s variation with help of modelling).
https://medium.com/@fingoldo/why-rp-roc-auc-should-not-be-your-first-choice-metrics-for-classification-tasks-8ed516cec1ee
In this article I’d like to share with you my findings about inconsistency of traditional ML metrics when it comes to imbalanced binary classification, and propose a superior metric from calibration domain that works well and possesses high discriminative power not only in cases of class imbalance, but also when the predictability itself is fundamentally weak (i.e., when factors most predictive to the target are unknown or not reachable, and everything we can hope is to explain at least some part of target’s variation with help of modelling).
https://medium.com/@fingoldo/why-rp-roc-auc-should-not-be-your-first-choice-metrics-for-classification-tasks-8ed516cec1ee
Medium
Why PR/ROC AUC should NOT be your first choice metrics for classification tasks
In this article I’d like to share with you my findings about inconsistency of traditional ML metrics when it comes to imbalanced binary…
🔥1
#probabilities #outcomes #synthetic #calibration #decisionmaking #python
Зная вероятности событий, сгенерировать по ним возможные бинарные исходы тривиально. Проще всего сравнить вероятность со случайным числом из интервала [0;1], если число оказалось меньше исходной вероятности, записываем в исход 1, иначе 0.
Внезапно возникла обратная задача: мы знаем исходы (они взяты из реального процесса), но интересно, какие ground truth вероятности могли бы привести к таким исходам? Для чего это может понадобиться: я тестирую систему принятия решений по ML модели, и хочется понять границы возможностей такой связки для конкретной задачи. Допустим, нам удалось построить "идеальную" в вероятностном плане модель, т.е. прекрасно откалиброванную (раз она сказала в какие-то моменты, что вероятность положительного исхода 60%, то примерно в 60% случаев такой исход и случился) - чего тогда можно ожидать от неё в плане онлайн метрик? Понятно, что получить такую модель сложно, часто и невозможно, но нам же хочется знать, каких результатов вообще возможно достичь?
И вот тут оказалось сложнее, чем кажется. Попробуйте поставит текст на паузу и предложить решение )
На удивление, ИИ в лице Чат ГПТ оказался совершенно бессилен, и пришлось думать. (Если сможете получить от него ответ, напишите.)
@njit ()
def generate_probs_from_outcomes(
outcomes: np.ndarray, chunk_size: int = 20, scale: float = 0.1, nbins: int = 10, bins_std: float = 0.1, flip_percent: float = 0.6
) -> np.ndarray:
"""Can we generate hypothetical ground truth probs knowing the outcomes in advance?
Our model probs will (hopefully) be calibrated. So, we need synthetic probs to be calibrated, too. With some degree of fitness.
We also need to cover broad range of probs.
So, how to achieve this?
0) if flip_percent is specified, for a random portion of data zeroes and ones are flipped. this will lower ROC AUC.
1) we can work with small random chunks/subsets of data
2) for every chunk, its real freq is computed.
3) for every observation, 'exact' prob is drawn from some distribution (uniform or, say, gaussian) with center in real freq.
then, if bins_std is specified, constant bin noise is applied to all observations of the chunk.
final result is clipped to [0,1]
"""
n = len(outcomes)
indices = np.arange(n)
np.random.shuffle(indices)
probs = np.empty(n, dtype=np.float32)
bin_offsets = (np.random.random(size=nbins) - 0.5) * bins_std
if flip_percent:
# flip some bits to worsen our so far perfect predictive power
flip_size = int(n * flip_percent)
if flip_size:
outcomes = outcomes.copy()
flip_indices = np.random.choice(indices, size=flip_size)
outcomes[flip_indices] = 1 - outcomes[flip_indices]
l = 0 # left border
for idx in range(n // chunk_size): # traverse randomly selected chunks/subsets of original data
r = (idx + 1) * chunk_size # right border
freq = outcomes[l:r].mean() # find real event occuring frequency in current chunk of observation
# add pregenerated offset for particular bin
bin_idx = int(freq * nbins)
freq = freq + bin_offsets[bin_idx]
# add small symmetric random noise. it must be higher when freq approaches [0;1] borders.
probs[l:r] = freq + (np.random.random(size=chunk_size) - 0.5) * scale * np.abs(freq - 0.5)
l = r
return np.clip(probs, 0.0, 1.0)
Зная вероятности событий, сгенерировать по ним возможные бинарные исходы тривиально. Проще всего сравнить вероятность со случайным числом из интервала [0;1], если число оказалось меньше исходной вероятности, записываем в исход 1, иначе 0.
Внезапно возникла обратная задача: мы знаем исходы (они взяты из реального процесса), но интересно, какие ground truth вероятности могли бы привести к таким исходам? Для чего это может понадобиться: я тестирую систему принятия решений по ML модели, и хочется понять границы возможностей такой связки для конкретной задачи. Допустим, нам удалось построить "идеальную" в вероятностном плане модель, т.е. прекрасно откалиброванную (раз она сказала в какие-то моменты, что вероятность положительного исхода 60%, то примерно в 60% случаев такой исход и случился) - чего тогда можно ожидать от неё в плане онлайн метрик? Понятно, что получить такую модель сложно, часто и невозможно, но нам же хочется знать, каких результатов вообще возможно достичь?
И вот тут оказалось сложнее, чем кажется. Попробуйте поставит текст на паузу и предложить решение )
def generate_probs_from_outcomes(
outcomes: np.ndarray, chunk_size: int = 20, scale: float = 0.1, nbins: int = 10, bins_std: float = 0.1, flip_percent: float = 0.6
) -> np.ndarray:
"""Can we generate hypothetical ground truth probs knowing the outcomes in advance?
Our model probs will (hopefully) be calibrated. So, we need synthetic probs to be calibrated, too. With some degree of fitness.
We also need to cover broad range of probs.
So, how to achieve this?
0) if flip_percent is specified, for a random portion of data zeroes and ones are flipped. this will lower ROC AUC.
1) we can work with small random chunks/subsets of data
2) for every chunk, its real freq is computed.
3) for every observation, 'exact' prob is drawn from some distribution (uniform or, say, gaussian) with center in real freq.
then, if bins_std is specified, constant bin noise is applied to all observations of the chunk.
final result is clipped to [0,1]
"""
n = len(outcomes)
indices = np.arange(n)
np.random.shuffle(indices)
probs = np.empty(n, dtype=np.float32)
bin_offsets = (np.random.random(size=nbins) - 0.5) * bins_std
if flip_percent:
# flip some bits to worsen our so far perfect predictive power
flip_size = int(n * flip_percent)
if flip_size:
outcomes = outcomes.copy()
flip_indices = np.random.choice(indices, size=flip_size)
outcomes[flip_indices] = 1 - outcomes[flip_indices]
l = 0 # left border
for idx in range(n // chunk_size): # traverse randomly selected chunks/subsets of original data
r = (idx + 1) * chunk_size # right border
freq = outcomes[l:r].mean() # find real event occuring frequency in current chunk of observation
# add pregenerated offset for particular bin
bin_idx = int(freq * nbins)
freq = freq + bin_offsets[bin_idx]
# add small symmetric random noise. it must be higher when freq approaches [0;1] borders.
probs[l:r] = freq + (np.random.random(size=chunk_size) - 0.5) * scale * np.abs(freq - 0.5)
l = r
return np.clip(probs, 0.0, 1.0)
#sklearn #imblanced #resampling #calibration
Этот Лемэтр зарубил много моих оптимизационных инициатив в sklearn, кстати.
Из новшеств: cost-sensitive learning, metadata routing. Английский докладчика понимается с трудом, но пытливый ум при желании разберётся )
https://www.youtube.com/watch?v=Gjrz4YCp6l8
Этот Лемэтр зарубил много моих оптимизационных инициатив в sklearn, кстати.
Из новшеств: cost-sensitive learning, metadata routing. Английский докладчика понимается с трудом, но пытливый ум при желании разберётся )
https://www.youtube.com/watch?v=Gjrz4YCp6l8
YouTube
Guillaume Lemaitre - Get the best from your scikit-learn classifier | PyData Global 2023
www.pydata.org
When operating a classifier in a production setting (i.e. predictive phase), practitioners are interested in potentially two different outputs: a "hard" decision used to leverage a business decision or/and a "soft" decision to get a confidence…
When operating a classifier in a production setting (i.e. predictive phase), practitioners are interested in potentially two different outputs: a "hard" decision used to leverage a business decision or/and a "soft" decision to get a confidence…
#pit #calibration #metrics
Как-то я совсем пропустил эту идею с PIT. Диаграммы рассеяния я постоянно использую, надо бы и PIT графики заценить.
Advantages of PIT over Binned Probabilities:
Continuous Assessment:
PIT uses the entire predicted distribution for each observation, providing a continuous view of calibration rather than relying on discretized bins.
This avoids issues with arbitrarily choosing bin edges or having too few samples per bin, which can bias binned reliability diagrams.
Higher Resolution:
PIT evaluates the full shape of the calibration, capturing subtle patterns in miscalibration that might be lost in coarse binning.
Better for Continuous Variables:
PIT is particularly advantageous for continuous outcomes (e.g., temperature, stock prices) where using bins can be challenging or lead to overly smoothed results.
Works Naturally for CDF Predictions:
If your model directly predicts cumulative probabilities (e.g., quantile regression or distributional models), PIT aligns naturally with this representation. Binned probabilities may not integrate smoothly with these types of predictions.
Uniform Distribution Diagnostic:
PIT values being uniformly distributed under perfect calibration provide a statistically robust test of calibration, allowing for formal hypothesis testing (e.g., Kolmogorov-Smirnov test or histogram-based goodness-of-fit tests).
Advantages of Binned Probabilities:
Intuitive Visualization:
Binned reliability diagrams are easier for non-experts to understand, as they directly show how predicted probabilities correspond to observed frequencies.
Focused on Predicted Probabilities:
These diagrams emphasize the calibration of specific probability ranges (e.g., "Does a predicted 70% chance event happen 70% of the time?"), which is useful for discrete probabilistic predictions like classification.
Handles Classification Tasks Well:
For binary classification tasks, binned probabilities are more direct and interpretable, especially when dealing with predicted probabilities rather than full distributions.
PS. Попробовал я эти PIT диаграммы, для классификаторов это вообще не подходит (
https://medium.com/@maltetichy/demystifying-the-probability-integral-transform-77b7de3a3af9
Как-то я совсем пропустил эту идею с PIT. Диаграммы рассеяния я постоянно использую, надо бы и PIT графики заценить.
The Probability Integral Transform (PIT) and binned reliability diagrams (e.g., plotting binned probabilities vs. real hit frequencies) are both tools for evaluating the calibration of probabilistic predictions, but they have distinct advantages and limitations:
Advantages of PIT over Binned Probabilities:
Continuous Assessment:
PIT uses the entire predicted distribution for each observation, providing a continuous view of calibration rather than relying on discretized bins.
This avoids issues with arbitrarily choosing bin edges or having too few samples per bin, which can bias binned reliability diagrams.
Higher Resolution:
PIT evaluates the full shape of the calibration, capturing subtle patterns in miscalibration that might be lost in coarse binning.
Better for Continuous Variables:
PIT is particularly advantageous for continuous outcomes (e.g., temperature, stock prices) where using bins can be challenging or lead to overly smoothed results.
Works Naturally for CDF Predictions:
If your model directly predicts cumulative probabilities (e.g., quantile regression or distributional models), PIT aligns naturally with this representation. Binned probabilities may not integrate smoothly with these types of predictions.
Uniform Distribution Diagnostic:
PIT values being uniformly distributed under perfect calibration provide a statistically robust test of calibration, allowing for formal hypothesis testing (e.g., Kolmogorov-Smirnov test or histogram-based goodness-of-fit tests).
Advantages of Binned Probabilities:
Intuitive Visualization:
Binned reliability diagrams are easier for non-experts to understand, as they directly show how predicted probabilities correspond to observed frequencies.
Focused on Predicted Probabilities:
These diagrams emphasize the calibration of specific probability ranges (e.g., "Does a predicted 70% chance event happen 70% of the time?"), which is useful for discrete probabilistic predictions like classification.
Handles Classification Tasks Well:
For binary classification tasks, binned probabilities are more direct and interpretable, especially when dealing with predicted probabilities rather than full distributions.
PS. Попробовал я эти PIT диаграммы, для классификаторов это вообще не подходит (
https://medium.com/@maltetichy/demystifying-the-probability-integral-transform-77b7de3a3af9
Medium
Demystifying the Probability Integral Transform
The Probability Integral Transform formalizes an intuitive and comprehensible approach to validating probabilistic predictions.
#news #calibration #teaser
В процессе написания небольшой статейки, мини-исследования о пользе посткалибрации бинарных классификаторов. По мере работы возникают всё новые вопросы, на которые хочется дать ответ 😅 Вначале был 1 датасет, 2 модели, 3 библиотеки, через день уже 5 моделей, еще через день добавился доп. датасет с "другим видом" мискалибрации (что, кстати, заметно изменило рейтинги), через день библиотек заюзанных в сравнении стало 7. Теперь вот хочется добавить к зоопарку и какую-то свою реализацию калибратора, а просто "шоб було".
В процессе написания небольшой статейки, мини-исследования о пользе посткалибрации бинарных классификаторов. По мере работы возникают всё новые вопросы, на которые хочется дать ответ 😅 Вначале был 1 датасет, 2 модели, 3 библиотеки, через день уже 5 моделей, еще через день добавился доп. датасет с "другим видом" мискалибрации (что, кстати, заметно изменило рейтинги), через день библиотек заюзанных в сравнении стало 7. Теперь вот хочется добавить к зоопарку и какую-то свою реализацию калибратора, а просто "шоб було".
#calibration #chainedlearning
Задумался, почему отдельное калибровочное множество помогает классификатору, даже если уже используется валидационное множество и ранняя остановка по "истиной скоринговой" метрике (типа логлосса).
Что удалось выжать из ИИ:
"Many ML models tend to produce poorly calibrated probabilities, often being overconfident.
Even if the larger validation set includes the same calibration data, training directly on it does not explicitly adjust probability estimates for better calibration.
A separate calibration step explicitly corrects systematic miscalibration, which improves probability-based metrics (e.g., log loss, Brier score, AUC in some cases).
Splitting into validation + calibration introduces an implicit regularization effect because:
The model's probability outputs on the validation set remain unchanged.
The calibration step learns an additional transformation to correct systematic biases, which is less likely to overfit than if the model had seen all the data at once.
If you train a calibration model (like isotonic regression) on all validation data at once, it could overfit the calibration mapping and be less effective OOS.
Standard model training optimizes classification accuracy (e.g., cross-entropy loss) but does not directly optimize for probability calibration.
Calibration methods, on the other hand, explicitly adjust probability distributions to minimize metrics like Brier loss or expected calibration error (ECE).
This difference means that models that look equally good on raw validation metrics may behave differently after calibration.
By calibrating on a held-out subset, you're reducing variance in probability estimates.
This smoothing effect makes your probability distributions more stable and generalizable OOS."
- Так погодите, значит ли это, что можно накидать ещё пару цепочек полезных трансформаций, и это сработает лучше, чем одна общая?
-Да, в этом есть смысл! Если калибровка работает как дополнительный корректирующий слой, то можно применить аналогичный подход для других полезных трансформаций. Это похоже на послойное обучение (layer-wise learning) или разделение функций оптимизации.
"Почему несколько отдельных трансформаций могут быть лучше, чем одна общая?
Разделение задач → Меньший риск переобучения
Основная модель учится находить основные паттерны в данных.
Дополнительные корректирующие трансформации (например, калибровка, устранение систематических ошибок) могут улучшать качество без риска переобучения всей модели.
В случае одной общей модели ей приходится одновременно решать обе задачи → это может привести к компромиссам.
Адаптация под разные аспекты ошибки
Например, можно отдельно:
Устранить систематический сдвиг (bias correction).
Отрегулировать масштаб предсказаний (variance correction).
Откалибровать доверительные интервалы (quantile adjustment).
Каждая такая трансформация исправляет конкретный тип ошибки, а не пытается все исправить разом.
Влияние на обобщающую способность
Когда модель учится сразу на всём датасете, она может подстраиваться под шум и переобучаться.
Если разбить процесс на несколько последовательных этапов, это добавляет эффект регуляризации.
Как это применить на практике?
Основная модель → предсказывает сырые вероятности.
Калибровка (Platt scaling, isotonic regression) → исправляет систематические ошибки.
Дополнительная модель может корректировать редкие случаи (например, сильно несбалансированные классы)."
Задумался, почему отдельное калибровочное множество помогает классификатору, даже если уже используется валидационное множество и ранняя остановка по "истиной скоринговой" метрике (типа логлосса).
Что удалось выжать из ИИ:
"Many ML models tend to produce poorly calibrated probabilities, often being overconfident.
Even if the larger validation set includes the same calibration data, training directly on it does not explicitly adjust probability estimates for better calibration.
A separate calibration step explicitly corrects systematic miscalibration, which improves probability-based metrics (e.g., log loss, Brier score, AUC in some cases).
Splitting into validation + calibration introduces an implicit regularization effect because:
The model's probability outputs on the validation set remain unchanged.
The calibration step learns an additional transformation to correct systematic biases, which is less likely to overfit than if the model had seen all the data at once.
If you train a calibration model (like isotonic regression) on all validation data at once, it could overfit the calibration mapping and be less effective OOS.
Standard model training optimizes classification accuracy (e.g., cross-entropy loss) but does not directly optimize for probability calibration.
Calibration methods, on the other hand, explicitly adjust probability distributions to minimize metrics like Brier loss or expected calibration error (ECE).
This difference means that models that look equally good on raw validation metrics may behave differently after calibration.
By calibrating on a held-out subset, you're reducing variance in probability estimates.
This smoothing effect makes your probability distributions more stable and generalizable OOS."
- Так погодите, значит ли это, что можно накидать ещё пару цепочек полезных трансформаций, и это сработает лучше, чем одна общая?
-Да, в этом есть смысл! Если калибровка работает как дополнительный корректирующий слой, то можно применить аналогичный подход для других полезных трансформаций. Это похоже на послойное обучение (layer-wise learning) или разделение функций оптимизации.
"Почему несколько отдельных трансформаций могут быть лучше, чем одна общая?
Разделение задач → Меньший риск переобучения
Основная модель учится находить основные паттерны в данных.
Дополнительные корректирующие трансформации (например, калибровка, устранение систематических ошибок) могут улучшать качество без риска переобучения всей модели.
В случае одной общей модели ей приходится одновременно решать обе задачи → это может привести к компромиссам.
Адаптация под разные аспекты ошибки
Например, можно отдельно:
Устранить систематический сдвиг (bias correction).
Отрегулировать масштаб предсказаний (variance correction).
Откалибровать доверительные интервалы (quantile adjustment).
Каждая такая трансформация исправляет конкретный тип ошибки, а не пытается все исправить разом.
Влияние на обобщающую способность
Когда модель учится сразу на всём датасете, она может подстраиваться под шум и переобучаться.
Если разбить процесс на несколько последовательных этапов, это добавляет эффект регуляризации.
Как это применить на практике?
Основная модель → предсказывает сырые вероятности.
Калибровка (Platt scaling, isotonic regression) → исправляет систематические ошибки.
Дополнительная модель может корректировать редкие случаи (например, сильно несбалансированные классы)."
#calibration #regression
Ну хорошо, двигаемся дальше, нельзя ли эту логику обобщить на регрессию? Электронный болван согласен.
Yes! The same logic that makes post-calibration beneficial for binary classification can also be applied to regression tasks—though it is rarely discussed. Here’s why post-calibration can be valuable for regression and how it can be implemented effectively.
Why Would Regression Benefit from Post-Calibration?
Regression models output continuous values, but just like classification models, they can suffer from systematic miscalibration in their predictions. The key idea is that a model’s predicted values might be biased or have the wrong spread compared to the actual target distribution.
There are two main ways a regression model can be miscalibrated:
Mean Shift (Bias)
The model’s predictions systematically overestimate or underestimate the true values.
Example: A house price prediction model always underestimates expensive houses.
Spread Distortion (Misestimated Variance)
The model’s predictions have the wrong level of dispersion:
Too narrow → Underestimated uncertainty (overconfident)
Too wide → Overestimated uncertainty (underconfident)
Example: A temperature prediction model might always predict values within ±2°C, even when actual deviations are much larger.
How to Perform Post-Calibration in Regression?
Instead of calibrating probabilities like in classification, you adjust the magnitude and distribution of the predicted values in regression. This can be done in a few ways:
1. Post-hoc Mean Correction (Bias Calibration)
Take a held-out calibration set (separate from validation).
Compute the difference between the predicted and actual values.
Fit a simple correction model (e.g., linear regression) to adjust the predictions.
This works like Platt scaling in classification but for correcting systematic bias.
2. Quantile Regression Calibration (Fixing Spread)
Instead of just predicting the mean, we fit a secondary model to predict quantiles (e.g., 10th, 50th, 90th percentile).
This helps in cases where the model’s uncertainty is wrong.
Ну хорошо, двигаемся дальше, нельзя ли эту логику обобщить на регрессию? Электронный болван согласен.
Yes! The same logic that makes post-calibration beneficial for binary classification can also be applied to regression tasks—though it is rarely discussed. Here’s why post-calibration can be valuable for regression and how it can be implemented effectively.
Why Would Regression Benefit from Post-Calibration?
Regression models output continuous values, but just like classification models, they can suffer from systematic miscalibration in their predictions. The key idea is that a model’s predicted values might be biased or have the wrong spread compared to the actual target distribution.
There are two main ways a regression model can be miscalibrated:
Mean Shift (Bias)
The model’s predictions systematically overestimate or underestimate the true values.
Example: A house price prediction model always underestimates expensive houses.
Spread Distortion (Misestimated Variance)
The model’s predictions have the wrong level of dispersion:
Too narrow → Underestimated uncertainty (overconfident)
Too wide → Overestimated uncertainty (underconfident)
Example: A temperature prediction model might always predict values within ±2°C, even when actual deviations are much larger.
How to Perform Post-Calibration in Regression?
Instead of calibrating probabilities like in classification, you adjust the magnitude and distribution of the predicted values in regression. This can be done in a few ways:
1. Post-hoc Mean Correction (Bias Calibration)
Take a held-out calibration set (separate from validation).
Compute the difference between the predicted and actual values.
Fit a simple correction model (e.g., linear regression) to adjust the predictions.
This works like Platt scaling in classification but for correcting systematic bias.
2. Quantile Regression Calibration (Fixing Spread)
Instead of just predicting the mean, we fit a secondary model to predict quantiles (e.g., 10th, 50th, 90th percentile).
This helps in cases where the model’s uncertainty is wrong.