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

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

Metrics

what you care the most about when using RMSLE is the scale of your predictions with respect
to the scale of the ground truth.

By far, at the moment, RMSLE is the most used evaluation metric for regression in Kaggle competitions.


In terms of downside, using MAE as an objective function results in much slower convergence, since you are actually optimizing for predicting the median of the target (also called the L1 norm),
instead of the mean (also called the L2 norm), as occurs by MSE minimization. This results in more complex computations for the optimizer, so the training time can even grow exponentially
based on your number of training cases (see, for instance, this Stack Overflow question: https://stackoverflow.com/questions/57243267/why-is-training-a-random-forest-regressorwith-mae-criterion-so-slow-compared-to).

Dimensionality reduction

t-SNE and UMAP are two techniques, often used by data scientists, that allow you to project multivariate data into lower dimensions. They are often used to represent complex sets of data in two dimensions. 2-D UMAP and t-SNE plots can reveal the presence of outliers and relevant clusters for your data problem.

In fact, if you can plot the scatter graph of the resulting 2-D projection and color it by target value, the plot may give you hints about possible strategies for dealing with subgroups. You can find a useful example of applying both UMAP and t-SNE with a RAPIDS implementation and a GPU for data exploration purposes.

t-SNE/UMAP надо тоже использовать (как препроцессоры) при написании "умного" оптимизатора гиперпараметров

Pseudo-labeling

In competitions where the number of examples used for training can make a difference, pseudo-labeling can boost your scores by providing further examples taken from the test set. The idea is to add examples from the test set whose predictions you are confident about to your training set.

Unfortunately, you cannot know for sure beforehand whether or not pseudo-labeling will work in a competition (you have to test it empirically), though plotting learning curves may provide you with a hint as to whether having more data could be useful.
#books #kagglebook #noise #augmentaion #todo

Denoising with autoencoders

In his famous post (https://www.kaggle.com/c/porto-seguro-safe-driver-prediction/ discussion/44629), Michael Jahrer describes how a DAE can not only remove noise but also automatically create new features, so the representation of the features is learned in a similar way to what happens in image competitions. In the post, he mentions the secret sauce for the DAE recipe, which is not simply the layers, but the noise you put into the data in order to augment it. He also made clear that the technique requires stacking together training and test data, implying that the technique would not have applications beyond winning a Kaggle competition.

In order to help train any kind of DAE, you need to inject noise that helps to augment the training data and avoid the overparameterized neural network just memorizing inputs (in other words, overfitting). In the Porto Seguro competition, Michael Jahrer added noise by using a technique called swap noise, which he described as follows: Here I sample from the feature itself with a certain probability “inputSwapNoise” in the table above. 0.15 means 15% of features replaced by values from another row.

What is described is basically an augmentation technique called mixup (which is also used in image augmentation: https://arxiv.org/abs/1710.09412). In mixup for tabular data, you decide a probability for mixing up. Based on that probability, you change some of the original values in a sample, replacing them with values from a more or less similar sample from the same training data.

Большой вопрос, на который нет ответа - почему аугментации всегда используются в задачах машинного зрения, и никогда - в табличных данных? А ведь это отличный метод создания diversity. Нужно исследование.

Neural networks for tabular competitions

Use activations such as GeLU, SeLU, or Mish instead of ReLU; they are quoted in quite a few papers as being more suitable for modeling tabular data and our own experience confirms that they tend to perform better.

Use augmentation with mixup (discussed in the section on autoencoders).
Use quantile transformation on numeric features and force, as a result, uniform or Gaussian distributions.

Leverage embedding layers, but also remember that embeddings do not model everything. In fact, they miss interactions between the embedded feature and all the others (so you have to force these interactions into the network with direct feature engineering).

Remember that embedding layers are reusable. In fact, they consist only of a matrix multiplication that reduces the input (a sparse one-hot encoding of the high cardinality variable) to a dense one of lower dimensionality. By recording and storing away the embedding of a trained neural network, you can transform the same feature and use the resulting embeddings in many other different algorithms, from gradient boosting to linear models.
#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.
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.
#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.
#colab

Мне понравилось

Generate Colab badges
Check out openincolab.com to create a badge for your READMEs, websites, documents, and more. Simply input the URL of a notebook hosted on GitHub, test the badge, and grab the HTML code!

https://medium.com/towards-data-science/a-close-look-at-colabs-new-updates-and-enhancements-f1225fd5d504
#diamonds

"Выращенный в лаборатории алмаз, о котором сообщили исследователи, относится к «неправильной» гексагональной разновидности. Его создали путём нагревания сильно спрессованного графита. Группе удалось получить образец шестиугольного алмаза размером около миллиметра. Его твёрдость составила 155 гигапаскалей (ГПа), что существенно выше, чем у природных алмазов (70–100 ГПа). Также синтезированный лонсдейлит продемонстрировал повышенную термическую стабильность на воздухе — он выдерживал нагрев до 1100 °C, тогда как природный алмаз начинал окисляться уже при 700 °C.

Наибольший спрос на синтетические лонсдейлиты ожидается в промышленности. Они также могут использоваться в системах отвода тепла. Кроме того, такие алмазы способны помочь в разработке более надёжных устройств хранения данных и при производстве электроники, во многом превосходя в этих сферах традиционные алмазы. "

https://3dnews.ru/1118508/kitaytsi-nauchilis-sintezirovat-nepravilnie-almazi-oni-na-50-tvyorge-prirodnih
#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) глубокое знание ВСЕХ гиперпараметров каждого алгоритма. Нет универсальности, да глубокой компетенции.
#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 (сэмплирование надо фиксировать для воспроизводимости).
#ghosts

Ахаха, блэт, этот Егор просто Крамник в мире айтишников!! )) А ты сколько коммитов сделал за год, сволочь такая, не призрак ли ты?! Я слежу за тобой!

https://blog.stackademic.com/1-in-10-silicon-valley-engineers-are-ghost-engineer-earning-300k-for-doing-almost-nothing-474b667da09d
🤡1
#featureengineering #pysr #symbolicregression

На самом деле, подход символьной регрессии перекликается с моей идеей использования информационно-теоретических метрик.

Читаю сейчас статью pysr, у них интересный подход с генетиком над признаками, отобранными бустингом.

Очень хочу сравнить их результаты со своими на том же игрушечном примере.

Для естественных наук приложение прямое, для машинного обучения, естественно, приложение может быть в создании новых хороших признаков.

Ps. ДА! pysr отлично справился с моим примером!

import numpy as np, pandas as pd

n =100_000
a = np.random.rand(n)
b = np.random.rand(n)
c = np.random.rand(n)
d = np.random.rand(n)
e = np.random.rand(n)
f = np.random.rand(n)

y=a**2/b+f/5+np.log(c)*np.sin(d)

df = pd.DataFrame(
{
"a": a,
"b": b,
"c": c,
"d": d,
"e": e,

}
)

from pysr import PySRRegressor

model = PySRRegressor(
maxsize=20,
niterations=40, # < Increase me for better results
binary_operators=["+", "*"],
unary_operators=[
"cos",
"exp",
"log",
"sin",
"inv(x) = 1/x",
# ^ Custom operator (julia syntax)
],
extra_sympy_mappings={"inv": lambda x: 1 / x},
# ^ Define operator for SymPy as well
elementwise_loss="loss(prediction, target) = (prediction - target)^2",
# ^ Custom loss function (julia syntax)
)

model.fit(df, y)

model.get_best()


после ~6 минут работы

complexity 14
loss 0.003329
score 0.947915
sympy_format a**2/b + log(c)*sin(d) + 0.09998281
👍2
#featureengineering #pysr #symbolicregression #todo

Библиотека pysr заслуживает пристального внимания. Она настолько хорошо сделана, глубока и функциональна, что просто загляденье.

Полностью готова к внедрению в бой, поддерживает оптимизации, кластера, логгинг в тензорборд, пре-отбор признаков с помощью ML, сохранение прогресса в файл и тёплый старт.

Зацените функциональность и количество опций:

model = PySRRegressor(
populations=8,
# ^ Assuming we have 4 cores, this means 2 populations per core, so one is always running.
population_size=50,
# ^ Slightly larger populations, for greater diversity.
ncycles_per_iteration=500,
# ^ Generations between migrations.
niterations=10000000, # Run forever
early_stop_condition=(
"stop_if(loss, complexity) = loss < 1e-6 && complexity < 10"
# Stop early if we find a good and simple equation
),
timeout_in_seconds=60 * 60 * 24,
# ^ Alternatively, stop after 24 hours have passed.
maxsize=50,
# ^ Allow greater complexity.
maxdepth=10,
# ^ But, avoid deep nesting.
binary_operators=["*", "+", "-", "/"],
unary_operators=["square", "cube", "exp", "cos2(x)=cos(x)^2"],
constraints={
"/": (-1, 9),
"square": 9,
"cube": 9,
"exp": 9,
},
# ^ Limit the complexity within each argument.
# "inv": (-1, 9) states that the numerator has no constraint,
# but the denominator has a max complexity of 9.
# "exp": 9 simply states that `exp` can only have
# an expression of complexity 9 as input.
nested_constraints={
"square": {"square": 1, "cube": 1, "exp": 0},
"cube": {"square": 1, "cube": 1, "exp": 0},
"exp": {"square": 1, "cube": 1, "exp": 0},
},
# ^ Nesting constraints on operators. For example,
# "square(exp(x))" is not allowed, since "square": {"exp": 0}.
complexity_of_operators={"/": 2, "exp": 3},
# ^ Custom complexity of particular operators.
complexity_of_constants=2,
# ^ Punish constants more than variables
select_k_features=4,
# ^ Train on only the 4 most important features
progress=True,
# ^ Can set to false if printing to a file.
weight_randomize=0.1,
# ^ Randomize the tree much more frequently
cluster_manager=None,
# ^ Can be set to, e.g., "slurm", to run a slurm
# cluster. Just launch one noscript from the head node.
precision=64,
# ^ Higher precision calculations.
warm_start=True,
# ^ Start from where left off.
turbo=True,
# ^ Faster evaluation (experimental)
extra_sympy_mappings={"cos2": lambda x: sympy.cos(x)**2},
# extra_torch_mappings={sympy.cos: torch.cos},
# ^ Not needed as cos already defined, but this
# is how you define custom torch operators.
# extra_jax_mappings={sympy.cos: "jnp.cos"},
# ^ For JAX, one passes a string.
)


И на её базе, как понимаю, уже сделаны отличные исследования.
Надо изучать доку.

И хорошо бы её потестить для FE, на каких-то разумных настройках глубины/сложности/времени. И датасетах с в т.ч. большим количеством фичей.
👍2
#energy

"За последние 50 лет придуманные нефтяниками методы бурения и разрыва пластов открыли возможность доступа к теплу недр на большей части планеты, а не только рядом с вулканами. Пока новыми технологиями воспользовались лишь единичные компании, но в них скрыт огромный потенциал для производства электрической энергии в больших масштабах. Сегодня в глобальном масштабе доля геотермальной энергетики по-прежнему составляет менее половины процента. Доля солнечной и ветряной энергии более чем в 25 раз выше, что можно исправить в обозримые сроки.

Для доступа к подземному теплу следует использовать методы бурения, разработанные для добычи сланцевого газа, включая горизонтальное бурение и гидроразрыв пластов. Закачивая в скважины жидкость под большим давлением, нефтяники расширяют существующие в породе трещины и создают новые, за счёт чего происходит приток нефти и других жидкостей к поверхности. В геотермальных системах с улучшенными характеристиками жидкость представляет собой просто горячую воду из естественных подземных резервуаров."

https://3dnews.ru/1118710/nesmotrya-na-risk-zemletryaseniy-geotermalnuyu-energiyu-gdyot-svetloe-budushchee-schitayut-uchyonie