Aspiring Data Science – Telegram
Aspiring Data Science
386 subscribers
465 photos
12 videos
12 files
2.15K links
Заметки экономиста о программировании, прогнозировании и принятии решений, научном методе познания.
Контакт: @fingoldo

I call myself a data scientist because I know just enough math, economics & programming to be dangerous.
Download Telegram
#categoricals

Скорее всего, автор допустил множественные утечки данных, но сам подход интересен. По схожей схеме работает и optbinning.

https://medium.com/@ordavidovitch/advanced-feature-engineering-and-regression-techniques-with-python-5239621731ac
#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
#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
#automl #papers

An Empirical Study on the Usage of Automated Machine Learning Tools

Forough Majidi, Moses Openja, Foutse Khomh , Heng Li

Интересное исследование, как automl используется в гитхабовских проектах.

https://arxiv.org/pdf/2208.13116
#automl #hpo #hpt #openml

Наконец-то дочитал вторую книжку, Frank Hutter - automatic machine learning methods systems challenges, и кандидатскую диссертацию его менти Маттиаса Фойрера, по сов-му создателя auto-sklearn.

Перехожу наконец-то к feasibility study своей идеи мета-обучения для HPT. Данные openml не получится использовать для полноценного решения, т.к. они не тречат время расчётов и железо, размер модели и время инференса.

Также в запусках нет указания, какие параметры были дефолтными.

Но хотя бы их платформу и собранные данные можно попробовать использовать для

1) быстрой оценки, а можно ли вообще с помощью мета-признаков ранжировать алгоритмы и гиперпараметры на конкретной задаче
2) разведки самых важных метапризнаков (и в будущем создания подобных)
3) изучения их АПИ, чтобы взять хорошие идеи и пофиксить плохие
4) использования хотя бы части их датасетов.

Для затравочки - визуализация метрик SVM в зависимости от 2-х HP.
Forwarded from LightAutoML framework
📔 Мы внимательно следим за последними статьями в области ML, и сегодня хотим обратить ваше внимание на модель TabPFN v2 из статьи “Accurate predictions on small data with a tabular foundation model”, опубликованную в январе 2025 года в Nature. Модель работает на табличных данных, первая версия TabPFN была опубликована в октябре 2022, во второй версии помимо классификации появилась регрессия.

💡 Идея TabPFN v2:
В классических алгоритмах для решения suprevised задач на табличных данных модель обучается с нуля, в статье используется подход с предобучением:
1. Генерируются 130 миллионов синтетических датасетов с помощью каузальных графов, которые имитируют сложные зависимости в данных, пропуски, выбросы.
2. На сгенерированных данных предобучается трансформер, предсказывая таргет test выборки, получая на вход train как контекст. Для каждой ячейки таблицы используется отдельная репрезентация. Используется механизм внимания как по строкам, так и по столбцам таблицы.
3. Вместо привычных отдельных "fit" и "predict", трансформер за один проход получая и train, и test новой задачи одновременно, делает инференс на test, используя in-context learning. Простыми словами, модель обучена однажды, но подхватывает зависимости в данных из подаваемого в контекст датасета и сразу делает предсказания.

🥇 Результаты авторов:
1. Скорость и качество: в задачах классификации и регрессии на данных до 10к строк и 500 признаков за несколько секунд получает качество лучше, чем ансамбль из базовых алгоритмов (бустинги, лес, линейные), которые тюнились в течение нескольких часов.
2. Минимум работы: алгоритм не нужно тюнить, имеет отбор признаков, нативно работает с числовыми и категориальными признаками, а также с пропусками.
3. Плюсы foundation моделей: возможность получить распределение таргета, генерировать данные итд.
4. Неплохо показывает себя на временных рядах.

🤔 Выводы:
1. Статья показала эффективность foundation моделей в домене табличных данных, теперь у бустингов сильные конкуренты.
2. Пока есть вопросы с точки зрения эффективности инференса, ограниченности контекста, но дальше будут улучшения.
3. Интересно, что TabPFN v2 можно назвать AutoML решением, ведь для решения задачи он не требует ни настройки гиперпараметров, ни предобработки данных.

Тема интересная, у нас имеются наработки по этой теме, и мы работаем над их применением в LightAutoML🦙, stay tuned!

#обзор
Please open Telegram to view this post
VIEW IN TELEGRAM
#automl #tabpfn

Читаю авторскую статью про TabPFN. Если они не накосячили нигде, похоже, это одна их самых сильных работ по ML за последние года. А то и десятилетия.

