#masters #ensembling #localaccuracy
Ещё одна оригинальная техника ансамблирования, с названием "по локальной точности". Для каждого экземпляра при выдаче прогноза участвует только одна из моделей ансамбля - "наиболее компетентная локально". в обучающем наборе ищется N (например, 10) примеров, наиболее похожих на прогнозный (по расстоянию в метрическом пространстве - например, евклидовом). Точность каждой модели ансамбля рассчитывается "локально" на этих N примерах, ответ позволяется дать победившей модели.
Ещё одна оригинальная техника ансамблирования, с названием "по локальной точности". Для каждого экземпляра при выдаче прогноза участвует только одна из моделей ансамбля - "наиболее компетентная локально". в обучающем наборе ищется N (например, 10) примеров, наиболее похожих на прогнозный (по расстоянию в метрическом пространстве - например, евклидовом). Точность каждой модели ансамбля рассчитывается "локально" на этих N примерах, ответ позволяется дать победившей модели.
#ensembling #optimization #scipy
"Machine learning practitioners rely on ensembles to improve the performance of their model. One of the methods used for ensembling multiple models is to calculate the weighted average of their predictions. The problem that rises is how to find the weights that will give us the best ensemble. In this post, I will explain how to optimize those weights using scipy."
https://guillaume-martin.github.io/average-ensemble-optimization.html
"Machine learning practitioners rely on ensembles to improve the performance of their model. One of the methods used for ensembling multiple models is to calculate the weighted average of their predictions. The problem that rises is how to find the weights that will give us the best ensemble. In this post, I will explain how to optimize those weights using scipy."
https://guillaume-martin.github.io/average-ensemble-optimization.html
Guillaume Martin
Average ensemble optimization
How to find the best weights to use in a weighted average ensemble.
#ensembling #confidence
Крайне удивительное открытие, как всегда, делюсь ценной информацией с читателями моего блога, которые хотят профессионально вырасти в ML/DS.
Исследую методы ансамблирования от простого усреднения до стэкинга, часто вижу ситуации когда ансамблирование не улучшает качество прогнозов out-of-sample (OOS).
(В случае со стэкингом метамодель просто почти сразу срывается в оверфит, это тема отдельного исследования).
Но посетила светлая мысль, мол, погоди выбрасывать ансамбли, хоть они и не улучшают метрики OOS в целом, так может, давай отдельно проверим точки/инстансы, в которых прогнозы моделей совпадают? Это ж будет значить повышенную надёжность именно этих конкретных прогнозов, раз много экспертов по ним имеют консенсус, правда?
Проверяю: считаем средние и скв. отклонения модельных прогнозов по точкам (они же инстансы/строки/примеры). Затем считаем надёжными предсказания, где среднеквадратичные отклонения прогнозов (можно их нормировать дополнительно на сами средние, у меня это картины не поменяло) меньше заданного порога, ну или находятся в своём первом дециле, к примеру. Отдельно считаем OOS метрики по этим "надёжным предсказаниям".
И вот тут как раз неожиданное открытие. По "надёжным предсказаниям" метрики хуже, а по остальной части - лучше!!
То есть, если эксперты дают разброс по некоторым точкам, их усреднению можно доверять больше, чем если бы их прогнозы совпадали. Парадокс? Для меня да. Работает на практике? Тоже да.
PS. Возможно, это лишь на конкретной задаче, нужно более широкое тестирование.
Крайне удивительное открытие, как всегда, делюсь ценной информацией с читателями моего блога, которые хотят профессионально вырасти в ML/DS.
Исследую методы ансамблирования от простого усреднения до стэкинга, часто вижу ситуации когда ансамблирование не улучшает качество прогнозов out-of-sample (OOS).
(В случае со стэкингом метамодель просто почти сразу срывается в оверфит, это тема отдельного исследования).
Но посетила светлая мысль, мол, погоди выбрасывать ансамбли, хоть они и не улучшают метрики OOS в целом, так может, давай отдельно проверим точки/инстансы, в которых прогнозы моделей совпадают? Это ж будет значить повышенную надёжность именно этих конкретных прогнозов, раз много экспертов по ним имеют консенсус, правда?
Проверяю: считаем средние и скв. отклонения модельных прогнозов по точкам (они же инстансы/строки/примеры). Затем считаем надёжными предсказания, где среднеквадратичные отклонения прогнозов (можно их нормировать дополнительно на сами средние, у меня это картины не поменяло) меньше заданного порога, ну или находятся в своём первом дециле, к примеру. Отдельно считаем OOS метрики по этим "надёжным предсказаниям".
И вот тут как раз неожиданное открытие. По "надёжным предсказаниям" метрики хуже, а по остальной части - лучше!!
То есть, если эксперты дают разброс по некоторым точкам, их усреднению можно доверять больше, чем если бы их прогнозы совпадали. Парадокс? Для меня да. Работает на практике? Тоже да.
PS. Возможно, это лишь на конкретной задаче, нужно более широкое тестирование.
👍2🔥1🤔1
#ensembling #cv
Поржал с The Fuck-It Approach. На русский можно, наверное, перевести как ДебОК-метод.
https://mindfulmodeler.substack.com/p/how-to-get-from-evaluation-to-final
Поржал с The Fuck-It Approach. На русский можно, наверное, перевести как ДебОК-метод.
https://mindfulmodeler.substack.com/p/how-to-get-from-evaluation-to-final
Mindful Modeler
How to get from evaluation to final model
We’ve all been there: You’ve set up a machine learning pipeline with tuning, model selection, and evaluation.
#llms #ai #gpt #math #ensembling #diversity
Недавно на ютубе смотрел видео о применении компьютера (в частности, языка Julia для исследования проблемы 196), спросил в комментах математика (явно советской школы), который написал статью по модификации проблемы, не пробовал ли он ИИ для генерации кода, да и вообще обкатки идей, на что получил кажущийся высокомерным ответ, мол, этот ваш ИИ слишком слаб для моих задач. Повеяло Сурдиным, в общем ) Я такой думаю, да что ж вы за гиганты мысли такие, что он для вас слаб и неточен, я вот прекрасно с ним работаю и оочень доволен. А вот и пример.
Q.: Suppose i'm running HPT/HPO for some model on a particular dataset, and I plan to later use more than one HP combinations to form an ensemble. Now, am I looking for HPs producing un-correlated predictions (zero MI), or anti-correlated predictions (corrcoeff=-1)?
A.: You're looking for hyperparameter (HP) combinations that produce uncorrelated predictions (zero mutual information, MI ≈ 0) rather than strictly anti-correlated ones (corrcoeff=−1).
Why uncorrelated predictions?
Ensemble Diversity: The key to a strong ensemble is combining diverse but individually strong models. If two models are perfectly anti-correlated (ρ=−1), their predictions will cancel each other out when averaged, leading to little to no improvement.
Reduction in Variance: The goal of an ensemble is to reduce variance and improve generalization. If the models are uncorrelated, they make different kinds of errors, so their combination will smooth out those errors.
Avoiding Overcompensation: A correlation of −1 means that one model's overestimation is exactly another model's underestimation, which could lead to instability in the ensemble.
How to achieve this?
Optimize for performance first: Choose hyperparameters that result in good individual models.
Select diverse models: Instead of maximizing anti-correlation, look for models that make errors in different places (measured by MI or correlation).
Use decorrelation techniques: Cluster models based on prediction similarity and pick those with the lowest pairwise correlation.
In short, low correlation (not necessarily negative) is desirable, but enforcing perfect anti-correlation is counterproductive.
Вот эта интересная идея, о которой я и не подумал, Cluster models based on prediction similarity and pick those with the lowest pairwise correlation. А ведь интересная визуализация может получиться. Хоть какое-то реальное применение для unsupervised ML 😅
Q.: What are other practical means to look for models that make errors in different places, except MI?
A.: Aside from mutual information (MI), there are several practical ways to identify models that make errors in different places when forming an ensemble:
Disagreement Rate (Prediction Diversity Index)
For classification, measure how often two models make different predictions on the same data points.
Higher values indicate greater diversity.
Jaccard Similarity for Misclassified Samples
Compute the Jaccard index for misclassified examples between two models:
Lower values mean models make mistakes on different samples.
Double-Fold Cross-Validation Differences
Train models on different folds and analyze how much their predictions differ on holdout sets.
If a model performs well on Fold 1 but poorly on Fold 2, and another model shows the opposite behavior, they might complement each other.
Shapley Value or Feature Importance Differences
Compare the features each model relies on using SHAP, permutation importance, or Gini importance.
If two models prioritize different features, they likely capture different aspects of the data.
Orthogonality of Prediction Vectors (in High-Dimensional Spaces)
Compute cosine similarity between prediction vectors:
Lower cosine similarity implies more independent predictions.
Недавно на ютубе смотрел видео о применении компьютера (в частности, языка Julia для исследования проблемы 196), спросил в комментах математика (явно советской школы), который написал статью по модификации проблемы, не пробовал ли он ИИ для генерации кода, да и вообще обкатки идей, на что получил кажущийся высокомерным ответ, мол, этот ваш ИИ слишком слаб для моих задач. Повеяло Сурдиным, в общем ) Я такой думаю, да что ж вы за гиганты мысли такие, что он для вас слаб и неточен, я вот прекрасно с ним работаю и оочень доволен. А вот и пример.
Q.: Suppose i'm running HPT/HPO for some model on a particular dataset, and I plan to later use more than one HP combinations to form an ensemble. Now, am I looking for HPs producing un-correlated predictions (zero MI), or anti-correlated predictions (corrcoeff=-1)?
A.: You're looking for hyperparameter (HP) combinations that produce uncorrelated predictions (zero mutual information, MI ≈ 0) rather than strictly anti-correlated ones (corrcoeff=−1).
Why uncorrelated predictions?
Ensemble Diversity: The key to a strong ensemble is combining diverse but individually strong models. If two models are perfectly anti-correlated (ρ=−1), their predictions will cancel each other out when averaged, leading to little to no improvement.
Reduction in Variance: The goal of an ensemble is to reduce variance and improve generalization. If the models are uncorrelated, they make different kinds of errors, so their combination will smooth out those errors.
Avoiding Overcompensation: A correlation of −1 means that one model's overestimation is exactly another model's underestimation, which could lead to instability in the ensemble.
How to achieve this?
Optimize for performance first: Choose hyperparameters that result in good individual models.
Select diverse models: Instead of maximizing anti-correlation, look for models that make errors in different places (measured by MI or correlation).
Use decorrelation techniques: Cluster models based on prediction similarity and pick those with the lowest pairwise correlation.
In short, low correlation (not necessarily negative) is desirable, but enforcing perfect anti-correlation is counterproductive.
Вот эта интересная идея, о которой я и не подумал, Cluster models based on prediction similarity and pick those with the lowest pairwise correlation. А ведь интересная визуализация может получиться. Хоть какое-то реальное применение для unsupervised ML 😅
Q.: What are other practical means to look for models that make errors in different places, except MI?
A.: Aside from mutual information (MI), there are several practical ways to identify models that make errors in different places when forming an ensemble:
Disagreement Rate (Prediction Diversity Index)
For classification, measure how often two models make different predictions on the same data points.
Higher values indicate greater diversity.
Jaccard Similarity for Misclassified Samples
Compute the Jaccard index for misclassified examples between two models:
Lower values mean models make mistakes on different samples.
Double-Fold Cross-Validation Differences
Train models on different folds and analyze how much their predictions differ on holdout sets.
If a model performs well on Fold 1 but poorly on Fold 2, and another model shows the opposite behavior, they might complement each other.
Shapley Value or Feature Importance Differences
Compare the features each model relies on using SHAP, permutation importance, or Gini importance.
If two models prioritize different features, they likely capture different aspects of the data.
Orthogonality of Prediction Vectors (in High-Dimensional Spaces)
Compute cosine similarity between prediction vectors:
Lower cosine similarity implies more independent predictions.
Wikipedia
Проблема 196
условное название нерешённой математической задачи
✍2
Aspiring Data Science
#hpo #hpt #metalearning #books Пересмотрев доклад, стал искать упомянутую книжку "Automated Machine Learning - Methods, Systems, Challenges". Она оказалась в свободном доступе, по виду хорошая, изучаю. Наугад полистал этот сайт на предмет интересной литературы…
#ensembling #cascading #delegating #arbitrating
Читаю "Metalearning - Applications to Automated Machine Learning and Data Mining". В главе про ансамбли с удивлением обнаружил весьма интересные алгоритмы.
1. Cascade Generalization
Cascade generalization is a type of stacked ensembling where models are arranged in a sequential, layered fashion. Predictions from earlier layers become additional features for models in later layers. Unlike traditional stacking, cascade generalization emphasizes using higher-level models to refine or augment lower-level predictions.
Key idea: Each layer’s models pass their predictions as additional inputs to models in the next layer.
Advantage: Can iteratively refine weak models, allowing later models to correct errors made earlier.
Example: A first-layer model predicts probabilities, and a second-layer model uses those probabilities along with the original features to make the final decision.
2. Cascading
Cascading refers to a progressive model selection strategy where simpler (cheaper) models are used first, and only ambiguous cases are passed to more complex (expensive) models.
Key idea: Reduce computational cost by filtering easy cases early.
Example: A decision tree quickly filters obvious negative cases, and only uncertain cases are sent to a more sophisticated deep learning model.
3. Delegating (or Selective Routing)
Delegating is a framework where multiple models exist, and an intelligent mechanism decides which model should handle each instance. This is also known as an expert selection approach.
Key idea: Different models specialize in different regions of the feature space, and a routing function determines which model should process a given input.
Example: In fraud detection, a rule-based system handles typical transactions, while an anomaly detection model analyzes suspicious ones.
4. Arbitrating
Arbitrating is a meta-learning approach where an additional model (arbitrator) decides which base model’s prediction to trust more. Unlike delegation, where models specialize in different regions, arbitration combines predictions but gives more weight to the most confident model.
Key idea: Instead of picking a single expert, the arbitrator dynamically adjusts confidence in different models.
Example: A reinforcement learning agent (arbitrator) learns which base model performs best in specific scenarios.
5. Meta-Decision Trees (MDTs)
Meta-decision trees (MDTs) are decision trees that learn when to trust each base model in an ensemble, instead of directly predicting the target.
Key idea: The decision tree’s leaves represent which model should be used for a given input, rather than the final prediction itself.
Advantage: Unlike traditional stacking, it explicitly learns a strategy for model selection.
Example: An MDT may learn that Model A performs best for low-income customers, while Model B works better for high-income customers.
Ещё Мастерс писал о чём-то, подобном Arbitrating, когда модели могут специализироваться в разных регионах области определения. Открытых реализаций в Питоне найти не смог навскидку.
Читаю "Metalearning - Applications to Automated Machine Learning and Data Mining". В главе про ансамбли с удивлением обнаружил весьма интересные алгоритмы.
1. Cascade Generalization
Cascade generalization is a type of stacked ensembling where models are arranged in a sequential, layered fashion. Predictions from earlier layers become additional features for models in later layers. Unlike traditional stacking, cascade generalization emphasizes using higher-level models to refine or augment lower-level predictions.
Key idea: Each layer’s models pass their predictions as additional inputs to models in the next layer.
Advantage: Can iteratively refine weak models, allowing later models to correct errors made earlier.
Example: A first-layer model predicts probabilities, and a second-layer model uses those probabilities along with the original features to make the final decision.
2. Cascading
Cascading refers to a progressive model selection strategy where simpler (cheaper) models are used first, and only ambiguous cases are passed to more complex (expensive) models.
Key idea: Reduce computational cost by filtering easy cases early.
Example: A decision tree quickly filters obvious negative cases, and only uncertain cases are sent to a more sophisticated deep learning model.
3. Delegating (or Selective Routing)
Delegating is a framework where multiple models exist, and an intelligent mechanism decides which model should handle each instance. This is also known as an expert selection approach.
Key idea: Different models specialize in different regions of the feature space, and a routing function determines which model should process a given input.
Example: In fraud detection, a rule-based system handles typical transactions, while an anomaly detection model analyzes suspicious ones.
4. Arbitrating
Arbitrating is a meta-learning approach where an additional model (arbitrator) decides which base model’s prediction to trust more. Unlike delegation, where models specialize in different regions, arbitration combines predictions but gives more weight to the most confident model.
Key idea: Instead of picking a single expert, the arbitrator dynamically adjusts confidence in different models.
Example: A reinforcement learning agent (arbitrator) learns which base model performs best in specific scenarios.
5. Meta-Decision Trees (MDTs)
Meta-decision trees (MDTs) are decision trees that learn when to trust each base model in an ensemble, instead of directly predicting the target.
Key idea: The decision tree’s leaves represent which model should be used for a given input, rather than the final prediction itself.
Advantage: Unlike traditional stacking, it explicitly learns a strategy for model selection.
Example: An MDT may learn that Model A performs best for low-income customers, while Model B works better for high-income customers.
Ещё Мастерс писал о чём-то, подобном Arbitrating, когда модели могут специализироваться в разных регионах области определения. Открытых реализаций в Питоне найти не смог навскидку.
🤔1
#ensembling #hpo #hpt #autosklearn
Вот какой интересный метод ансамблирования опробовали авторы оптимизатора auto-sklearn:
"Two important problems in AutoML are that (1) no single machine learning method performs best on all datasets and (2) some machine learning methods (e.g., non-linear SVMs) crucially rely on hyperparameter optimization.
While Bayesian hyperparameter optimization is data-efficient in finding the bestperforming hyperparameter setting, we note that it is a very wasteful procedure when the goal is simply to make good predictions: all the models it trains during the course of the search are lost, usually including some that perform almost as well as the best.
Rather than discarding these models, we propose to store them and to use an efficient post-processing method (which can be run in a second process on-the-fly) to construct an ensemble out of them. This automatic ensemble
construction avoids to commit itself to a single hyperparameter setting and is thus more robust (and less prone to overfitting) than using the point estimate that standard hyperparameter optimization yields. To our best knowledge, we are the first to make this simple observation, which can be applied to improve any Bayesian hyperparameter optimization method.
It is well known that ensembles often outperform individual models [24, 31], and that effective ensembles can be created from a library of models [9, 10]. Ensembles perform particularly well if the models they are based on (1) are individually strong and (2) make uncorrelated errors [6]. Since this is much more likely when the individual models are different in nature, ensemble building is particularly well suited for combining strong instantiations of a flexible ML framework.
However, simply building a uniformly weighted ensemble of the models found by Bayesian optimization does not work well. Rather, we found it crucial to adjust these weights using the predictions of all individual models on a hold-out set. We experimented with different approaches to optimize these weights: stacking [44], gradient-free numerical optimization, and the method ensemble selection [10].
While we found both numerical optimization and stacking to overfit to the validation set and to be computationally costly, ensemble selection was fast and robust . In a nutshell, ensemble selection (introduced by Caruana et al. [10]) is a greedy procedure that starts from an empty ensemble and then iteratively adds the model that minimizes ensemble validation loss (with uniform weight, but allowing for repetitions). We used this technique in all our experiments—building an ensemble of size 50 using selection with replacement [10]. We calculated the ensemble loss using the same validation set that we use for Bayesian optimization."
Вот какой интересный метод ансамблирования опробовали авторы оптимизатора auto-sklearn:
"Two important problems in AutoML are that (1) no single machine learning method performs best on all datasets and (2) some machine learning methods (e.g., non-linear SVMs) crucially rely on hyperparameter optimization.
While Bayesian hyperparameter optimization is data-efficient in finding the bestperforming hyperparameter setting, we note that it is a very wasteful procedure when the goal is simply to make good predictions: all the models it trains during the course of the search are lost, usually including some that perform almost as well as the best.
Rather than discarding these models, we propose to store them and to use an efficient post-processing method (which can be run in a second process on-the-fly) to construct an ensemble out of them. This automatic ensemble
construction avoids to commit itself to a single hyperparameter setting and is thus more robust (and less prone to overfitting) than using the point estimate that standard hyperparameter optimization yields. To our best knowledge, we are the first to make this simple observation, which can be applied to improve any Bayesian hyperparameter optimization method.
It is well known that ensembles often outperform individual models [24, 31], and that effective ensembles can be created from a library of models [9, 10]. Ensembles perform particularly well if the models they are based on (1) are individually strong and (2) make uncorrelated errors [6]. Since this is much more likely when the individual models are different in nature, ensemble building is particularly well suited for combining strong instantiations of a flexible ML framework.
However, simply building a uniformly weighted ensemble of the models found by Bayesian optimization does not work well. Rather, we found it crucial to adjust these weights using the predictions of all individual models on a hold-out set. We experimented with different approaches to optimize these weights: stacking [44], gradient-free numerical optimization, and the method ensemble selection [10].
While we found both numerical optimization and stacking to overfit to the validation set and to be computationally costly, ensemble selection was fast and robust . In a nutshell, ensemble selection (introduced by Caruana et al. [10]) is a greedy procedure that starts from an empty ensemble and then iteratively adds the model that minimizes ensemble validation loss (with uniform weight, but allowing for repetitions). We used this technique in all our experiments—building an ensemble of size 50 using selection with replacement [10]. We calculated the ensemble loss using the same validation set that we use for Bayesian optimization."
#ensembling #featureselection #papers #todo
Ensemble Selection from Libraries of Models
Rich Caruana, Alexandru Niculescu-Mizil, Geoff Crew, Alex Ksikes
Простой метод ансамблирования 20-летней давности, возможно, незаслуженно обделённый вниманием. (Именно его авторы auto-sklearn отмаечают как превосходящий по качеству стэкинг.)
"We present a method for constructing ensembles from libraries of thousands of models. Model libraries are generated using different learning algorithms and parameter settings.
Forward stepwise selection is used to add to the ensemble the models that maximize its performance.
Ensemble selection allows ensembles to be optimized to performance metric such as accuracy, cross entropy, mean precision, or ROC Area. Experiments with seven test problems and ten metrics demonstrate the benefit of ensemble selection."
Что удивительно, есть прямая параллель между выбором "артистов" в ансамбль и ... просто выбором признаков в одиночную модель. Только, в отличие от последнего, качество ансамбля подсчитать можно очень быстро (это же усреднение предсказаний), не надо (пере)обучать потенциально медленную модель.
В статье использован жадный алгоритм выбора, когда на каждом шаге к ансамблю добавляется самый "перформящий" (совместно с уже выбранными) на валидации кандидат.
Находкой авторов, видимо, стоит считать выбор кандидатов с возвращением, когда вхождение модели в ансамбль может рассматриваться неоднократно, причём на разных этапах (эквивалент веса):
"Selection with replacement flattens the curve so much that a test set is not needed to determine when to stop adding models to the ensemble. The hillclimbing set can be used to stop hillclimbing. This means ensemble selection does not need more test sets than the base-level models would have used to select model parameters. Ensemble selection uses the validation set to do both parameter and model selection."
Что ещё очень интересно, для борьбы с оверфитом валидационного множества они вводят 50%-ный бэггинг моделей, но повторяют всю процедуру построения ансамбля 20 раз, так что итоговое решение - это среднее 20 ансамблей 🤪
Глядя на таблицу результатов, кажется, что стэкинг они реализовали неправильно, ну не может он быть таким плохим. Вот как они это объясняют:
"Stacking (Wolpert, 1992) with logistic regression performs poorly because regression overfits dramatically when there are 2000 highly correlated input models and only 1k points in the validation set."
Видимо, отсюда и проблемы, ведь стэкинг лучше делать на CV, а не на одном множестве.
Ко всей методологии сравнения у меня есть 1 большая претензия: похоже, что все тестовые множества были сгенерированы 1 раз. Ну не серьёзно. Я понимаю, что и так объём вычислений был большой, но... (
Тем не менее, главные результаты статьи в том, что ансамблирование байесовским усреднением моделей, и особенно прямым отбором моделей значительно лучше даже индивидуально самых лучших моделей.
Я постараюсь повторить это исследование в рамках создания своего тюнера Diogenes, с бОльшим количеством HP-шек на модель, более современными моделями, метриками включающими и "резкость" и калибрацию, бОльшим количеством альтернативных методов ансамблирования.
Интересно, а если полностью затюнить ансамбль сначала на одну, потом на другую метрику, получится ли улучшить обе, как обсуждалось ранее?
Попросил "размышляющие" версии AI проанализировать интересные аспекты и слабости статьи. Deepseek R1 справилась куда лучше OpenAI O3-mini. Gemini 2.0 жёстко галлюцинировала.
https://www.cs.cornell.edu/~alexn/papers/shotgun.icml04.revised.rev2.pdf
Ensemble Selection from Libraries of Models
Rich Caruana, Alexandru Niculescu-Mizil, Geoff Crew, Alex Ksikes
Простой метод ансамблирования 20-летней давности, возможно, незаслуженно обделённый вниманием. (Именно его авторы auto-sklearn отмаечают как превосходящий по качеству стэкинг.)
"We present a method for constructing ensembles from libraries of thousands of models. Model libraries are generated using different learning algorithms and parameter settings.
Forward stepwise selection is used to add to the ensemble the models that maximize its performance.
Ensemble selection allows ensembles to be optimized to performance metric such as accuracy, cross entropy, mean precision, or ROC Area. Experiments with seven test problems and ten metrics demonstrate the benefit of ensemble selection."
Что удивительно, есть прямая параллель между выбором "артистов" в ансамбль и ... просто выбором признаков в одиночную модель. Только, в отличие от последнего, качество ансамбля подсчитать можно очень быстро (это же усреднение предсказаний), не надо (пере)обучать потенциально медленную модель.
В статье использован жадный алгоритм выбора, когда на каждом шаге к ансамблю добавляется самый "перформящий" (совместно с уже выбранными) на валидации кандидат.
Находкой авторов, видимо, стоит считать выбор кандидатов с возвращением, когда вхождение модели в ансамбль может рассматриваться неоднократно, причём на разных этапах (эквивалент веса):
"Selection with replacement flattens the curve so much that a test set is not needed to determine when to stop adding models to the ensemble. The hillclimbing set can be used to stop hillclimbing. This means ensemble selection does not need more test sets than the base-level models would have used to select model parameters. Ensemble selection uses the validation set to do both parameter and model selection."
Что ещё очень интересно, для борьбы с оверфитом валидационного множества они вводят 50%-ный бэггинг моделей, но повторяют всю процедуру построения ансамбля 20 раз, так что итоговое решение - это среднее 20 ансамблей 🤪
Глядя на таблицу результатов, кажется, что стэкинг они реализовали неправильно, ну не может он быть таким плохим. Вот как они это объясняют:
"Stacking (Wolpert, 1992) with logistic regression performs poorly because regression overfits dramatically when there are 2000 highly correlated input models and only 1k points in the validation set."
Видимо, отсюда и проблемы, ведь стэкинг лучше делать на CV, а не на одном множестве.
Ко всей методологии сравнения у меня есть 1 большая претензия: похоже, что все тестовые множества были сгенерированы 1 раз. Ну не серьёзно. Я понимаю, что и так объём вычислений был большой, но... (
Тем не менее, главные результаты статьи в том, что ансамблирование байесовским усреднением моделей, и особенно прямым отбором моделей значительно лучше даже индивидуально самых лучших моделей.
Я постараюсь повторить это исследование в рамках создания своего тюнера Diogenes, с бОльшим количеством HP-шек на модель, более современными моделями, метриками включающими и "резкость" и калибрацию, бОльшим количеством альтернативных методов ансамблирования.
Интересно, а если полностью затюнить ансамбль сначала на одну, потом на другую метрику, получится ли улучшить обе, как обсуждалось ранее?
Попросил "размышляющие" версии AI проанализировать интересные аспекты и слабости статьи. Deepseek R1 справилась куда лучше OpenAI O3-mini. Gemini 2.0 жёстко галлюцинировала.
https://www.cs.cornell.edu/~alexn/papers/shotgun.icml04.revised.rev2.pdf
#ensembling #papers
Getting the Most Out of Ensemble Selection
Rich Caruana, Art Munson, Alexandru Niculescu-Mizil
Вторая часть исследования ансамблирования прямым отбором. Реализовали CV, проверили эффект пре-калибрации участников ансамбля, рапортуют о двукратном увеличении преимуществ метода.
Из интересных открытий:
"Ensemble selection’s ability to optimize to any performance metric is an attractive capability of the method that is particularly useful in domains which use non-traditional performance measures such as natural language processing [14]. Because of this, the third aspect we investigate is what benefit, if any, comes from being able to optimize to any metric. Our experiments reinforce the intuition that it is best to optimize to the target performance metric;however, they also show that minimizing squared error or cross-entropy frequently yields ensembles with competitive performance—seemingly regardless of the metric."
"Interestingly, ensemble selection is hurt less by a small hillclimbing set than model selection, suggesting that it is less prone to overfitting than model selection. Because of this, the benefit of ensemble selection over the best models appears to be strongest when training data is scarce."
Ещё более интересно, оказывается, выгодно смешивать в ансамбле "сырые" и калиброванные модели:
"Having both calibrated and uncalibrated models in the library (ES-BOTH and MODSEL-BOTH) gives the best of both worlds: it alleviates the problem with FSC while retaining the RMS and MXE improvements."
Есть и достаточно неожиданные выводы:
"We test ensemble selection’s performance when only the best X% models are available for selection. These experiments confirm our intuition that the potential for overfitting increases with more models. Using only the top 10-20% of the models yields performance better than or equivalent to ensemble selection without this model pruning."
"Unlike with ensemble selection, using calibrated models for Bayesian model averaging improves performance on all metrics, not just RMS and MXE (significant at .05). With calibrated models, Bayesian averaging outperforms model selection but is still not as good as ensemble selection."
Мухаха, кажется, я понял, почему они полезли в такие дебри проверять миксы калиброванных/некалиброванных моделей: байесовское усреднение обогнало авторский метод, и они went an extra mile выясняя, при каких же настройках их метод всё-таки лучше ))
"Not only does cross-validation greatly improve ensemble selection performance, it also provides the same benefit to model selection. Five-fold cross-validated model selection actually outperforms non-cross-validated ensemble selection by a small but noticeable amount. However, ensemble selection with embedded cross-validation continues to outperform model selection."
"Although performance starts to decline at different pruning levels for the different problems, it is clear that larger
model libraries increase the risk of overfitting the hillclimb set. Using 100% of the models is never worthwhile. At best, using the full library can match the performance of using only a small subset. In the worst case, ensemble selection overfits. This is particularly evident for the COD data set where model selection outperforms ensemble selection unless pruning is employed. While further work is needed to develop good heuristics for automatically choosing an appropriate pruning level for a data set, simply using the top 10–20% models seems to be a good rule of thumb. An open problem is finding a better pruning method. For example, taking into account model diversity (see for example [11, 17]) might find better pruned sets."
https://www.researchgate.net/publication/220766367_Getting_the_Most_Out_of_Ensemble_Selection
Getting the Most Out of Ensemble Selection
Rich Caruana, Art Munson, Alexandru Niculescu-Mizil
Вторая часть исследования ансамблирования прямым отбором. Реализовали CV, проверили эффект пре-калибрации участников ансамбля, рапортуют о двукратном увеличении преимуществ метода.
Из интересных открытий:
"Ensemble selection’s ability to optimize to any performance metric is an attractive capability of the method that is particularly useful in domains which use non-traditional performance measures such as natural language processing [14]. Because of this, the third aspect we investigate is what benefit, if any, comes from being able to optimize to any metric. Our experiments reinforce the intuition that it is best to optimize to the target performance metric;however, they also show that minimizing squared error or cross-entropy frequently yields ensembles with competitive performance—seemingly regardless of the metric."
"Interestingly, ensemble selection is hurt less by a small hillclimbing set than model selection, suggesting that it is less prone to overfitting than model selection. Because of this, the benefit of ensemble selection over the best models appears to be strongest when training data is scarce."
Ещё более интересно, оказывается, выгодно смешивать в ансамбле "сырые" и калиброванные модели:
"Having both calibrated and uncalibrated models in the library (ES-BOTH and MODSEL-BOTH) gives the best of both worlds: it alleviates the problem with FSC while retaining the RMS and MXE improvements."
Есть и достаточно неожиданные выводы:
"We test ensemble selection’s performance when only the best X% models are available for selection. These experiments confirm our intuition that the potential for overfitting increases with more models. Using only the top 10-20% of the models yields performance better than or equivalent to ensemble selection without this model pruning."
"Unlike with ensemble selection, using calibrated models for Bayesian model averaging improves performance on all metrics, not just RMS and MXE (significant at .05). With calibrated models, Bayesian averaging outperforms model selection but is still not as good as ensemble selection."
Мухаха, кажется, я понял, почему они полезли в такие дебри проверять миксы калиброванных/некалиброванных моделей: байесовское усреднение обогнало авторский метод, и они went an extra mile выясняя, при каких же настройках их метод всё-таки лучше ))
"Not only does cross-validation greatly improve ensemble selection performance, it also provides the same benefit to model selection. Five-fold cross-validated model selection actually outperforms non-cross-validated ensemble selection by a small but noticeable amount. However, ensemble selection with embedded cross-validation continues to outperform model selection."
"Although performance starts to decline at different pruning levels for the different problems, it is clear that larger
model libraries increase the risk of overfitting the hillclimb set. Using 100% of the models is never worthwhile. At best, using the full library can match the performance of using only a small subset. In the worst case, ensemble selection overfits. This is particularly evident for the COD data set where model selection outperforms ensemble selection unless pruning is employed. While further work is needed to develop good heuristics for automatically choosing an appropriate pruning level for a data set, simply using the top 10–20% models seems to be a good rule of thumb. An open problem is finding a better pruning method. For example, taking into account model diversity (see for example [11, 17]) might find better pruned sets."
https://www.researchgate.net/publication/220766367_Getting_the_Most_Out_of_Ensemble_Selection
ResearchGate
(PDF) Getting the Most Out of Ensemble Selection
PDF | We investigate four previously unexplored aspects of ensemble selection, a procedure for building ensembles of classifiers. First we test whether... | Find, read and cite all the research you need on ResearchGate
#books #kagglebook #ensembling
Ensembling
Ensemble of tuned models always performs better than an ensemble of untuned ones.
The logarithmic mean: Analogous to the geometric mean, you take the logarithm of your submission, average them together, and take the exponentiation of the resulting mean.
The mean of powers: Where you take the average of the nth power of the submissions, then you take the 1/nth power of the resulting average.
Giving more importance to more uncorrelated predictions is an ensembling strategy that is often successful. Even if it only provides slight improvements, this could suffice to turn the competition to your advantage.
In blending, the kind of meta-learner you use can make a great difference. The most common choices are to use a linear model or a non-linear one. One limit to using these kinds of meta-learners is that they may assign some models a negative contribution, as you will be able to see from the value of the coefficient in the model. When you encounter this situation, the model is usually overfitting, since all models should be contributing positively to the building of the ensemble (or, at worst, not contributing at all). The most recent versions of Scikit-learn allow you to impose only positive weights and to remove the intercept. These constraints act as a regularizer and prevent overfitting.
Non-linear models as meta-learners are less common because they tend to overfit in regression and binary classification problems, but they often shine in multiclass and multilabel classification problems since they can model the complex relationships between the classes present. They also generally perform better if, aside from the models’ predictions, you also provide them with the original features, since they can spot any useful interactions that help them correctly select which models to trust more.
Ensembling
Ensemble of tuned models always performs better than an ensemble of untuned ones.
The logarithmic mean: Analogous to the geometric mean, you take the logarithm of your submission, average them together, and take the exponentiation of the resulting mean.
The mean of powers: Where you take the average of the nth power of the submissions, then you take the 1/nth power of the resulting average.
Giving more importance to more uncorrelated predictions is an ensembling strategy that is often successful. Even if it only provides slight improvements, this could suffice to turn the competition to your advantage.
In blending, the kind of meta-learner you use can make a great difference. The most common choices are to use a linear model or a non-linear one. One limit to using these kinds of meta-learners is that they may assign some models a negative contribution, as you will be able to see from the value of the coefficient in the model. When you encounter this situation, the model is usually overfitting, since all models should be contributing positively to the building of the ensemble (or, at worst, not contributing at all). The most recent versions of Scikit-learn allow you to impose only positive weights and to remove the intercept. These constraints act as a regularizer and prevent overfitting.
Non-linear models as meta-learners are less common because they tend to overfit in regression and binary classification problems, but they often shine in multiclass and multilabel classification problems since they can model the complex relationships between the classes present. They also generally perform better if, aside from the models’ predictions, you also provide them with the original features, since they can spot any useful interactions that help them correctly select which models to trust more.
✍1
#books #kagglebook #ensembling
Ensembling
An alternative to using a linear or non-linear model as a meta-learner is provided by the ensemble selection technique formalized by Caruana, Niculescu-Mizil, Crew, and Ksikes. (Мы уже обсуждали этот метод не так давно)
The ensemble selection is actually a weighted average, so it could simply be considered analogous to a linear combination. However, it is a constrained linear combination (because it is part of a hill-climbing optimization) that will also make a selection of models and apply only positive weights to the predictions. All this minimizes the risk of overfitting and ensures a more compact solution, because the solution will involve a model selection. From this perspective, ensemble selection is recommended in all problems where the risk of overfitting is high (for instance, because the training cases are few in number or the models are too complex) and in real-world applications because of its simpler yet effective solution.
When using a meta-learner, you are depending on the optimization of its own cost function, which may differ from the metric adopted for the competition. Another great advantage of ensemble selection is that it can be optimized to any evaluation function, so it is mostly suggested when the metric for the competition is different from the canon of those typically optimized in machine learning models.
Having obtained OOF predictions for all your models, you can proceed to build a meta-learner that predicts your target based on the OOF predictions (first-level predictions), or you can keep on producing further OOF predictions on top of your previous OOF predictions (second- or higher-level predictions), thus creating multiple stacking layers. This is compatible with an idea presented by Wolpert himself: by using multiple meta-learners, you are actually imitating the structure of a fully connected feedforward neural network without backpropagation, where the weights are optimally calculated in order to maximize the predictive performance at the level of each layer separately. From a practical point of view, stacking multiple layers has proven very effective and works very well for complex problems where single algorithms are unable to obtain the best results.
Moreover, one interesting aspect of stacking is that you don’t need models of comparable predictive power, as in averaging and often in blending. In fact, even worse-performing models may be effective as part of a stacking ensemble. A k-nearest neighbors model may not be comparable to a gradient boosting solution, but when you use its OOF predictions for stacking it may contribute positively and increase the predictive performance of the ensemble.
When you have trained all the stacking layers, it is time to predict. As far as producing the predictions used at various stacking stages, it is important to note that you have two ways to do this.
The original Wolpert paper suggests re-training your models on all your training data and then using those re-trained models for predicting on the test set. In practice, many Kagglers don’t retrain, but directly use the models created for each fold and make multiple predictions on the test set that are averaged at the end. In our experience, stacking is generally more effective with complete re-training on all available data before predicting on the test set when you are using a low number of k-folds. In these cases, the sample consistency may really make a difference in the quality of the prediction because training on less data means getting more variance in the estimates. As we discussed in Chapter 6, when creating OOF predictions it is always better to use a high number of folds, between 10 to 20. This limits the number of examples that are held out, and, without re-training on all the data, you can simply use the average of predictions obtained from the cross-validation trained models for obtaining your prediction on the test set.
Ensembling
An alternative to using a linear or non-linear model as a meta-learner is provided by the ensemble selection technique formalized by Caruana, Niculescu-Mizil, Crew, and Ksikes. (Мы уже обсуждали этот метод не так давно)
The ensemble selection is actually a weighted average, so it could simply be considered analogous to a linear combination. However, it is a constrained linear combination (because it is part of a hill-climbing optimization) that will also make a selection of models and apply only positive weights to the predictions. All this minimizes the risk of overfitting and ensures a more compact solution, because the solution will involve a model selection. From this perspective, ensemble selection is recommended in all problems where the risk of overfitting is high (for instance, because the training cases are few in number or the models are too complex) and in real-world applications because of its simpler yet effective solution.
When using a meta-learner, you are depending on the optimization of its own cost function, which may differ from the metric adopted for the competition. Another great advantage of ensemble selection is that it can be optimized to any evaluation function, so it is mostly suggested when the metric for the competition is different from the canon of those typically optimized in machine learning models.
Having obtained OOF predictions for all your models, you can proceed to build a meta-learner that predicts your target based on the OOF predictions (first-level predictions), or you can keep on producing further OOF predictions on top of your previous OOF predictions (second- or higher-level predictions), thus creating multiple stacking layers. This is compatible with an idea presented by Wolpert himself: by using multiple meta-learners, you are actually imitating the structure of a fully connected feedforward neural network without backpropagation, where the weights are optimally calculated in order to maximize the predictive performance at the level of each layer separately. From a practical point of view, stacking multiple layers has proven very effective and works very well for complex problems where single algorithms are unable to obtain the best results.
Moreover, one interesting aspect of stacking is that you don’t need models of comparable predictive power, as in averaging and often in blending. In fact, even worse-performing models may be effective as part of a stacking ensemble. A k-nearest neighbors model may not be comparable to a gradient boosting solution, but when you use its OOF predictions for stacking it may contribute positively and increase the predictive performance of the ensemble.
When you have trained all the stacking layers, it is time to predict. As far as producing the predictions used at various stacking stages, it is important to note that you have two ways to do this.
The original Wolpert paper suggests re-training your models on all your training data and then using those re-trained models for predicting on the test set. In practice, many Kagglers don’t retrain, but directly use the models created for each fold and make multiple predictions on the test set that are averaged at the end. In our experience, stacking is generally more effective with complete re-training on all available data before predicting on the test set when you are using a low number of k-folds. In these cases, the sample consistency may really make a difference in the quality of the prediction because training on less data means getting more variance in the estimates. As we discussed in Chapter 6, when creating OOF predictions it is always better to use a high number of folds, between 10 to 20. This limits the number of examples that are held out, and, without re-training on all the data, you can simply use the average of predictions obtained from the cross-validation trained models for obtaining your prediction on the test set.
#books #kagglebook #ensembling
Stacking variations
The main variations on stacking involve changing how test data is processed across the layers, whether to use only stacked OOF predictions or also the original features in all the stacking layers, what model to use as the last one, and various tricks in order to prevent overfitting.
We discuss some of the most effective here that we have personally experimented with:
• Optimization may or may not be used. Some solutions do not care too much about optimizing single models; others optimize only the last layers; others optimize on the first layers. Based on our experiences, optimization of single models is important and we prefer to do it as early as possible in our stacking ensemble.
• Models can differ at the different stacking layers, or the same sequence of models can be repeated at every stacking layer. Here we don’t have a general rule, as it really depends on the problem. The kind of models that are more effective may vary according to the problem. As a general suggestion, putting together gradient boosting solutions and neural networks has never disappointed us.
• At the first level of the stacking procedure, just create as many models are possible.
For instance, you can try a regression model if your problem is a classification one, and vice versa. You can also use different models with different hyperparameter settings, thus avoiding too much extensive optimization because the stacking will decide for you. If you are using neural networks, just changing the random initialization seed could suffice to create a diverse bag of models. You can also try models using different feature engineering and even use unsupervised learning (like Mike Kim did when he used t-SNE dimensions in a solution of his: https://www.kaggle.com/c/otto-group-product-classificationchallenge/discussion/14295). The idea is that the selection of all such contributions is done during the second level of the stacking. This means that, at that point, you do not have to experiment any further and you just need to focus on a narrower set of better-performing models. By applying stacking, you can re-use all your experiments and let the stacking decide for you to what degree you should use something in your modeling pipeline.
• Some stacking implementations take on all the features or a selection of them to further stages, reminiscent of skip layers in neural networks. We have noticed that bringing in features at later stages in the stacking can improve your results, but be careful: it also brings in more noise and risk of overfitting.
• Ideally, your OOF predictions should be made from cross-validation schemes with a high number of folds, in other words, between 10 to 20, but we have also seen solutions working with a lower number, such as 5 folds.
• For each fold, bagging the data (resampling with repetition) multiple times for the same model and then averaging all the results from the model (OOF predictions and test predictions) helps to avoid overfitting and produces better results in the end.
The possibilities are endless. Once you have grasped the basic concept of this ensembling technique, all you need is to apply your creativity to the problem at hand.
Stacking variations
The main variations on stacking involve changing how test data is processed across the layers, whether to use only stacked OOF predictions or also the original features in all the stacking layers, what model to use as the last one, and various tricks in order to prevent overfitting.
We discuss some of the most effective here that we have personally experimented with:
• Optimization may or may not be used. Some solutions do not care too much about optimizing single models; others optimize only the last layers; others optimize on the first layers. Based on our experiences, optimization of single models is important and we prefer to do it as early as possible in our stacking ensemble.
• Models can differ at the different stacking layers, or the same sequence of models can be repeated at every stacking layer. Here we don’t have a general rule, as it really depends on the problem. The kind of models that are more effective may vary according to the problem. As a general suggestion, putting together gradient boosting solutions and neural networks has never disappointed us.
• At the first level of the stacking procedure, just create as many models are possible.
For instance, you can try a regression model if your problem is a classification one, and vice versa. You can also use different models with different hyperparameter settings, thus avoiding too much extensive optimization because the stacking will decide for you. If you are using neural networks, just changing the random initialization seed could suffice to create a diverse bag of models. You can also try models using different feature engineering and even use unsupervised learning (like Mike Kim did when he used t-SNE dimensions in a solution of his: https://www.kaggle.com/c/otto-group-product-classificationchallenge/discussion/14295). The idea is that the selection of all such contributions is done during the second level of the stacking. This means that, at that point, you do not have to experiment any further and you just need to focus on a narrower set of better-performing models. By applying stacking, you can re-use all your experiments and let the stacking decide for you to what degree you should use something in your modeling pipeline.
• Some stacking implementations take on all the features or a selection of them to further stages, reminiscent of skip layers in neural networks. We have noticed that bringing in features at later stages in the stacking can improve your results, but be careful: it also brings in more noise and risk of overfitting.
• Ideally, your OOF predictions should be made from cross-validation schemes with a high number of folds, in other words, between 10 to 20, but we have also seen solutions working with a lower number, such as 5 folds.
• For each fold, bagging the data (resampling with repetition) multiple times for the same model and then averaging all the results from the model (OOF predictions and test predictions) helps to avoid overfitting and produces better results in the end.
The possibilities are endless. Once you have grasped the basic concept of this ensembling technique, all you need is to apply your creativity to the problem at hand.
#hpo #hpt #ensembling #diogenes #todo #metalearning
Работаю над планом создания своего тюнера гипер-параметров для библиотеки Diogenes, в том числе, формализацией процесса сбора мета-признаков.
Цели тюнера
1) простая. для конкретного датасета/таргета и ML-алгоритма, порекомендовать гиперпараметры, которые дадут лучшие (и стабильные) метрики на CV
2) посложнее. для конкретного датасета/таргета порекомендовать ML-алгоритмы с гиперпараметрами, которые дадут лучшие результаты в ансамбле
3) сложная. для конкретного датасета/таргета порекомендовать лучшие пре-, пост-процессинг (и признаков, и таргета), фиче инжиниринг, и ML-алгоритмы с гиперпараметрами для последующего ансамблирования.
Предпосылка в том, что для данного датасета (признаков) и таргета, задачи и ML алгоритма, зависимость достигнутых ML метрик от гиперпараметров алгоритма не случайна и может быть выучена/смоделирована с помощью мета-обучения. Она подтверждается моим feasibility study на базе датасета openml, да и работой авторов TabPFN.
Простой пример, чего я хочу достигнуть в задаче 1:
LTV regression where target is bimodally distributed. Tuner should recommend using Lgbm with a Tweedie loss.
https://youtu.be/qGsHlvE8KZM?t=1139
Подход, соответственно, заключается в сборе мета-датасета, когда на множестве задач обучается большое число кандидатов с разными HP, и в процессе работы с новым датасетом интеллектуальная мета-модель рекомендует "хороших" кандидатов, что должно повышать качество решения при сокращении затрат времени.
Наверное, разумно начать решение с задачи 2 (автоматически решая задачу 1). Задачу 3 можно попытаться решать позже модификацией задачи 2, когда случайным образом добавляется определённый препроцессинг, и старый алгоритм сбора мета-признаков отрабатывает уже по изменённым данным.
Неизвестно, можно ли вообще будет предсказывать хороший препроцессинг, вполне может быть, что общим решением задачи 3 будет просто случайная генерация препроцессингов и уже направленное обучение ансамблей тюнером из задачи 2. Но в этом случае надо хотя бы сформировать мета-признаки для задачи 2 с помощью разных препроцессингов хотя бы для некоторых датасетов, что само по себе крайне ресурсоёмкая задача.
Крутые "фишки" тюнера, которых ни у кого (вроде) пока нет, а у меня будут:
1) стабильность (robustness) к малым изменениям гиперпараметров. будут учитываться метрики в ближайших окрестностях решения, вместо точечной оценки. Веса будут браться пропрорционально расстоянию до точек-соседей от центра (кандидата) в одном из метрических пространств.
2) гибкая мультикритериальность - можно будет не просто получить Парето-фронт по, скажем, ROC AUC и затем F-score, но и указать, какой % от первичной метрики мы готовы променять на какой % от вторичной (и т.д.). К примеру, мы предпочитаем 3% роста F-меры (вторичной метрики) 1% роста ROC AUC (первичной метрики). Хотя, может, проще будет просто дать возможность задать веса метрик в абсолютной или нормализированной шкалах, и потом просто оптимизировать линейную комбинацию (скаляр).
3) заточенность под будущее ансамблирование, в плане стремления к разнообразности предсказаний (diversity)
4) детальное планирование затрат времени и загруженности железа, составление оптимального плана эксперимента с учётом ограничений
5) глубокое знание ВСЕХ гиперпараметров каждого алгоритма. Нет универсальности, да глубокой компетенции.
Работаю над планом создания своего тюнера гипер-параметров для библиотеки Diogenes, в том числе, формализацией процесса сбора мета-признаков.
Цели тюнера
1) простая. для конкретного датасета/таргета и ML-алгоритма, порекомендовать гиперпараметры, которые дадут лучшие (и стабильные) метрики на CV
2) посложнее. для конкретного датасета/таргета порекомендовать ML-алгоритмы с гиперпараметрами, которые дадут лучшие результаты в ансамбле
3) сложная. для конкретного датасета/таргета порекомендовать лучшие пре-, пост-процессинг (и признаков, и таргета), фиче инжиниринг, и ML-алгоритмы с гиперпараметрами для последующего ансамблирования.
Предпосылка в том, что для данного датасета (признаков) и таргета, задачи и ML алгоритма, зависимость достигнутых ML метрик от гиперпараметров алгоритма не случайна и может быть выучена/смоделирована с помощью мета-обучения. Она подтверждается моим feasibility study на базе датасета openml, да и работой авторов TabPFN.
Простой пример, чего я хочу достигнуть в задаче 1:
LTV regression where target is bimodally distributed. Tuner should recommend using Lgbm with a Tweedie loss.
https://youtu.be/qGsHlvE8KZM?t=1139
Подход, соответственно, заключается в сборе мета-датасета, когда на множестве задач обучается большое число кандидатов с разными HP, и в процессе работы с новым датасетом интеллектуальная мета-модель рекомендует "хороших" кандидатов, что должно повышать качество решения при сокращении затрат времени.
Наверное, разумно начать решение с задачи 2 (автоматически решая задачу 1). Задачу 3 можно попытаться решать позже модификацией задачи 2, когда случайным образом добавляется определённый препроцессинг, и старый алгоритм сбора мета-признаков отрабатывает уже по изменённым данным.
Неизвестно, можно ли вообще будет предсказывать хороший препроцессинг, вполне может быть, что общим решением задачи 3 будет просто случайная генерация препроцессингов и уже направленное обучение ансамблей тюнером из задачи 2. Но в этом случае надо хотя бы сформировать мета-признаки для задачи 2 с помощью разных препроцессингов хотя бы для некоторых датасетов, что само по себе крайне ресурсоёмкая задача.
Крутые "фишки" тюнера, которых ни у кого (вроде) пока нет, а у меня будут:
1) стабильность (robustness) к малым изменениям гиперпараметров. будут учитываться метрики в ближайших окрестностях решения, вместо точечной оценки. Веса будут браться пропрорционально расстоянию до точек-соседей от центра (кандидата) в одном из метрических пространств.
2) гибкая мультикритериальность - можно будет не просто получить Парето-фронт по, скажем, ROC AUC и затем F-score, но и указать, какой % от первичной метрики мы готовы променять на какой % от вторичной (и т.д.). К примеру, мы предпочитаем 3% роста F-меры (вторичной метрики) 1% роста ROC AUC (первичной метрики). Хотя, может, проще будет просто дать возможность задать веса метрик в абсолютной или нормализированной шкалах, и потом просто оптимизировать линейную комбинацию (скаляр).
3) заточенность под будущее ансамблирование, в плане стремления к разнообразности предсказаний (diversity)
4) детальное планирование затрат времени и загруженности железа, составление оптимального плана эксперимента с учётом ограничений
5) глубокое знание ВСЕХ гиперпараметров каждого алгоритма. Нет универсальности, да глубокой компетенции.
#hpo #hpt #ensembling #diogenes #todo #metalearning
Требования к тюнеру:
В реальных задачах есть конкретное железо и бюджет времени на обучение. Соответственно, планировщик должен понимать, какое время займёт обучение каждого кандидата и сколько потребует ресурсов (RAM, VRAM, диска для хранения модели). В идеале, если пользователь задал совсем жёсткое ограничение, планировщик должен рассчитать сэмплирование и обучить одну "предполагаемую лучшую" модель на этом сэмпле, использовав (почти) всё отведённое время.
То есть, от кандидатов надо собирать не только достигнутые на CV разнообразные ML-метрики, но и затраченные ресурсы CPU, GPU, памяти, диска. (add resulting model size as a factor. in xgboost, max_cat_threshold must be varied btw 0 and max cat features cardinality! # affects model size heavily when high cardinality cat features r present! ADD HIGH CARD dataset to the testing suite!)
Скорее всего, модели будут ансамблироваться для лучшей точности. При ограниченном времени это означает, что тюнеру желательно предлагать кандидатов не просто с высокой точностью, но и при этом максимально отличающихся в прогнозах от других кандидатов.
Значит, мета-модель должна прогнозировать среднюю "непохожесть" ответов кандидата на ответы всех остальных кандидатов (хотя бы внутри группы данного алгоритма).
Тут есть тонкий момент, навеянный идеями ensemble selection: возможно, ещё надо пытаться прогнозировать, сможет ли данный кандидат составить "лучшее в группе простое усреднение" с каким-то другим кандидатом. Типа, можно быть довольно похожим на остальных, но вот прям засиять с кем-то в паре.
Для сборщика мета-признаков это означает, что нужно хранить непосредственно прогнозы каждого кандидата, иначе невозможно подсчитать попарную непохожесть.
Учёт multi-fidelity. Если данные представлены таблицей с миллионами строк, конечно, нет смысла тестировать всех кандидатов на полном датасете. В идеале "пристрелку" хорошо бы вести на более разумном сэмпле, скажем, 10k, ну или хотя бы 100k строк. Но тогда надо понимать, а как для одних и тех же HP соотносятся результаты на полной и уменьшенных версиях датасета, и можно ли последние использовать для оценки первых (непосредственно в виде рангов, или через отдельную ML-модель).
Значит, при сборе мета-признаков надо их собирать как для полного датасета, так и для его "уменьшенных копий", при точно тех же HP (сэмплирование надо фиксировать для воспроизводимости).
Требования к тюнеру:
В реальных задачах есть конкретное железо и бюджет времени на обучение. Соответственно, планировщик должен понимать, какое время займёт обучение каждого кандидата и сколько потребует ресурсов (RAM, VRAM, диска для хранения модели). В идеале, если пользователь задал совсем жёсткое ограничение, планировщик должен рассчитать сэмплирование и обучить одну "предполагаемую лучшую" модель на этом сэмпле, использовав (почти) всё отведённое время.
То есть, от кандидатов надо собирать не только достигнутые на CV разнообразные ML-метрики, но и затраченные ресурсы CPU, GPU, памяти, диска. (add resulting model size as a factor. in xgboost, max_cat_threshold must be varied btw 0 and max cat features cardinality! # affects model size heavily when high cardinality cat features r present! ADD HIGH CARD dataset to the testing suite!)
Скорее всего, модели будут ансамблироваться для лучшей точности. При ограниченном времени это означает, что тюнеру желательно предлагать кандидатов не просто с высокой точностью, но и при этом максимально отличающихся в прогнозах от других кандидатов.
Значит, мета-модель должна прогнозировать среднюю "непохожесть" ответов кандидата на ответы всех остальных кандидатов (хотя бы внутри группы данного алгоритма).
Тут есть тонкий момент, навеянный идеями ensemble selection: возможно, ещё надо пытаться прогнозировать, сможет ли данный кандидат составить "лучшее в группе простое усреднение" с каким-то другим кандидатом. Типа, можно быть довольно похожим на остальных, но вот прям засиять с кем-то в паре.
Для сборщика мета-признаков это означает, что нужно хранить непосредственно прогнозы каждого кандидата, иначе невозможно подсчитать попарную непохожесть.
Учёт multi-fidelity. Если данные представлены таблицей с миллионами строк, конечно, нет смысла тестировать всех кандидатов на полном датасете. В идеале "пристрелку" хорошо бы вести на более разумном сэмпле, скажем, 10k, ну или хотя бы 100k строк. Но тогда надо понимать, а как для одних и тех же HP соотносятся результаты на полной и уменьшенных версиях датасета, и можно ли последние использовать для оценки первых (непосредственно в виде рангов, или через отдельную ML-модель).
Значит, при сборе мета-признаков надо их собирать как для полного датасета, так и для его "уменьшенных копий", при точно тех же HP (сэмплирование надо фиксировать для воспроизводимости).
#timeseries #ensembling #todo #hetboost
Что мне тут нравится, ансамблируются не просто МЛ-модельки, а еще и статмодельки.
И вот здесь автора доклада рассматривает идею, которая и меня с недавних пор преследует: гетерогенный бустинг.
У меня планируется исследование/сравнение продвинутых методов ансамблирования, и даже есть идея своего метода.
Это будет микс гетерогенного бустинга, ансамблевого отбора и стэкинга.
https://www.youtube.com/watch?v=xnF9QajUzv0
Что мне тут нравится, ансамблируются не просто МЛ-модельки, а еще и статмодельки.
И вот здесь автора доклада рассматривает идею, которая и меня с недавних пор преследует: гетерогенный бустинг.
У меня планируется исследование/сравнение продвинутых методов ансамблирования, и даже есть идея своего метода.
Это будет микс гетерогенного бустинга, ансамблевого отбора и стэкинга.
https://www.youtube.com/watch?v=xnF9QajUzv0
YouTube
Boosting Time Series Accuracy: The Power of Ensemble Methods - Robert Haase (Paretos)
Boosting Time Series Accuracy: The Power of Ensemble Methods - Robert Haase (Paretos)
This talk explores the practical application of ensemble methods in time series analysis, based on Robert’s extensive experience at Pareto. It covers various ensembling…
This talk explores the practical application of ensemble methods in time series analysis, based on Robert’s extensive experience at Pareto. It covers various ensembling…
🔥1
#timeseries #ensembling #hetboost #pmdarima #todo
Вот попался классный пример, где идея "гетерогенного бустинга" отлично отрабатывает.
Лектор на синтетике сравнивает ариму и ансамбль линрег+дерево.
В задачах на временные ряды декомпозиция на тренд, сезонность и остаточные нерегулярный сигнал очевидна и необходима, но можно посмотреть на проблему в общем - классы моделей имеют свои ограничения (деревянные модели регрессии, к примеру, плохо моделируют линейные зависимости), и обучение модели одного класса на невязках модели другого класса способно показать отличные результаты.
В то же время, сейчас самыми распространёнными методами ансамблирования являются стэкинг (когда для моделей последующего уровня меняется признаковое пространство) и гомогенный бустинг (например, градиентный над деревьями в catboost/xgboost/lightgbm), а вот идею бустинга гетерогенного как будто никто и не рассматривает, и как будто бы нет опенсорсных реализаций.
Истоки такого предубеждения, похоже, растут из ранних статей о бустинговом подходе над "слабыми моделями" (weak learners). Выбор именно слабых моделей аргументировался контролем переобучения, равномерностью шагов процесса обучения, фокусом на сложных для предсказания примерах (которые более сильная модель могла бы просто запомнить).
Мне кажется, "слабость" и одинаковость участников ансамбля не всегда благо, и на практике есть смысл в каждой конкретной задаче проверять (на CV) наиболее выгодный подход к ансамблированию, от простого усреднения моделей и ensemble selection (который мы недавно рассматривали) до стэкинга и двух видов бустинга, одно- и разнородного.
На этот год планирую сравнительное исследование )
Видимо, относительно небольшая статья о том, как стать лучше в DS, которую я подготовил, столкнувшись с неспособностью современных библиотек градиентного бустинга хорошо смоделировать простую зависимость Y=X, вырастет в большое сравнение алгоритмов ансамблирования.
Постараюсь захватить Ensemble Selection (1, 2, 3), опции ансамблирования рассмотренные в #kagglebook (1, 2, 3), и Cascade Generalization/Cascading/Delegating (or Selective Routing)/Arbitrating.
Вот попался классный пример, где идея "гетерогенного бустинга" отлично отрабатывает.
Лектор на синтетике сравнивает ариму и ансамбль линрег+дерево.
В задачах на временные ряды декомпозиция на тренд, сезонность и остаточные нерегулярный сигнал очевидна и необходима, но можно посмотреть на проблему в общем - классы моделей имеют свои ограничения (деревянные модели регрессии, к примеру, плохо моделируют линейные зависимости), и обучение модели одного класса на невязках модели другого класса способно показать отличные результаты.
В то же время, сейчас самыми распространёнными методами ансамблирования являются стэкинг (когда для моделей последующего уровня меняется признаковое пространство) и гомогенный бустинг (например, градиентный над деревьями в catboost/xgboost/lightgbm), а вот идею бустинга гетерогенного как будто никто и не рассматривает, и как будто бы нет опенсорсных реализаций.
Истоки такого предубеждения, похоже, растут из ранних статей о бустинговом подходе над "слабыми моделями" (weak learners). Выбор именно слабых моделей аргументировался контролем переобучения, равномерностью шагов процесса обучения, фокусом на сложных для предсказания примерах (которые более сильная модель могла бы просто запомнить).
Мне кажется, "слабость" и одинаковость участников ансамбля не всегда благо, и на практике есть смысл в каждой конкретной задаче проверять (на CV) наиболее выгодный подход к ансамблированию, от простого усреднения моделей и ensemble selection (который мы недавно рассматривали) до стэкинга и двух видов бустинга, одно- и разнородного.
На этот год планирую сравнительное исследование )
Видимо, относительно небольшая статья о том, как стать лучше в DS, которую я подготовил, столкнувшись с неспособностью современных библиотек градиентного бустинга хорошо смоделировать простую зависимость Y=X, вырастет в большое сравнение алгоритмов ансамблирования.
Постараюсь захватить Ensemble Selection (1, 2, 3), опции ансамблирования рассмотренные в #kagglebook (1, 2, 3), и Cascade Generalization/Cascading/Delegating (or Selective Routing)/Arbitrating.
Telegram
Aspiring Data Science
#ensembling #hpo #hpt #autosklearn
Вот какой интересный метод ансамблирования опробовали авторы оптимизатора auto-sklearn:
"Two important problems in AutoML are that (1) no single machine learning method performs best on all datasets and (2) some machine…
Вот какой интересный метод ансамблирования опробовали авторы оптимизатора auto-sklearn:
"Two important problems in AutoML are that (1) no single machine learning method performs best on all datasets and (2) some machine…
🔥4👍1
#ensembling #tabm #anns
Из интересного:
эмбеддинги непрерывных признаков позволяют лучше учиться - выучивают "высокочастотные" зависимости, делают сеть НЕинвариантной к поворотам
ансамбли оптимизируются как единое целое, синхронно по итерациям
https://www.youtube.com/watch?v=qpdGUFF7vsI
Из интересного:
эмбеддинги непрерывных признаков позволяют лучше учиться - выучивают "высокочастотные" зависимости, делают сеть НЕинвариантной к поворотам
ансамбли оптимизируются как единое целое, синхронно по итерациям
https://www.youtube.com/watch?v=qpdGUFF7vsI
YouTube
Открытая лекция: DL в табличных данных
Занятие ведёт Юра Горишний, исследователь из Yandex Research, автор научных статей по обучению нейросетей на табличных данных.
Ссылка на материалы занятия:
- Презентация: https://drive.google.com/file/d/1SO4CMRmNQQljBzOD8ZYOGQMCl6h51Qef/view?usp=sharing…
Ссылка на материалы занятия:
- Презентация: https://drive.google.com/file/d/1SO4CMRmNQQljBzOD8ZYOGQMCl6h51Qef/view?usp=sharing…
👍1