Ну извините, ТАКОГО преимущества от мета-обучения (хотя там доля и от транформерной архитектуры, знать бы, какая), я не ожидал даже в самых смелых мечтах: "TabPFN (default) outperforms AutoGluon for classification tasks, even if AutoGluon is allowed up to 4 h, a 5.140× speedup".

"Apart from its strong predictive performance, TabPFN exhibits key foundation model abilities, such as data generation, density estimation, learning reusable embeddings and fine-tuning. We showcase these abilities through proof-of-concept experiments on the German Credit Dataset44, which contains credit risk information and the mfeat-factors45 dataset classifying handwritten digits based on a tabular representation.

TabPFN can estimate the probability density function of numerical features, as shown in Fig. 6a, and the probability mass function of categorical features. Computing the sample densities enables anomaly detection to identify issues such as fraud, equipment failures, medical emergencies or low-quality data.

TabPFN also allows synthesizing new tabular data samples that mimic real-world dataset characteristics as shown in Fig. 6b. This enables applications such as data augmentation or privacy-preserving data sharing.

The architecture of TabPFN yields meaningful feature representations that can be reused for downstream tasks such as data imputation and clustering. We extract and visualize learned embeddings from the mfeat-factors dataset in Fig. 6c, showing improved class separation compared with the raw data on the first two principal components."

А есть вообще то, чего она не может?

Limitations of TabPFN. The limitations of TabPFN are as follows:

(1) the inference speed of TabPFN may be slower than highly optimized approaches such as CatBoost;
(2) the memory usage of TabPFN scales linearly with dataset size, which can be prohibitive for very large datasets;
(3) our evaluation focused on datasets with up to 10,000 samples and 500 features; scalability to larger datasets requires further study.
4
#automl #tabpfn

Могу подтвердить, что, похоже, их либа (и подход) реально работает. На нескольких датасетах типа breast cancer, и синтетики типа make_classification(n_samples=40_000, n_classes=2,n_features=40,n_informative=10) TabPFN в моих запусках всегда опережала катбуст по ROC AUC и точности. пусть ненамного, но всегда. гиперпараметры катбуста я 4 часа не тюнил, просто проверил кол-во деревьев 1_000, 10_000, с и без ранней остановки.


На моей старенькой RTX 2070:

train, test sets shape= (30000, 40)

ROC AUC: 0.9945391499218594
Accuracy 0.9890666666666666

train+inference time: 4min 7s


для сравнения результаты катбуста CatBoostClassifier(verbose=0,task_type='CPU',eval_fraction=0.1,early_stopping_rounds=200, num_trees=10000)

ROC AUC: 0.9939392120134284
Accuracy 0.9802


Для train, test sets shape= (20000, 40) время 1min 56s.

С хорошим GPU она возьмёт и датасет 100k-200k строк, наверное.
С другой стороны, мне кажется, если тюнить, можно TabPFN и догнать.

Для PHE-версии надо явно передавать device: AutoTabPFNClassifier(max_time=60*9,ignore_pretraining_limits=True,device="cuda")

Что интересно, он грузит веса типа Attempting HuggingFace download: tabpfn-v2-classifier-od3j1g5m.ckpt, Attempting HuggingFace download: tabpfn-v2-classifier-llderlii.ckpt.

В общем, теперь метод .fit выполняется долго (согласно max_time), да ещё и .predict_proba занял 5 минут на том же датасете. ROC AUC немного улучшилась по сравнению с не-PHE версией, Accuracy чуть просела.

ROC AUC: 0.9948400465955762
Accuracy 0.9888666666666667
3
The Kaggle Book by Konrad Banachewicz and Luca Massaron

Millions of data enthusiasts from around the world compete on Kaggle, the most famous data science competition platform of them all. Participating in Kaggle competitions is a surefire way to improve your data analysis skills, network with an amazing community of data scientists, and gain valuable experience to help grow your career.

The first book of its kind, The Kaggle Book assembles in one place the techniques and skills you'll need for success in competitions, data science projects, and beyond. Two Kaggle Grandmasters walk you through modeling strategies you won't easily find elsewhere, and the knowledge they've accumulated along the way. As well as Kaggle-specific tips, you'll learn more general techniques for approaching tasks based on image, tabular, textual data, and reinforcement learning. You'll design better validation schemes and work more comfortably with different evaluation metrics.

Whether you want to climb the ranks of Kaggle, build some more data science skills, or improve the accuracy of your existing models, this book is for you.

Link: Book

Navigational hashtags: #armknowledgesharing #armbooks
General hashtags: #ml #machinelearning #featureengineering #kaggle #metrics #validation #hyperparameters #tabular #cv #nlp

@data_science_weekly
#automl #hpo #hpt #openml #diogenes

Провёл feasibility study оптимизатора гиперпараметров на базе мета-обучения, по данным openml. Результаты очень обнадёживают.

Для конкретного алгоритма ML (я взял xgboost classifier) , зная признаки датасета и, собственно, гиперпараметры, можно, не проводя каждый раз обучение, предсказывать достижимый ROC AUC со средней ошибкой MAPE в 3-5%.

Это fewshot, обучив модель на 1% комбинаций данного конкретного датасета (не обучив ни на одной комбинации датасета, т.е., только pretrain, MAPE=14%).
С мета-фичами от застройщика авторов openml.

А у меня же еще тонна идей по улучшениям. Я хотел эту идею реализовать еще 2 года тому, ну да ладно, хорошо хоть сейчас начал.

Работы, конечно, море, но предварительные результаты позитивные. В топку "байесовкую оптимизацию". There must be a better way!
#books #kagglebook #ctf

Читаю The Kaggle book, оказывается , Энтони Голдблюм по образованию экономист, как и я )
А Джереми Ховард перед основанием fast.ai трудился в Kaggle.

Хинтон тоже не избежал участия в соревах каггл, и даже выиграл MerckActiviy. Уже интересно!

"Professor Donoho does not refer to Kaggle specifically, but to all data science competition platforms. Quoting computational linguist Mark Liberman, he refers to data science competitions and platforms as being part of a Common Task Framework (CTF) paradigm that has been silently and steadily progressing data science in many fields during the last decades. He states that a CTF can work incredibly well at improving the solution of a problem in data science from an empirical point of view, quoting the Netflix competition and many DARPA competitions as successful examples. The CTF paradigm has contributed to reshaping the best-in-class solutions for problems in many fields.

The system works the best if the task is well defined and the data is of good quality. In the long run, the performance of solutions improves by small gains until it reaches an asymptote. The process can be sped up by allowing a certain amount of sharing among participants (as happens on Kaggle by means of discussions, and sharing Kaggle Notebooks and extra data provided by the datasets found in the Datasets section). According to the CTF paradigm, competitive pressure in a competition suffices to produce always-improving solutions. When the competitive pressure is paired with some degree of sharing among participants, the improvement happens at an even faster rate – hence why Kaggle introduced many incentives for sharing."
#cv

"Actually, if you watch carefully the data, it seems like data distributions are segregated into specific portions of space, something reminiscent ot me of the Madelon dataset created by Isabelle Guyon.

I therefore tried to stratifiy my folds based on a k-means clustering of the non-noisy data and my local cv has become more reliable (very correlated with the public leaderboard) and my models are performing much better with cv prediction."

https://www.kaggle.com/code/lucamassaron/are-you-doing-cross-validation-the-best-way
🔥1
#umap #tsne #dimreducers #manifold

Понравилась интерактивная визуализация кластеров датасета одежды. Ну и мамонт, конечно.

"UMAP is an incredibly powerful tool in the data scientist's arsenal, and offers a number of advantages over t-SNE.

While both UMAP and t-SNE produce somewhat similar output, the increased speed, better preservation of global structure, and more understandable parameters make UMAP a more effective tool for visualizing high dimensional data.

Finally, it's important to remember that no dimensionality reduction technique is perfect - by necessity, we're distorting the data to fit it into lower dimensions - and UMAP is no exception.

However, by building up an intuitive understanding of how the algorithm works and understanding how to tune its parameters, we can more effectively use this powerful tool to visualize and understand large, high-dimensional datasets."

https://pair-code.github.io/understanding-umap/
Думаю, это была свёрточная нейросеть, а не "ИИ".

"В USP был проведён эксперимент, в котором ИИ самостоятельно анализировал фотографии лошадей, сделанные до и после хирургического вмешательства, а также до и после приёма обезболивающих препаратов. ИИ изучал глаза, уши и рот лошадей, определяя наличие болевого синдрома. Согласно результатам исследования, ИИ сумел выявить признаки, указывающие на боль, с точностью 88 %, что подтверждает эффективность такого подхода и открывает перспективы для дальнейших исследований."

https://3dnews.ru/1118376/ii-nauchilsya-raspoznavat-emotsii-givotnih-po-virageniyu-mordi
👍1