Title of Competition
stringclasses 343
values | Title of Writeup
stringlengths 6
139
| User
stringclasses 1
value | Writeup
stringlengths 419
80.4k
|
---|---|---|---|
Liberty Mutual Group: Property Inspection Prediction
|
My Solution
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Liberty Mutual Group: Property Inspection Prediction
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Hi,
This is the competition that i participated with lot of enthusiasm and followed quite closely. With my final selected submissions, i am sitting at 81'th position on a private leaderboard. If i had selected another model, my score could be 0.393273 (with a possible rank of 55). I tried few following things:</p>
<ol>
<li>I mainly used XGBoost, K-nearest neighbor and Random forests.</li>
<li>Trained these models with different parameters, i.e. mainly XGBoost with Linear, and POisson objective. Also, used RMSE criteria along with GINI metric.</li>
<li>For K-Nearest Neighbor, i tried different number of neighbors and weighting schemes</li>
<li>Random forest: I did not get a chance to fine tune it that much, but managed to get @0.357 GINI with RF. </li>
<li>I then ensembled all these models and tried different weights on each of these models to check how it improves the public leaderboard score.</li>
</ol>
<p>This ensemble i selected as a final entry which scored 0.392898 on a private leaderboard.</p>
<p>The another ensemble containing only 3-XGBoost models would have scored 0.393273 on a private leaderboard. This ensemble contains, XGBoost model with linear objective, and RMSE criteria, Poission objective with default error metric (i.e. negative log likelihood) and Poisson objective with RMSE criteria. </p>
<p>Lessons learnt:
1. Model themselves have limitations in terms of how much you can improve on a single model.
2. Feature engineering is quite crucial. I did not use any synthetic feature in my simulations. I wish i have focused more on feature engineering (may be in the next competition).
3. Model stacking is something that seems to be promising. I did not get a chance to implement it here. </p>
<p>I will post my codes soon on the forum.</p>
<p>Best,
abhijit</p>
|
Liberty Mutual Group: Property Inspection Prediction
|
My Top15 Solution
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Liberty Mutual Group: Property Inspection Prediction
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>[quote=Alexander D'yakonov;91574]</p>
<p>Thanks, Faron!</p>
<p>[/quote]</p>
<p>You are welcome!</p>
<p>Dear Kagglers,</p>
<p>I learnt alot in this competition due to the great community and I want to share my solution in order to "give something back".</p>
<p>My solution scores 0.394519 @ Private LB (Top15). You can find the sources here:
<a href="https://github.com/far0n/kaggle-lmgpip">kaggle-lmgpip</a></p>
<p>It is based on <a href="https://www.kaggle.com/justfor/liberty-mutual-group-property-inspection-prediction/bench-stacked-generalization">Bench Stacked Generalization</a> by <a href="https://www.kaggle.com/justfor">Justfor</a> and the famous .3911 script <a href="https://www.kaggle.com/soutik/liberty-mutual-group-property-inspection-prediction/blah-xgb">Blah-XGB</a> by <a href="https://www.kaggle.com/soutik">Soutik Chakraborty</a>.</p>
|
Liberty Mutual Group: Property Inspection Prediction
|
Sharing my solution
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Liberty Mutual Group: Property Inspection Prediction
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>This is the best solution that I got. I tried various xgboost with different specifications. No improvement by adding other model libraries.</p>
<p><a href="https://github.com/ffyu/Kaggle-Liberty-Mutual-Competition">https://github.com/ffyu/Kaggle-Liberty-Mutual-Competition</a></p>
|
Liberty Mutual Group: Property Inspection Prediction
|
my solution 0.3498
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Liberty Mutual Group: Property Inspection Prediction
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>[quote=brave heart;95810]</p>
<p>[quote=tsing;91312]</p>
<p>i try 4 models. private score: fm(0.363), rf(0.378*), gbm(0.3929*), xgb(0.39498). emsemble get no improve。</p>
<p>[/quote]</p>
<p>Hi tsing, thank you for your sharing. I quickly look into you code, while i could find how you using FM model? Did you training Fm in some where else ?</p>
<p>[/quote]</p>
<p>FM model not in this file, here is the code for feature convert. FM model use libfm with default parameters.</p>
<p>[quote=Alexander Popov;91931]</p>
<p>[quote=tsing;91312]</p>
<p>i try 4 models. private score: fm(0.363), rf(0.378*), gbm(0.3929*), xgb(0.39498). emsemble get no improve。</p>
<p>[/quote]
I ensembled your model with mine (fine tuned like this: <a href="https://www.kaggle.com/c/liberty-mutual-group-property-inspection-prediction/forums/t/16271/fine-tuned-xgb">https://www.kaggle.com/c/liberty-mutual-group-property-inspection-prediction/forums/t/16271/fine-tuned-xgb</a>) and got 0.396126 </p>
<p>[/quote]
it seems my feature engineering works</p>
<p>i try 4 models. private score: fm(0.363), rf(0.378*), gbm(0.3929*), xgb(0.39498). emsemble get no improve。</p>
|
Linking Writing Processes to Writing Quality
|
1151 Place Solution for the Linking Writing Processes to Writing Quality Competition [275 efficiency leaderboard]
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Linking Writing Processes to Writing Quality
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>I know that my notebook didn't place well on the performance leaderboard, but I'm hoping to get feedback on the efficiency leaderboard soon. My public score landed me at 295 on the efficiency leaderboard (as of earlier today), so I'm going to focus on efficiency here. </p>
<h2><strong>Context section</strong></h2>
<p>Business Context: <a href="https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/overview" target="_blank">https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/overview</a> <br>
Data Context: <a href="https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/data" target="_blank">https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/data</a></p>
<h2>Overview of my Approach</h2>
<p>The models that I tried for my final submission included a CatBoostRegressor and a LightGBM Regressor. I decided against using a more complex deep learning model and although there were other notebooks shared with higher scores that I could have used to build on, I wanted to do the majority of the work on my own.</p>
<p>My model's public score was .607 and the private leaderboard score was .589. I placed a heavy emphasis on feature engineering for my submission, which I will describe below.</p>
<h2>Details of the Submission</h2>
<p>I approached this competition both from a data scientist's point of view and a researcher's point of view. A lot of the time I spent involved reading relevant articles about this topic and learning about the features that have been used before for this type of analysis. </p>
<p>Below are some examples:</p>
<ul>
<li><p><a href="https://people.eng.unimelb.edu.au/baileyj/papers/paper249-EDM.pdf" target="_blank">https://people.eng.unimelb.edu.au/baileyj/papers/paper249-EDM.pdf</a><br>
Highlight: Defines data processing methods for analyzing pauses, bursts, and revision periods</p></li>
<li><p><a href="https://link.springer.com/article/10.1007/s11145-019-09953-8#Sec6" target="_blank">https://link.springer.com/article/10.1007/s11145-019-09953-8#Sec6</a><br>
Highlight: Figure 4 identifies the top features used in the model and their effect sizes</p></li>
</ul>
<h3>Feature Engineering</h3>
<p>As I said earlier, I placed a large emphasis on feature engineering for this competition. Some of the areas I focused on included:</p>
<ul>
<li>Calculating streaks for activities<br>
-Word length</li>
<li>Sentences, questions, quotes, commas</li>
<li>Grouping by activity (for input, nonproduction, remove/cut, and replace)</li>
<li>2 minute warning for nonproduction</li>
<li>Production rate - number of characters (including spaces) produced per minute during the process</li>
<li>Binary flags based on number of words, number of paragraphs, and sentences</li>
<li>Percentage of time spent writing, pausing, or revising</li>
<li>INTER-KEY INTERVAL (IKI) </li>
<li>Time between keys (TBK)</li>
</ul>
<p>This is an example of the code used for IKI and tbk:</p>
<p><code>def iki_tbk(data):
data['previous_uptime'] = data.groupby('id')['up_time'].shift()
data['iki']=data['up_time']-data['previous_uptime']
data['tbk']=data['down_time']-data['previous_uptime']
return data
df_logs=iki_tbk(df_logs)
df_logs['iki.5-1']=np.where((df_logs['iki']>=500 ) & (df_logs['iki']<=1000 ),1,0)
df_logs['iki1.5']=np.where((df_logs['iki']>1000 ) & (df_logs['iki']<=1500 ),1,0)
df_logs['iki2']=np.where((df_logs['iki']>1500 ) & (df_logs['iki']<=2000 ),1,0)
df_logs['iki2.5']=np.where((df_logs['iki']>2000 ) & (df_logs['iki']<=3000 ),1,0)
df_logs['iki3']=np.where((df_logs['iki']>3000 ),1,0)</code></p>
<p>In the end, the features I selected were based on their correlation coefficient with the essay score. I set an arbitrary threshold for myself and moved it up and down for testing purposes.</p>
<h3>Model Comparisons</h3>
<p>I compared four different baseline models to start.</p>
<ol>
<li>Random Forest Regressor</li>
<li>LGBM Regressor</li>
<li>CatBoost Regressor</li>
<li>XGBoost Regressor</li>
</ol>
<p>This is the code block I used to generate my baseline model comparisons.</p>
<p><code>seed = 7
models = []
models.append(('LGBM', lgbm.LGBMRegressor()))
models.append(('RF', RandomForestRegressor()))
models.append(('Cat', CatBoostRegressor()))
models.append(('XG', XGBRegressor() ))
results = []
names = []
scoring='neg_root_mean_squared_error'
for name, model in models:
kfold = KFold(n_splits=10, shuffle=True)
cv_results = cross_val_score(model, X, y, cv=kfold, scoring=scoring,verbose=0)
results.append(cv_results)
names.append(name)
msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std())
print(msg)
fig = plt.figure()
fig.suptitle('Algorithm Comparison')
ax = fig.add_subplot(111)
plt.boxplot(results)
ax.set_xticklabels(names)</code><br>
After I selected the LGBM and CatBoost models to start tuning, I used Optuna to select the best hyperparameters. To do this, I set up a couple of simple Optuna studies, based on this code template:</p>
<p><code>def objective(trial):
param = {
"iterations": 1000,
"learning_rate": trial.suggest_float("learning_rate", 1e-3, 0.1, log=True),
"depth": trial.suggest_int("depth", 1, 10),
"subsample": trial.suggest_float("subsample", 0.05, 1.0),
"colsample_bylevel": trial.suggest_float("colsample_bylevel", 0.05, 1.0),
"min_data_in_leaf": trial.suggest_int("min_data_in_leaf", 1, 100),
}
model = CatBoostRegressor(**param)
model.fit(X_train, y_train, verbose=0)
y_pred = model.predict(X_test)
rmse = np.sqrt(mean_squared_error(y_test, y_pred))
return rmse</code><br>
Though some may say this automated tuning process is the "easy way out", I found that this forced me to learn more about the different hyperparameters for each model and how they function. <img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F3113438%2F081910922a14df80c7574f229be60174%2Falgo%20comp.png?generation=1704848671754360&alt=media"></p>
<h2>Validation</h2>
<p>I used a kfold cross validation technique to arrive at my best solution. I see from the top entries that relying on CV scores paid off for many. In my case, my CV score was consistently around .610 and my entry came in at .589, so I guess this was a good strategy. </p>
<h2>What didn't work</h2>
<p>I tried a few things that clearly did not work for this competition.</p>
<ul>
<li>I filtered out essays with a score of .5 at one point. I did this because based on the rubric provided, it seemed that these could be erroneous scores. However, these proved to be very important.</li>
<li>I tried SMOTE for oversampling the outlier scores: To do this I had to convert the float score to a categorical field and then separate low scores from the other scores so that I could oversample .5 and 1 essays. This did not work at all, but I'm glad I gave it a try.</li>
</ul>
<h2>Sources</h2>
<p>At one point, I did try to recreate the essays using this notebook: <br>
<a href="https://www.kaggle.com/code/iurigabriel/lgbm-xgboost" target="_blank">https://www.kaggle.com/code/iurigabriel/lgbm-xgboost</a><br>
I thought their function for the basic word features was great and I used it as inspiration for writing my own feature engineering functions (the IKI and TBK functions).</p>
<p>The articles that I mentioned earlier were extremely helpful for me. I'll link to them again here:</p>
<ul>
<li><a href="https://people.eng.unimelb.edu.au/baileyj/papers/paper249-EDM.pdf" target="_blank">https://people.eng.unimelb.edu.au/baileyj/papers/paper249-EDM.pdf</a></li>
<li><a href="https://link.springer.com/article/10.1007/s11145-019-09953-8#Sec6" target="_blank">https://link.springer.com/article/10.1007/s11145-019-09953-8#Sec6</a></li>
</ul>
<h2>Conclusion</h2>
<p>Even though I didn't do well on the performance leaderboard, I think this competition helped me immensely as it was the first "real" code competition I've attempted on Kaggle. Thank you to the organizers of the competition for giving us all the opportunity to work on this project!</p>
|
Linking Writing Processes to Writing Quality
|
12th place solution
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Linking Writing Processes to Writing Quality
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h3>Acknowledgements</h3>
<p>I would like to express my sincere gratitude to Kaggle and the competition host for providing an opportunity filled with learning and inspiration. I also extend my deep respect to all the participants who contributed their insights and ideas to the competition. Thank you.</p>
<h3>Overview</h3>
<p>I trained lightgbm, xgboost, catboost, and denselight(from lightautoml) on two different sets of features, and averaged their predictions with different weights. The weight ratios were adjusted while observing the Local CV score and Public LB.</p>
<p><strong>Feature set 1</strong><br>
1504 features, which include various features introduced by public notebooks,and some additional features. I added PCA, TF-IDF, CountVectorizer, and additional up_time_lagged features.</p>
<p>Reference public notebooks:<br>
<a href="https://www.kaggle.com/code/abdullahmeda/enter-ing-the-timeseries-space-sec-3-new-aggs" target="_blank">enter-ing-the-timeseries-space-sec-3-new-aggs</a><br>
<a href="https://www.kaggle.com/code/awqatak/silver-bullet-single-model-165-features" target="_blank">silver-bullet-single-model-165-features</a></p>
<p>Feature set1 Lightgbm Result:<br>
CV(10fold&5seed average): 0.596, Public LB:0.579, Private LB:0.571</p>
<p><strong>Feature set 2</strong><br>
Features from public notebooks(<a href="https://www.kaggle.com/code/awqatak/silver-bullet-single-model-165-features" target="_blank">silver-bullet-single-model-165-features</a>)and distilroberta predictions.</p>
<p>Feature set2 Lightgbm Result:<br>
CV(10fold&5seed average): 0.589, Public LB:0.580, Private LB:0.570</p>
<p><strong>The weight ratio</strong><br>
0.4 * (lightgbm(Feature Set 1) + 0.5 * xgboost(Feature Set 1) + 0.5 * catboost(Feature Set 1) + denselight(Feature Set 1)) / 3 + 0.6 * (lightgbm(Feature Set 2) + denselight(Feature Set 2)) / 2</p>
<p>Weighted Average Result:<br>
CV(10fold&5seed average): 0.5870 ,Public LB: 0.576, Private LB: 0.563</p>
<h3>Training Strategy</h3>
<p>For both feature sets 1 and 2, I trained all models with a 10-fold cross-validation on 5 different seeds and took the average. I performed parameter tuning for lightgbm and xgboost using optuna, while for catboost, I did not tune parameters and only set the depth to 6. For denselight, I used the parameters directly from this notebook. <a href="https://www.kaggle.com/code/alexryzhkov/lightautoml-nn-test" target="_blank">lightautoml-nn-test</a></p>
<h3>Feature set2's distilroberta</h3>
<p>I used the reconstructed essay based on this notebook. <a href="https://www.kaggle.com/code/kawaiicoderuwu/essay-contructor" target="_blank">essay-contructor</a></p>
<p>I performed preprocessing like the following: <br>
“qqq qq q’qq, qqq qqq” → “3 2 1’2, 3 3” <br>
Converted to the number of consecutive 'q’s.</p>
<p>Due to the vocabulary included in the tokenizer, it is only capable of encoding sequences of one or two characters, such as ‘q’ or ‘qq’, consecutively. Therefore, feeding it directly into the tokenizer results in an extremely large number of tokens. The following figure illustrates the change in the distribution of token counts before and after preprocessing.</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F5053254%2Fbc0293d70b93300db2e2ab143f0a56c0%2Fpreprocessing.png?generation=1705031689302363&alt=media"></p>
<p>Initially, I attempted to train using deberta-v3-large, but I could not achieve satisfactory result. When I switched to the lighter distilroberta, I obtained better results.The fact that there is limited data and the same token appears repeatedly may have led to better performance with lighter models.</p>
<p>deberta-v3-large CV(10fold&5seed average): 0.620 <br>
distilroberta CV(10fold&5seed average): 0.605</p>
<p>However, it is likely that better accuracy could have been achieved with deberta-v3-base ,small or xsmall, as with many other top-tier solutions(deberta-v3-small is smaller than distilroberta). Since I started testing lighter models towards the end of the competition, I didn’t have time to consider a wide range of models and couldn’t investigate them. I am conducting follow-up tests with deberta-v3-base, small, and xsmall to see what results can be obtained. Once the results are out, I would like to share them in this form of an additional note.</p>
<p>To add diversity to the models, I only used the roberta features in feature set 2, since Feature set 1 already included many features extracted from reconstructed essay like TF-IDF. </p>
<p>The improvement for the predictions of feature set 2 was as follows. </p>
<table>
<thead>
<tr>
<th>model</th>
<th>CV(w/o roberta )</th>
<th>CV(w/ roberta)</th>
<th>Public LB(w/o roberta)</th>
<th>Public LB(w/ roberta)</th>
<th>Private LB(w/o roberta)</th>
<th>Private LB(w/ roberta)</th>
</tr>
</thead>
<tbody>
<tr>
<td>lightgbm</td>
<td>0.602</td>
<td>0.589</td>
<td>0.582</td>
<td>0.580</td>
<td>0.574</td>
<td>0.570</td>
</tr>
<tr>
<td>xgboost</td>
<td>0.607</td>
<td>0.579</td>
<td>0.581</td>
<td>0.579</td>
<td>0.578</td>
<td>0.572</td>
</tr>
<tr>
<td>catboost</td>
<td>0.606</td>
<td>0.583</td>
<td>0.586</td>
<td>0.583</td>
<td>0.575</td>
<td>0.568</td>
</tr>
<tr>
<td>denselight</td>
<td>0.602</td>
<td>0.585</td>
<td>0.590</td>
<td>0.585</td>
<td>0.568</td>
<td>0.565</td>
</tr>
</tbody>
</table>
<h3>What didn't work</h3>
<p>dimension reduction(umap, tsne)<br>
tsfresh<br>
clustering<br>
clasification<br>
other loss function(huber, poisson …)<br>
wavenet<br>
Inception time<br>
Denoise auto encoder<br>
Tabnet<br>
MLP<br>
autoint<br>
ffttransformer</p>
<h3>late submission result (update 2024.01.24)</h3>
<p>The deberta-xsmall model yielded the best results.<br>
A token count of 1280 produced better outcomes than 512, and deberta was considered superior for its ability to increase the maximum token count significantly.<br>
The presence of preprocessing led to better results. However, it should be noted that as the token count for deberta is increased, the difference becomes less significant.</p>
<p><strong>various model result</strong></p>
<table>
<thead>
<tr>
<th>model</th>
<th>CV</th>
<th>Public LB</th>
<th>Private LB</th>
</tr>
</thead>
<tbody>
<tr>
<td>deberta v3 xsmall max_token = 512</td>
<td>0.6088</td>
<td>0.6201</td>
<td>0.5999</td>
</tr>
<tr>
<td>deberta v3 xsmall max_token = 1280</td>
<td>0.5965</td>
<td>0.5879</td>
<td>0.6020</td>
</tr>
<tr>
<td>deberta v3 small max_token = 512</td>
<td>0.6046</td>
<td>0.6152</td>
<td>0.5989</td>
</tr>
<tr>
<td>deberta v3 xsmall max_token = 1280</td>
<td>0.5946</td>
<td>0.5994</td>
<td>0.5874</td>
</tr>
<tr>
<td>deberta v3 base max_token = 512</td>
<td>0.6041</td>
<td>0.6135</td>
<td>0.5983</td>
</tr>
<tr>
<td>deberta v3 base max_token = 1280</td>
<td>0.5955</td>
<td>0.5959</td>
<td>0.5906</td>
</tr>
<tr>
<td>distil-roberta max_token = 512</td>
<td>0.605</td>
<td>0.6134</td>
<td>0.5900</td>
</tr>
<tr>
<td>distil-roberta max_token = 512 w/o preprocess</td>
<td>0.7638</td>
<td>0.7548</td>
<td>0.7820</td>
</tr>
<tr>
<td>deberta v3 base max_token = 512 w/o preprocess</td>
<td>0.7764</td>
<td>0.7991</td>
<td>0.7758</td>
</tr>
<tr>
<td>deberta v3 base max_token = 1280 w/o preprocess</td>
<td>0.6404</td>
<td>0.6392</td>
<td>0.6167</td>
</tr>
</tbody>
</table>
<p>note: I used huggingface trainer. I modified commonlit public notebook. Parameter is same as reference notebook's parameter. <a href="https://www.kaggle.com/code/tsunotsuno/debertav3-w-prompt-title-question-fields" target="_blank">ref</a></p>
<p><strong>stacking result</strong></p>
<table>
<thead>
<tr>
<th>model</th>
<th>CV</th>
<th>Public LB</th>
<th>Private LB</th>
</tr>
</thead>
<tbody>
<tr>
<td>deberta v3 xsmall max_token = 512</td>
<td>0.5878</td>
<td>0.5815</td>
<td>0.5717</td>
</tr>
<tr>
<td>deberta v3 xsmall max_token = 1280</td>
<td>0.5881</td>
<td>0.5789</td>
<td>0.5669</td>
</tr>
<tr>
<td>deberta v3 small max_token = 512</td>
<td>0.5866</td>
<td>0.5820</td>
<td>0.5723</td>
</tr>
<tr>
<td>deberta v3 xsmall max_token = 1280</td>
<td>0.5873</td>
<td>0.5820</td>
<td>0.5691</td>
</tr>
<tr>
<td>deberta v3 base max_token = 512</td>
<td>0.5882</td>
<td>0.5800</td>
<td>0.5711</td>
</tr>
<tr>
<td>deberta v3 base max_token = 1280</td>
<td>0.5862</td>
<td>0.5783</td>
<td>0.5703</td>
</tr>
<tr>
<td>distil-roberta max_token = 512</td>
<td>0.5889</td>
<td>0.5804</td>
<td>0.5700</td>
</tr>
<tr>
<td>distil-roberta max_token = 512 w/o preprocess</td>
<td>0.5946</td>
<td>0.5850</td>
<td>0.5691</td>
</tr>
<tr>
<td>deberta v3 base max_token = 512 w/o preprocess</td>
<td>0.5965</td>
<td>0.5832</td>
<td>0.5730</td>
</tr>
<tr>
<td>deberta v3 base max_token = 1280 w/o preprocess</td>
<td>0.5972</td>
<td>0.5834</td>
<td>0.5729</td>
</tr>
<tr>
<td>w/o bert predictions</td>
<td>0.602</td>
<td>0.582</td>
<td>0.574</td>
</tr>
</tbody>
</table>
<p>note: silver-bullet features + bert predictions, lightgbm and optuna, 10fold and 5seed</p>
<p>I used huggingface trainer and this trainer performs early stopping.<br>
distil-roberta's public LB is 0.6134, private LB is 0.5900.</p>
<p>The inclusion of roberta features provided a different set of characteristics compared to features like tfidf, which I believe contributed to the increased accuracy during the ensemble process. Additionally, the ability of the tokenizer to handle words not present in the train data was a superior point that I considered. I was concerned about the differences between the train and test data sets.</p>
|
Linking Writing Processes to Writing Quality
|
15th solution feature selection and trust your CV
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Linking Writing Processes to Writing Quality
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Congratulations to everyone who won or learnt from this competition.</p>
<p>Unfortunately, we did end with a gold medal, but we have already selected our best private result. Our best result come from feature selection of two groups of features & models. Our strategy is feature selection + trust CV</p>
<p><strong>Features summary:</strong></p>
<ul>
<li><p>P1 (features 1, 2, 3): from my teammates, but unfortunately they’re busy on their own work, they can not write up the detail.</p></li>
<li><p>P2: from my sides, which has 4 subgroups of features, feature4, feature5, feature6 and feature8 with feature selection, feature select boosted the CV about 0.008, but worsen 0.003 on public LB.</p></li>
</ul>
<p><strong>Feature 4/5/6/8 details:</strong></p>
<ul>
<li><p>Feature4: the public 0.584 notebook, I did feature selection and keep 130 features</p></li>
<li><p>Feature5 (selected 45 features): my own features but most are borrowed from public notebooks, and I added below features <br>
TFIDF of constructed essay: <br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F530572%2F5c830d62ed1b8d665e1774c75cb66cf4%2FScreenshot%202024-01-13%20at%2014.04.19.png?generation=1705154675640043&alt=media"><br>
TFIDF of event: <br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F530572%2Fc0fbfc3ef6445d25f04b05a57270807f%2FScreenshot%202024-01-13%20at%2014.04.53.png?generation=1705154705748892&alt=media"><br>
‘word_comma_cusor’ feature: <br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F530572%2Face2c051575b771d776334f67fb88ec4%2FScreenshot%202024-01-13%20at%2014.03.15.png?generation=1705154626602193&alt=media"></p></li>
<li><p>Feature6 (selected 60 features): added burst features to feature5 </p></li>
<li><p>Feature8: public 0.582/581 features, with feature selection of top 80 features</p></li>
</ul>
<p><strong>Final result:</strong></p>
<ul>
<li><p>0.5<em>my_teammate_result(CV: 0.587, public LB: 0.576, private LB: 0.566) + 0.5</em>my_result(CV: est 0.590, public LB: 0.579, private LB: 0.568)</p></li>
<li><p>my_results = 0.4<em>freature4_130features + 0.125</em>feature4_45features + 0.175<em>feature6_60features + 0.3</em>feature8_80features</p></li>
<li><p>feature5 and feature6 used 5 Kfold split, LGB, CAT, XGB and SVR with Bayesian optimisation to select best weights.</p></li>
<li><p>Feature4/5/6/8 used 5 seeds. feature4 CV: ~0.6, public LB 0.587; feature5 CV: 0.592; public LB: 0.590, feature6 CV: 0.591, public LB: 0.588; feature8 CV: 0.608, public LB: 0.584. Ensemble of feature4/5/6/8, got public LB: 0.579, private LB: 0.568.</p></li>
</ul>
|
Linking Writing Processes to Writing Quality
|
1st place solution before team disqualification
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Linking Writing Processes to Writing Quality
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p><a href="https://www.kaggle.com/mihailturlakov" target="_blank">@mihailturlakov</a>, see <a href="https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/discussion/469199" target="_blank">this post</a> about the reason of the team disqualification.</p>
<p>Thank you for your congratulations <a href="https://www.kaggle.com/jasonheesanglee" target="_blank">@jasonheesanglee</a>, and thank you for your amazing notebook! BTW did you manage to improve accuracy compare to the public version?</p>
<p>Thanks <a href="https://www.kaggle.com/darraghdog" target="_blank">@darraghdog</a>. Though being fourth might be frustrating for you and <a href="https://www.kaggle.com/christofhenkel" target="_blank">@christofhenkel</a>, congrats with another gold!</p>
<h1>1st Place Solution for the Linking Writing Processes to Writing Quality Competition</h1>
<p>First of all, I would like to express my gratitude to Kaggle and The Learning Agency Lab for organizing this wonderful competition. Thanks to the Kaggle community for sharing beautiful code and great ideas.<br>
I would like to thank my teammates <a href="https://www.kaggle.com/kurokurob" target="_blank">@kurokurob</a>, <a href="https://www.kaggle.com/ayaanjang" target="_blank">@ayaanjang</a>, <a href="https://www.kaggle.com/takuji" target="_blank">@takuji</a>, <a href="https://www.kaggle.com/alansmithe" target="_blank">@alansmithe</a> for the great team work. Congrats <a href="https://www.kaggle.com/kurokurob" target="_blank">@kurokurob</a> with the GM title! He was our team leader and generated many valuable ideas.</p>
<h2>Summary</h2>
<p>Our "Private LB 0.557, Public LB 0.575" submission used the following 8 models.</p>
<pre><code>MODELS = [
{: ,:},
{: ,:},
{: ,:},
{: , :[], :[]},
{: ,:},
{: ,: },
{: ,: },
{: ,: },
]
INTERCEPT = -
</code></pre>
<h2>CV Strategy</h2>
<p>All models' CVs have been created with the following split. <br>
This allows for proper weighting of the ensemble.</p>
<pre><code>skf = StratifiedKFold(n_splits=,shuffle=,random_state=)
fold = np.zeros((train),dtype=)
n, (_, val_idx) (skf.split(train, (train[] * ).astype())):
fold[val_idx] = n
train[] = fold
</code></pre>
<h2>Ayaan part</h2>
<p>I created the following 3 models.</p>
<ul>
<li>ayaan-v8-LGBM.py<ul>
<li>LGBM model, CV 0.59759</li></ul></li>
<li>ayaan-v8-MLP.py<ul>
<li>MLP model, CV 0.59716</li></ul></li>
<li>ayaan-v9-LGBM.py<ul>
<li>LGBM model, CV 0.58993</li></ul></li>
</ul>
<h3>ayaan-v8-LGBM.py</h3>
<ul>
<li>Model: LGBM (CV 0.59759)</li>
<li>Total Feature number: 1,339</li>
<li>Feature Engineering<ul>
<li>Solution based on "https://www.kaggle.com/code/alexryzhkov/lgbm-and-nn-on-sentences"</li>
<li>get Essay() <a href="https://www.kaggle.com/code/kawaiicoderuwu/essay-contructor" target="_blank">Ref.</a></li>
<li>sentence aggregations features</li>
<li>paragraphs aggregations features</li>
<li>nonspace ngram features</li>
<li>CountVectorizer features</li>
<li>TFidfVectorizer features (「analyzer="char"」 is important.They boost CV by +0.005 and public by +0.003 depending on models. Thanks for finding, <a href="https://www.kaggle.com/alansmithe" target="_blank">@alansmithe</a>)</li>
<li>class Preprocessor features <a href="https://www.kaggle.com/code/abdullahmeda/enter-ing-the-timeseries-space-sec-3-new-aggs" target="_blank">Ref.</a></li>
<li>Lagged Features (up_time_lagged, down_time_lagged, down_time_minus1_lagged)</li>
<li>Time Differences and Aggregated Statistics</li></ul></li>
</ul>
<pre><code>logs[] = (logs[] - logs[]) /
group = logs.groupby()[]
largest_lantency = group.()
smallest_lantency = group.()
...
logs[] = (logs[] - logs[]) /
group = logs.groupby()[]
iki_max = group.()
iki_min = group.()
</code></pre>
<ul>
<li>Pause Durations</li>
</ul>
<pre><code>pauses_half_sec = group.apply( x: ((x > ) & (x < )).())
pauses_1_sec = group.apply( x: ((x > ) & (x < )).())
pauses_1_half_sec = group.apply( x: ((x > ) & (x < )).())
pauses_2_sec = group.apply( x: ((x > ) & (x < )).())
pauses_3_sec = group.apply( x: (x > ).())
iki_pauses_half_sec = group.apply( x: ((x > ) & (x < )).())
iki_pauses_1_sec = group.apply( x: ((x > ) & (x < )).())
iki_pauses_1_half_sec = group.apply( x: ((x > ) & (x < )).())
iki_pauses_2_sec = group.apply( x: ((x > ) & (x < )).())
iki_pauses_3_sec = group.apply( x: (x > ).())
</code></pre>
<h3>ayaan-v8-MLP.py</h3>
<ul>
<li>Model: LightAutoML MLP (CV 0.59716)</li>
<li>Total Feature number: 1,339</li>
<li>Feature Engineering<ul>
<li>Same feature as “ayaan-v8-LGBM.py”</li></ul></li>
</ul>
<h3>ayaan-v9-LGBM.py</h3>
<ul>
<li>Model: LGBM (CV 0.58993)</li>
<li>Total Feature number: 1,390</li>
<li>Feature Engineering<ul>
<li>Same feature as “ayaan-v8-LGBM.py”</li>
<li>Added <a href="https://www.kaggle.com/nazarov" target="_blank">@nazarov</a>, <a href="https://www.kaggle.com/takuji" target="_blank">@takuji</a>’s feature (This is a very powerful feature. Boosted CV 0.007+. More on this in the <a href="https://www.kaggle.com/nazarov" target="_blank">@nazarov</a> and <a href="https://www.kaggle.com/takuji" target="_blank">@takuji</a> parts.)</li></ul></li>
</ul>
<h2>kuro_B part</h2>
<h3>KAA_model2/KAA_model2_infer.py</h3>
<ul>
<li>Model: LightAutoML denselight(CV0.6135 / public0.59)</li>
<li>Total Feature number: 865</li>
<li>Feature Engineering<ul>
<li>Based on this <a href="https://www.kaggle.com/code/hiarsl/feature-engineering-sentence-paragraph-features" target="_blank">notebook</a>. </li>
<li>Add some features. <ul>
<li>a variant of split_essays_into_paragraphs / compute_paragraph_aggregations(functions that splits essays by "\n\n" and make features for each segment.)<ul>
<li>This improved both cv & public by + 0.001.</li></ul></li>
<li>Other features slightly improved cv & public.</li></ul></li></ul></li>
<li>Important setting<ul>
<li>nn_params={"cont_embedder": "plr"}<ul>
<li>This setting improved cv by +0.01 and public by +0.004.</li>
<li>It's plr embedder mentioned in this <a href="https://openreview.net/forum?id=pfI7u0eJAIr" target="_blank">paper</a>.</li></ul></li></ul></li>
</ul>
<h2>esprit part</h2>
<h3>NLP model</h3>
<p>I created NLP models with reconstructed essays as input and scores as output.<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F3190389%2F09b93e128b1601a058ecfd3c969ec661%2Fimage_nlp_part.png?generation=1704962667288649&alt=media"></p>
<ul>
<li>Essay reconstructor<ul>
<li><a href="https://www.kaggle.com/code/jasonheesanglee/updated-75-35-acc-revealing-hidden-words?scriptVersionId=148517101" target="_blank">[Updated - 75.35% acc] Revealing hidden words</a></li></ul></li>
<li>Model<ul>
<li>Backbone: deberta-v3-base</li>
<li>GPU I used: single RTX 3090</li>
<li>Train time: 27 minutes / epoch</li></ul></li>
<li>What didn't work<ul>
<li>Using the constructor that does not output uppercase made the score slightly worse.</li>
<li>Adding tokens like ["q" * n for i in range(16)] made the score worse.</li>
<li>Adding pseudo-labeled Feedback 2 or Feedback 3 data to the training data did not improve scores.</li>
<li>Changing the base model to the large model did little to improve scores.</li></ul></li>
<li>Best CV: 0.61083<br>
In the end, I created 8 models with 10 epochs training with all essays.</li>
</ul>
<h2>ln part</h2>
<h3>Ridge</h3>
<p>I was lucky to find my key to this competition early. It was a Ridge model.<br>
The ensemble, consisting of LGBM with 165 public and 51 of my features, a simple NN with two layers trained on the same features, and a Ridge model scored 0.561 on Private, which is strong gold. So I begin the description with Ridge. It was applied to Tfidf features with the following settings.</p>
<pre><code> ():
text.split()
all_essays = all_essays..replace(,,regex=)
vec = TfidfVectorizer(tokenizer=word_tokenize, lowercase=,
token_pattern=,min_df=,ngram_range=(,upper))
X = vec.fit_transform(all_essays)
model = Ridge(alpha=)
model.fit(X[:(target)],target)
</code></pre>
<p>For upper from 7 to 4 the models CVs are {7:0.62832, 6:0.62829, 5:0.62964, 4:0.63795:}. The scores are not impressive, but they significantly improve the ensemble in both CV and LB.</p>
<h3>Feature engineering</h3>
<p>I will only describe the features that I created in the hope that they will differ from the publicly available ones.</p>
<h4>GridFeatureMaker</h4>
<p>While most of the public notebooks calculate statistics for gaps, this class makes the same for fixed 60 time intervals 30 seconds each. PCA factors are calculated for selected statistics. I used PCA in order to </p>
<ul>
<li>Limit the number of features;</li>
<li>Make features different from those calculated for gaps.</li>
</ul>
<h4>KNNFeatureMaker</h4>
<p>Only 3 but rather strong features. KNN regressor predictions based on </p>
<ul>
<li>statistics of the lengths of words;</li>
<li>statistics of text_change;</li>
<li>TfidfVectorizer features generated only by punctuation.</li>
</ul>
<h4>External data features</h4>
<p>I fitted models to the following datasets with letters replaced by "q".</p>
<ul>
<li><a href="https://www.kaggle.com/competitions/feedback-prize-english-language-learning" target="_blank">FB3</a></li>
<li><a href="https://www.kaggle.com/competitions/commonlit-evaluate-student-summaries" target="_blank">FB2</a></li>
<li><a href="https://www.kaggle.com/datasets/thevirusx3/automated-essay-scoring-dataset" target="_blank">AES</a></li>
<li><a href="https://www.kaggle.com/datasets/mazlumi/ielts-writing-scored-essays-dataset" target="_blank">IELTS</a><br>
The models' predictions for the competition dataset are very strong features. When <a href="https://www.kaggle.com/kurokurob" target="_blank">@kurokurob</a> added them to his model, the boost was 0.008. There were 10 days left until the end and all the models were already quite strong by this time. I fitted Ridge, text-CNN model and Deberta-v3-xsmall. In the final version FB2 and FB3 are predicted by Deberta-v3-xsmall, AES and IELTS by Ridge.</li>
</ul>
<h3>Nonlinear models</h3>
<h4>LGBM</h4>
<p>I started with the brilliant notebook of <a href="https://www.kaggle.com/awqatak" target="_blank">@awqatak</a> <a href="https://www.kaggle.com/code/awqatak/silver-bullet-single-model-165-features" target="_blank">Silver-bullet</a>. Special thanks to him. After adding my features and additional tuning I got 10-fold CV 0.58880.</p>
<h4>Simple NN with 2 FC layers and skip connection</h4>
<p>It was trained on the same features as LGBM, 10-fold CV 0.59084</p>
<h4>Deberta-v3-xsmall</h4>
<p>After teaming up with <a href="https://www.kaggle.com/takuji" target="_blank">@takuji</a>, I modified his training code and achieved with deberta-v3-xsmall trained on lowercase reconstructed essays (the output of <a href="https://www.kaggle.com/code/yuriao/fast-essay-constructor" target="_blank">fast essay constructor</a>) performance close to base and large models, 5-fold CV 0.611-0.613. This model was used for fitting to external datasets and obtaining external data features.</p>
<h3>What didn’t work</h3>
<h4>Training LM with small vocabulary from scratch</h4>
<p>Deberta tokenizer vocabulary doesn't contain tokens 'qqq','qqqq',… Here is the example</p>
<pre><code>tokenizer.tokenize()
</code></pre>
<p>That’s why tokenizing essays we get very long sequences. We used max_len 2048 in our models. I created vocabulary consisting from punctuation, tokens like ‘q’*n and special tokens (55 tokens total), made a custom tokenizer for it, and tried to train deberta-v3-xsmall (and its variants with reduced dimension) from scratch on a large corpus with letters replaced by ‘q’ as MLM. I spent a lot of time on this project but failed. I couldn’t push the score below 0.63.</p>
<h4>Text CNN</h4>
<p>Best 5-fold CV was about 0.63 and it didn’t improve ensemble</p>
<h4>Other NN architectures</h4>
<p>I tried RNN, different variants of Transformer including the one presented by <a href="https://www.kaggle.com/pdnartreb" target="_blank">@pdnartreb</a> in his <a href="https://www.kaggle.com/competitions/predict-student-performance-from-game-play/discussion/420217" target="_blank">winning solution</a> with no success.<br>
PS. See <a href="https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/discussion/469199" target="_blank">this post</a> about the reason of the team disqualification.</p>
<p>Suppose we have FB2. I replace letters with "q" and train deberta-v3-xsmall using the columns <code>['content','wording']</code> as the target. Then I make predictions for reconstructed essays and obtain two features <code>['content','wording']</code> that can be used by any of my models.</p>
<p><a href="https://www.kaggle.com/gauravbrills" target="_blank">@gauravbrills</a> The KNN regressors were too weak to add to the ensemble as is, but their predictions turned out to be useful features.</p>
|
Linking Writing Processes to Writing Quality
|
23th Place Solution
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Linking Writing Processes to Writing Quality
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks! Just added the link for the source to the original post, fyi.</p>
<p>There are a lot of differences between your kernel and mine. My implementations especially for bursts and pauses are different.</p>
<p>Whoa, I was trusting the CV and expecting a shake-up but not an upper-silver. 😅</p>
<p>You can check the code from here: <a href="https://github.com/nlztrk/Linking-Writing-Processes-to-Writing-Quality/" target="_blank">https://github.com/nlztrk/Linking-Writing-Processes-to-Writing-Quality/</a></p>
<p>Here are the things I've basically extracted and used:</p>
<p><strong>Text Features</strong></p>
<ul>
<li>Pre-processed the extracted essay and deleted recurring tabs, spaces and newlines</li>
<li>Word, sentence and paraghraph based statistical aggregations</li>
<li>Punctuation statistics</li>
<li>Punctuation mistake statistics (dot without a space after, comma with a space before, newline without a punctuation etc.)</li>
</ul>
<p><strong>Event Log Features</strong></p>
<ul>
<li>Count and nunique features for events</li>
<li>Statistical aggregations for all numerical columns</li>
<li>Pause-time aggregations (for all text, pause between words, sentences and paragraphs, seperately.)</li>
<li>P and R burst time and key-press count features</li>
</ul>
<p><strong>Training</strong></p>
<ul>
<li>Used 10-Fold Stratified</li>
<li>Used CatBoost, LGBM and XGBoost</li>
<li>Hyperparameter-tuned all models with using Optuna</li>
<li>Tracked OOF</li>
<li>Ensembled final models using Optuna-OOF-tuned weights</li>
</ul>
<p>I am happy that my efforts weren't for nothing. I congratulate all of you!</p>
<p>0.59446. I think luck still plays a big role. Even in my CV some folds were drastically better or worse than the others. I also have submission with CV 0.578 but I've used bi-gram count-vectorizer in that, so that might be the suspect for it performing worse. It scored 0.582 on private LB.</p>
<p>You can also try hyperopt. But I like the syntax of Optuna 😅</p>
<p>Thanks <a href="https://www.kaggle.com/yunsuxiaozi" target="_blank">@yunsuxiaozi</a>, glad you could reproduce it!</p>
|
Linking Writing Processes to Writing Quality
|
278th place solution
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Linking Writing Processes to Writing Quality
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Hello Kagllers.</p>
<p>I was placed 278th this competitions by using this<a href="https://www.kaggle.com/code/shisa07/lgbm-x2-nn-fusion?scriptVersionId=157068932" target="_blank"> notebook</a>. Thanks for sharing.</p>
<p>I tried some features engineering and blending, but score wasn't improved. I don't know if it's useful, but I'll share what I did.</p>
<ul>
<li>Feature Engineering<ul>
<li>Add pause time(30, 60, 90) </li>
<li>Changing Vectorizer(TF-IDF)</li></ul></li>
<li>Blending<ul>
<li>Add other model(random forest, svm, cat-boost)</li></ul></li>
</ul>
<p>I assumed that students who write good essays would spend a certain amount of time thinking about the content of their essays, so I added the above-mentioned pause time as a feature.<br>
The reason I used TF-IDF is that is one of a statistic intended to reflect how important a word is.</p>
<p>Some winner says "feature engineering is all you need", I feel the same way.</p>
<p>Thanks for reading. </p>
|
Linking Writing Processes to Writing Quality
|
2nd Place Efficiency Leaderboard Solution
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Linking Writing Processes to Writing Quality
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>My main focus for this competition was the efficiency stream. For this reason, I opted to concentrate on developing a LightGBM model, since past experience suggested this would provide good performance whilst minimising inference time. Most of my time was focused on feature engineering using the Polars, Numba and Joblib Python packages. The Polars package specifically was used because it proved to be much quicker than alternatives such as Pandas.</p>
<h1>Summary</h1>
<pre><code>• Leaderboard Score: / Place: th
• Efficiency Leaderboard Score: / Place: nd
• LightGBM model
• cross used during development, /th of training used as a test dataset
• Final model trained
• Total of features used
• Feature generation performed using Polars, Numba Joblib packages minimise processing time
• Important features based :
◦ reconstructed essays
◦ aggregates of the down_time event_id differences between events
• Code execution timings (based Kaggle notebook platform):
◦ Train Feature Generation Time: s
◦ Model Training Time ( models): s
</code></pre>
<h1>Feature Importance Plot</h1>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1199911%2F7c40ea8a95fba0d3e75d2deb93d2407f%2Ffeature_importances.png?generation=1705749562266522&alt=media"></p>
<h1>Code</h1>
<p>The code can be found <a href="https://www.kaggle.com/code/mark4h/writing-processes-2nd-place-efficiency-lb-solution" target="_blank">here</a></p>
|
Linking Writing Processes to Writing Quality
|
38th Place Solution (3rd Public)
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Linking Writing Processes to Writing Quality
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Hi everyone,<br>
Thanks for Kaggle and the host for this nice competition! Also, thanks to my brilliant teammates <a href="https://www.kaggle.com/ihebch" target="_blank">@ihebch</a> and <a href="https://www.kaggle.com/aliibrahimali" target="_blank">@aliibrahimali</a>. This would be impossible without them!</p>
<h1>Summary:</h1>
<p>We used almost same features as the ones in the public notebooks (I think this what led us to shake down in private, maybe because we relied too much on the silver bullet one, but anyway it was a really amazing notebook, thanks to <a href="https://www.kaggle.com/awqatak" target="_blank">@awqatak</a> ) and fed them into 3 classifiers (TabPFN, MLPClassifier, MultinomialNB) then took their probabilities as features. Then we fed all the features into our regression ensemble of XGBoost + 6 linear models, then we found the best weights for ensembling using linear regression.</p>
<h1>Validation:</h1>
<p>We had a quite good correlation between cv and lb. A lot of the improvements in cv translated to lb. Our best in cv was the best in public and private at the same time. <br>
Our best in cv was around 0.592, in public lb was 0.570 (3rd public) and in private lb was 0.566. <br>
Ok what is our cv? It is basically this piece of line:<br>
<code>StratifiedKFold(n_splits=5/10/.., shuffle=True, random_state=42)</code><br>
without any bags (We changed the n_splits several times, but at the end we used 5 because the class of score “0.5” had only 5 elements in the dataset).<br>
We treated the public lb as an additional fold. So, we kept only the changes that improved cv and lb at the same time.</p>
<h1>Feature Engineering:</h1>
<p>At the beginning, we started with the features from the public notebooks. We tried adding more aggregations/interactions to them but that didn’t help. What we found to be useful is:</p>
<ul>
<li>Raw Count Features: we added quite a lot of them then did features selection at the end which was useful. (+0.001)</li>
<li>Latent Dirichlet Allocation: Using pretrained NLP models didn’t help a lot in our case, so instead of embedding, why not trying some clustering? LDA helped in this and gave us a decent boost in cv/lb. We fed it with count vectorizers with different settings and it was really helpful (+0.002).</li>
<li>Some Representation Features: fitting t-SNE on top of the data with different perplexities helped gaining a good boost (+0.001).</li>
<li>Probabilities and Expectation of Classifiers: Using raw probabilities and Expectations out of the 3 models: TabPFN, MLPClassifier and MultinomialNB as features gave us a decent boost as well (+0.001). The input for these models was 100 PCA components of the original data. We did that to gain some diversity in input instead of feeding the original data.</li>
</ul>
<h1>Features Selection:</h1>
<p>The abovementioned engineered features were ~1400. We used LOFO extensively several times for all the models. Our final models contain ~350 features only. This gave us another boost (+0.001).</p>
<h1>Modeling:</h1>
<p>XGBoost was our best single model. Adding linear models helped gain some diversity.<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F7311816%2F83c03caffed31d01b9cb00c94594bbb5%2F1png.png?generation=1704865607048528&alt=media" alt=""><br>
We didn’t use early stopping as it would lead to overfitting, especially with this small dataset.</p>
<h1>What didn’t work:</h1>
<ul>
<li>Training on original logs: We put a lot of time into this one. We tried to fit various types of models on the logs data hoping that we may get some diversity gains later, but nothing worked. Btw, training on these logs by just mapping the target into the IDs won’t be useful (a sample at the beginning of the writing would score same as a sample at the end, which is not correct). So, we decided to use a growing target (Just used np.linspace(0,score,n_samples_in_id)). <br>
It gave some good boost in its own cv but it still was too bad compared to training on aggregated data (~0.718). It gave some boost in xgboost cv when adding its output as a feature, but that didn’t translate to lb, so we gave it up.</li>
<li>More bags: this always gave us a much better cv and much worse lb. So, we gave it up (We are using only ideas that improve both cv and lb). Btw, the result was still bad in private lb.</li>
<li>NN: They were overfitting all the time, so we dropped them. The only exception was the MLPClassifier. It gave some boost (as a feature) to the xgboost.</li>
<li>Training on Full Data: it looks like diversity matters more here.</li>
<li>Pseudo Labeling and Postprocessing: Pseudo Labeling was not working at all. <br>
Regarding the postprocessing, we wanted to optimize for these a,b,c and d:</li>
</ul>
<pre><code>preds[preds < a] = b
</code></pre>
<pre><code>preds[preds > c] = d
</code></pre>
<p>So, we applied an interior StratifiedKFold inside our cv to find the best values (for the outer cv, we choose n_splits=5 to assure no duplication for the samples of the “0.5” class. For the interior cv, we use n_splits=4 for the same reason). But that wasn’t helpful in the end. I think the low number of samples at the edges was the challenge here.</p>
<p>Here is our code (it is a little messy though):<br>
<a href="https://www.kaggle.com/code/ihebch/linking-38th-place-solution-3rd-public?scriptVersionId=158358742" target="_blank">https://www.kaggle.com/code/ihebch/linking-38th-place-solution-3rd-public?scriptVersionId=158358742</a></p>
<p>We were just missing that gold to get to the Master tier, but let’s try harder next time.<br>
Thanks for reading!</p>
|
Linking Writing Processes to Writing Quality
|
5th Place Solution: Features are all you need!
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Linking Writing Processes to Writing Quality
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>I'd like to extend my thanks to Kaggle and the Learning Agency Lab for organizing such a fantastic competition. We've had a strong correlation between our cross-validation and leaderboard scores since the beginning, and all three selected submissions are in the gold range, which is quite reassuring.<br>
I would like to thank my teammates. <a href="https://www.kaggle.com/jaideepvalani" target="_blank">@jaideepvalani</a> <a href="https://www.kaggle.com/rohitsingh9990" target="_blank">@rohitsingh9990</a> <a href="https://www.kaggle.com/mori123" target="_blank">@mori123</a> <a href="https://www.kaggle.com/phoenix9032" target="_blank">@phoenix9032</a> for their contribution and working hard till the last minute.<br>
I'll try to briefly summarize what worked and what didn't.</p>
<p>I spent most of my time in feature engineering and the rest on making CV and LB reliable.</p>
<h1>Link to our inference notebook:</h1>
<p><a href="https://www.kaggle.com/code/chaudharypriyanshu/light-automl-lgbm-22/notebook" target="_blank">https://www.kaggle.com/code/chaudharypriyanshu/light-automl-lgbm-22/notebook</a></p>
<h1>Feature Engineering</h1>
<p>Most of the features are based on the question<br>
<strong>Q.</strong> "what exactly the evaluator is going to see ?"<br>
<strong>A.</strong> The essay text. So the most important features will be derived from it's structure.</p>
<p>So I created features with following categories:</p>
<ol>
<li>Paragraph lengths (first, second, third,…..): word counts and characters length , some cumulative length features.</li>
<li>Sentence lengths (first, second, third): word counts and characters length </li>
<li>Total capital letters in the text. </li>
<li>total nouns in the text (Total capital letters - total_sentences).</li>
<li>Count of words that are added unsequentially.</li>
<li>How many sentences start with same word (first word, first two word, first three words).</li>
<li>Time window based features : how many words added before (7/15/22/35) minutes.</li>
<li>Total commas count.</li>
<li>Tfidf features ngram (1,1), A total of 20 features.</li>
<li>More Punctuation statistics. Mostly count based.</li>
<li>Total questions and exclamation marks. </li>
<li>Total number of more than 1 character replacements. </li>
<li>Cursor positions based features, i used cursor positions that were there in reconstructed essay this way i found what was the actual standard deviation. how many times the author related the cursor with more than 1 positions.</li>
<li>Total action time to write words with certain length.</li>
<li>Rest of the features were adopted from public notebooks. </li>
</ol>
<h1>Modelling</h1>
<p>For modelling our team utilised 4 Neural Net, 1 1DCNN based, 3 Trees based models.</p>
<h3>Neural Networks</h3>
<p>Most of the neural networks are adopted from lightautoML shared in public notebook <a href="https://www.kaggle.com/code/alexryzhkov/lgbm-and-nn-on-sentences" target="_blank">here</a>.<br>
The architectures we used are:</p>
<h5>CV LB scores</h5>
<table>
<thead>
<tr>
<th>Models</th>
<th>cv</th>
<th>LB</th>
</tr>
</thead>
<tbody>
<tr>
<td>MLP</td>
<td>0.589</td>
<td>-</td>
</tr>
<tr>
<td>Denselight</td>
<td>0.590</td>
<td>-</td>
</tr>
<tr>
<td>Autoint</td>
<td>0.599</td>
<td>-</td>
</tr>
<tr>
<td>NODE</td>
<td>0.593</td>
<td>-</td>
</tr>
<tr>
<td>1DCNN</td>
<td>0.602</td>
<td>0.592</td>
</tr>
<tr>
<td>Ensemble</td>
<td>0.5868</td>
<td>0.582</td>
</tr>
</tbody>
</table>
<h5>Training Strategy:</h5>
<p>1) Light autoML models are trained for 10 epochs<br>
2) Since the results were a bit unstable, i used Stochastic weighted averaging and used best 3 validation scores (early stopping is used).<br>
3) Since the CV could have been over optimistic i have ensembles them separately from the models that were not using Early stopping.</p>
<h3>Gradient Boosters:</h3>
<h5>CV LB scores</h5>
<table>
<thead>
<tr>
<th>Models</th>
<th>cv</th>
<th>LB</th>
</tr>
</thead>
<tbody>
<tr>
<td>LGBM</td>
<td>0.598</td>
<td>0.580</td>
</tr>
<tr>
<td>CATBoost</td>
<td>0.6007</td>
<td>-</td>
</tr>
<tr>
<td>XGBoost</td>
<td>0.6001</td>
<td>-</td>
</tr>
<tr>
<td>Ensemble</td>
<td>0.5963</td>
<td>0.582</td>
</tr>
</tbody>
</table>
<h5>Training Strategy:</h5>
<p>1) Trained for 1500 iterations, no early stopping is used.</p>
<h1>Final CV setup</h1>
<p>1) Stratified KFold by scores.<br>
2) Trained for 5 seeds [42,2022,7,4,1]<br>
3) Seeds for all models and CV are kept same throught</p>
<h1>Ensembling</h1>
<p>1) we independently optimised the weights of NN and Trees and gave equal weights to both.<br>
2) Optuna is used to determine the weight of each model.<br>
Final CV score was 0.5858, LB = 0.578, Private = 0.560</p>
<h1>What we did to avoid shake down?</h1>
<ol>
<li>Use same seeds for ensemble</li>
<li>Not overfitting on cv, instead we tried to improve both cv and lb and average of both.</li>
<li>Added diversity by using various features sets since models trained on different features will deliver diverse results.</li>
<li>Separately ensembled the NN(used early stopping) and gradient boosters (do not use early stopping)).</li>
<li>Reducing the difference between CV-LB. Most important</li>
<li>training all models on same seeds.</li>
</ol>
<p>As a result</p>
<ul>
<li>By adopting this strategy 12 of our submissions out of top 15 reliable and updated solutions were in gold range for us.</li>
<li>All three final selected subs are under in gold range</li>
<li>Best CV sub= Best Private LB sub</li>
</ul>
<h1>What didn't work</h1>
<p>1) TFIDF for ngrams more than 1.<br>
2) Past competitions data like Feedback.<br>
3) Word2vec features.<br>
4) svd+tfidf.<br>
5) Timing window based essa structure features.</p>
<h1>Notebooks that helped us throughout the competition,</h1>
<p><strong>Please give them an upvote</strong><br>
1) <a href="https://www.kaggle.com/code/hiarsl/feature-engineering-sentence-paragraph-features" target="_blank">Feature Engineering: Sentence & paragraph features</a><br>
2) <a href="https://www.kaggle.com/code/alexryzhkov/lgbm-and-nn-on-sentences" target="_blank">LGBM and NN on sentences</a><br>
3) <a href="https://www.kaggle.com/code/awqatak/silver-bullet-single-model-165-features" target="_blank">Silver Bullet | Single Model | 165 Features</a><br>
4) <a href="https://www.kaggle.com/code/abdullahmeda/enter-ing-the-timeseries-space-sec-3-new-aggs" target="_blank">https://www.kaggle.com/code/abdullahmeda/enter-ing-the-timeseries-space-sec-3-new-aggs</a></p>
<p>I also experienced the same, for me below 0.58x correlation with LB was lost and I focused totally on making cv better. Features related to paragraphs worked well on CV but on LB there was no improvement, I had a strong instinct that they would work on private as they were improving CV for all models with no early stopping.</p>
<p>Hey, <a href="https://www.kaggle.com/xiaoyi" target="_blank">@xiaoyi</a>, last I checked, it was around 0.581, and CV was 0.605. It wasn't the best LGBM that we chose in our last sub. However, based on the trend we saw the best LB for our best LGBM would have been same.</p>
<p>Yes, we were not overfitting Public LB.</p>
<p>Not really, i had this in mind but i forgot😅. So we trained lgbm for 1000 - 1500 iteration. And saved the last iteration score.<br>
It is pretty much same as what was done here in this notebook Silver Bullet | Single Model | 165 Features.</p>
|
Linking Writing Processes to Writing Quality
|
77th Place Solution ! Quick Writeup
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Linking Writing Processes to Writing Quality
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>TLDR : My solution involves usage of Lightgbm models and LLAMA trained models like Denselight , Node , Tabnet . Along with this I also used Public Lgbm and LLAMA models and also fusion notebook part</p>
<p>Preprocessing :<br>
While training my own LGB and LLAMA models I removed the rows where the action time was unreasonably large and exceeding the allowed essay times</p>
<p>Feature Engineering :<br>
Same as public notebooks , I tried using some pause features but that didnt helped much relied on public notebooks for feature engineering since we had <= 3k labels and lot of features </p>
<p>Cross Validation Strategy:<br>
Same as did by Abhishek thakur here : <a href="https://www.kaggle.com/code/abhishek/same-old-creating-folds" target="_blank">https://www.kaggle.com/code/abhishek/same-old-creating-folds</a></p>
<p>Models:</p>
<ol>
<li>LGBM : Hyperparameter tuned using Optuna for all K folds</li>
<li>I trained Lightautoml's model Denselight , tabnet and Node , Thanks to <a href="https://www.kaggle.com/alexryzhkov" target="_blank">@alexryzhkov</a> and his notebooks on training lightautoml model</li>
</ol>
<p>Ensemble :</p>
<ol>
<li>Finetuned the model weights using optuna to find optimal weights of model for blending</li>
</ol>
<p>Final Notebook can be found here : <a href="https://www.kaggle.com/sayedathar11/lgbm-x2-nn-fusion-v8" target="_blank">https://www.kaggle.com/sayedathar11/lgbm-x2-nn-fusion-v8</a></p>
|
Linking Writing Processes to Writing Quality
|
81st Place Solution for the "Linking Writing Processes to Writing Quality" Competition
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Linking Writing Processes to Writing Quality
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h1>Context</h1>
<p>Business context: <a href="https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/overview" target="_blank">https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/overview</a><br>
Data context: <a href="https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/data" target="_blank">https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/data</a></p>
<h1>Overview of the Approach section</h1>
<p>My solution is based on the following public notebook from sources.<br>
In the public notebook, I have added new features related to the time between each action during "down_event," as shown in the following image. Specifically, I calculated the time for each action, including ".", "Enter," "Delete," "q," "Backspace," and "space," similar to the calculation for "Shift."<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F6684193%2F24bbbfe33aef6ce94e9e3485fbbc40d1%2Fsolution.png?generation=1704893662175726&alt=media" alt=""></p>
<h2>training</h2>
<p>I added these new features to the models of the following two sections in the source code I referred to."<br>
・LightAutoML+LightGBM:No change<br>
・Public LGBM:add new features<br>
・Writing Quality(fusion_notebook):add new features</p>
<h2>Result</h2>
<p>The Public score slightly worsened, but as the CV score showed a slight improvement, I chose to submit relying on the CV score.</p>
<p><strong>①original version</strong><br>
CV(Public LGBM)=0.61103, Public=0.578, Private=0.56886</p>
<p><strong>②add new features</strong><br>
CV(Public LGBM)=0.60714, Public=0.583, Private=0.568179</p>
<h1>Sources</h1>
<p>・<a href="https://www.kaggle.com/code/kononenko/lgbm-x2-nn-fusion" target="_blank">https://www.kaggle.com/code/kononenko/lgbm-x2-nn-fusion</a></p>
<p>thank you!</p>
|
Linking Writing Processes to Writing Quality
|
868th place, sharing my findings!
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Linking Writing Processes to Writing Quality
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Firstly, thanks to the organizers for hosting this competition and everyone who provided insights through discussions and code!</p>
<p>According to me, this was a tricky competition due to multiple reasons:</p>
<ul>
<li>Relatively small dataset, over optimizing on it would result in poor generalization</li>
<li>Imbalance in the number of samples per score range as pointed out <a href="https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/discussion/446665" target="_blank">here</a></li>
<li>Requires extensive understanding/ experimentation to create relevant features</li>
</ul>
<p>My approach was essentially a hill climbing ensemble of public notebooks - <a href="https://www.kaggle.com/code/mcpenguin/writing-processes-baseline-v2-lgbm-nn" target="_blank">LGBM +NN</a>, <a href="https://www.kaggle.com/code/awqatak/silver-bullet-single-model-165-features" target="_blank">Silver Bullet</a> and <a href="https://www.kaggle.com/code/cody11null/lgbm-x2-nn" target="_blank">Count Vectorizer Features</a> averaged over 5 seeds and 10-fold cross validation along with some feature engineering. Features obtained from essay reconstruction seemed quite important. Including additional features at word, sentence and paragraph level such as length based, frequency based aggregations improved CV and LB scores.<br>
It was interesting to see top solutions also ensemble public notebook solutions!</p>
<p><strong>What didn't work</strong></p>
<ul>
<li>Including classification models standalone, or combined in an ensemble with regressors as suggested <a href="https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/discussion/451852" target="_blank">here</a></li>
<li>Using augmentation inspired by <a href="https://www.kaggle.com/code/seoyunje/gan-with-tabular-data" target="_blank">GAN</a>, Random OverSampling, SMOTE. I first transformed the labels into categorical, applied SMOTE and later converted back to labels.</li>
<li>Adding key-based ratios such as keys_pressed_per_second, product_to_keys, IKI. Also, P-burst, R-bursts increased RMSE</li>
<li>Features based on Replace and Move activity such as statistics about text length etc.</li>
</ul>
<p>I had a decent CV of ~0.594 but ultimately experienced a bad shakeup in the private leaderboard. Nevertheless, it was an enriching experience and I hope to do better next time!</p>
|
Linking Writing Processes to Writing Quality
|
Bronze medal journey
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Linking Writing Processes to Writing Quality
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>First, thanks to organizers and Kaggle team for hosting such a great competition. It was a pleasure to see many amazing ideas and notebooks shared by contestants during the last several months. Since we all had some concerns about the grading subjectiveness, metric, distribution of private test data, etc. for this competition I decided to follow several independent approaches.</p>
<h1>1. Conservative model</h1>
<p>This model used selected features shared in the excellent <a href="https://www.kaggle.com/code/awqatak/silver-bullet-single-model-165-features" target="_blank">Silver Bullet</a> notebook. My improvements were</p>
<ul>
<li>streamlining CV scheme;</li>
<li>adding punctuation features (didn't work);</li>
<li>adding mouse events features (didn't work);</li>
<li>minor tuning of LightGBM model (worked on both CV and LB);</li>
<li>designing XGBoost model (worked on CV, but didn't translate to LB);</li>
<li>designing CatBoost model (worked on both CV and LB);</li>
<li>trying many other things like regularization, etc. (most of them didn't work, but some did).</li>
</ul>
<p>Model's public/private scores: 0.581/0.576.</p>
<h1>2. Advanced model</h1>
<p>This model was a blend of many LightGBM, XGBoost and NN models. Most of the models were highly tuned, some with grid search, some with Optuna. This model had my best public score and I was hoping it will also perform well on private LB due to its diversity.</p>
<p>Model's public/private scores: 0.577/0.570.</p>
<h1>3. Random model</h1>
<p>Since for this competition we could select upto three submissions, I just randomly <a href="https://www.kaggle.com/code/kononenko/lgbm-x2-nn-fusion" target="_blank">blended</a> two promising public notebooks. Ironically, this random blend performed best when going from public to private. It could even be in silver, if tuned a little bit more, but I didn't spend time on it as it was only a random guess.</p>
<p>Model's public/private scores: 0.578/0.568.</p>
<h1>Conclusion</h1>
<p>When the private LB was revealed, my rank dropped by ~100 places. Despite the decent shake-up, Model #3 appeared to be in bronze. However, what still puzzles me is why for all of my models, and also for many shared notebooks, <code>CV score > Public score > Private score</code>. Were hard cases manually moved to training data or this is just a coincidence?</p>
<p>Anyways, I would like to take an opportunity to thank again to host, Kaggle and community. It was a fun competition and I'm looking forward to the next ones.</p>
|
Linking Writing Processes to Writing Quality
|
Efficiency - 1st Place Solution
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Linking Writing Processes to Writing Quality
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>We would like to thank the hosts of the competition and the Kaggle platform, and everyone involved for organizing and running this competition. This has been a period of great learning experience for us. Special thanks to my teammate <a href="https://www.kaggle.com/Shindera" target="_blank">@Shindera</a>, who helped optimize our model during the competition.</p>
<h4>Summary</h4>
<p>We used a XGBoost model, which was the model with the best cross-validation and public test set results in our analysis. The notebooks reproducing our submission are as follows:</p>
<ul>
<li><a href="https://www.kaggle.com/code/lucaskna/lwptwq-fe-train-efficiency-1st-place" target="_blank">https://www.kaggle.com/code/lucaskna/lwptwq-fe-train-efficiency-1st-place</a></li>
<li><a href="https://www.kaggle.com/code/lucaskna/lwptwq-model-efficiency-1st-place" target="_blank">https://www.kaggle.com/code/lucaskna/lwptwq-model-efficiency-1st-place</a></li>
<li><a href="https://www.kaggle.com/code/lucaskna/lwptwq-test-inference-efficiency-1st-place" target="_blank">https://www.kaggle.com/code/lucaskna/lwptwq-test-inference-efficiency-1st-place</a></li>
</ul>
<h4>Feature Engineering and Modeling</h4>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F2732602%2Fd7357f75764aa9171f0165d7c7da344a%2FFEATURE_IMPORTANCE%20VERDADEIRO.png?generation=1705847433049724&alt=media"><br>
The model has 62 features. We have given a brief description of each feature at the end of the training notebook. </p>
<p>When analyzing features, we tried to include them in the model if they showed positive results in both cross-validation and the public test score. We also took into account the execution time, considering the trade-off between performance and efficiency. Stratified cross-validation was carried out using 10 folds of the dataset after excluding the data points, with an early stop after 100 rounds to determine the optimal number of iterations. The model is trained on all the data. We average the predictions over 50 seeds. </p>
<p>The parameters of the XGBoost model were adjusted by trial and error, based on the results of the cross-validation and the performance on the public test data. </p>
<p>Using Kaggle's notebook with CPU, we have the following approximate times: </p>
<ul>
<li>Importing data + Data pre-processing: 15 seconds.</li>
<li>Training feature creation + Essay reconstruction: 40 seconds.</li>
<li>Training models (50 seeds): 85 seconds. </li>
</ul>
<p>Although the code to create the training and prediction features in the test set differs slightly, the execution times should be close.</p>
<h4>Other remarks</h4>
<p>An important factor in reducing execution time was the use of functions from R's ‘stringi’ package. The code could be faster with a more efficient algorithm for reconstructing essays and getting more from the 'data.table' package.</p>
|
Linking Writing Processes to Writing Quality
|
Exciting roller coaster
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Linking Writing Processes to Writing Quality
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Firstly, thank you to the organizers for organizing this competition</p>
<p>As you can see, on the public list, our team is capable of winning a silver medal, but on the private list, it suddenly drops by over 700. It's really like riding a roller coaster</p>
<p>I think the best notebook in our team should be this open-source one <a href="https://www.kaggle.com/code/yunsuxiaozi/writing-quality-fusion-notebook" target="_blank">https://www.kaggle.com/code/yunsuxiaozi/writing-quality-fusion-notebook</a> After that, although I improved a bit by integrating more notebooks, I felt that the code lacked aesthetics</p>
<p>The data volume of this competition is small, so it can be seen that some teams have increased by a few hundred places, while others have decreased by a few hundred places, which is really exciting</p>
<p>Through this competition, I have also learned a lot and look forward to meeting you all in the next competition.</p>
|
Linking Writing Processes to Writing Quality
|
No 😞 place solution
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Linking Writing Processes to Writing Quality
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thank you <a href="https://www.kaggle.com/kaggle" target="_blank">@kaggle</a> and The Learning Agency Lab for hosting another competition. </p>
<p><em>Congratulations 🎉 to my teammate <a href="https://www.kaggle.com/sid00733" target="_blank">@sid00733</a> on becoming Kaggle Competitions Master 🏆</em></p>
<hr>
<p><strong>Context</strong></p>
<p><strong>Business context:</strong> <a href="https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/overview" target="_blank">https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/overview</a></p>
<p><strong>Data context:</strong> <a href="https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/data" target="_blank">https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/data</a></p>
<p><strong>Overview of the approach</strong><br>
Our selected submission consisted of </p>
<ul>
<li>LightGBM (cv 0.5959)</li>
<li>Many other types of NN models (cv 0.59)</li>
<li>Simple MLP NN model (cv 0.6125) </li>
<li>Public Kernel with minor changes - changing folds to match ours, adding few more features. (cv 0.6058) - Catboost and LGBM (XGB had 0 weight) Thank you <a href="https://www.kaggle.com/awqatak" target="_blank">@awqatak</a> and <a href="https://www.kaggle.com/snnclsr" target="_blank">@snnclsr</a> for a well organized notebook. </li>
</ul>
<p>Overall ensemble cv 0.5866 and pvt. LB 0.561 public LB 0.575</p>
<p><strong>Cross validation</strong><br>
Kfold - 10 folds <br>
Many of our models were built with multiple seeds but folds remained the same</p>
<p><strong>Feature Engineering</strong><br>
Shout out to my teammates <a href="https://www.kaggle.com/sid00733" target="_blank">@sid00733</a> and <a href="https://www.kaggle.com/kanbehmw" target="_blank">@kanbehmw</a> for brilliant feature engineering 🏅🏅🏅</p>
<ul>
<li>Volatility features - change of % in activity over time.</li>
<li>P-Burst - (R-burst didn’t work) </li>
<li>Count vectorizer features</li>
<li>TF-IDF features with characters and ngram(4,4) i.e. 4 character words </li>
<li>Essay features - word level, bigrams, trigrams </li>
<li>Sentence, paragraph features with essays </li>
<li>IDF features for activity, events and text changes </li>
<li>Sequential features for Input, Non-Production and Remove/Cut activities </li>
<li>IKI features (IWI features didn’t work) </li>
<li>KeyStrokes features</li>
<li>Change in Typing Speed Features(WPM)</li>
<li>Feature selection using BorutaPy only on TF-IDF and CountVectorizer features</li>
</ul>
<p><strong>NN Models</strong> <br>
In our neural network pipeline, we've implemented a multi-faceted approach for processing a dataset with 1356 features, incorporating different types of feature scaling and complex neural network architectures:</p>
<p><em>Feature Scaling:</em><br>
For float columns, we applied three types of scalers: Robust Scaler, Standard Scaler, and Power Transformation Scaler, each tailored to normalize the data considering different aspects of distribution.<br>
For integer columns, MinMaxScaler was used to ensure the values are within a specific range.</p>
<p><em>Neural Network Architectures:</em></p>
<ul>
<li>First NN Model: It's a hybrid model combining a 1D CNN with LSTM, GRU, RNN, and a Transformer encoder. The output is a weighted average from these models, aiming to capture both spatial and temporal relationships in the data.</li>
<li>Second NN Model: This layer employs LSTM and RNN with a self-attention mechanism. It starts by embedding the sequences, then processes them through bidirectional LSTM and unidirectional RNN, applying self-attention to each before integrating the results.</li>
<li>Third NN Model: Similar in structure to the second layer but replaces the RNN with a unidirectional GRU, again using self-attention and integrating the outputs.<br>
The different configurations achieved a cross-validation score of 0.590 locally and 0.568 on a private leaderboard.</li>
</ul>
<p><strong>Ensemble:</strong><br>
We picked weights manually. We tried NelderMead as well as stacking with Ridge, but our final selection was hand picked weights. One of the reasons ensemble with Ridge/NelderMead didn’t work is because of disparate models and their scores. NN models had low cv but high public LB whereas LGBM models had comparable (to NN) or higher CV but much better public LB. Ridge/NelderMead would assign higher weight to NN models (with lower cv) which didn’t work on public LB. <br>
Since public LB was 50% of test set, we manually picked weights - 65% for LGBM models and 35% for NN Models</p>
<p><strong>Post processing</strong> <br>
We rounded values in range (3.95,4.05) to 4.0 and (3.45,3.55) to 3.5 . Other possibilities of rounding didn’t work. Also clipped predictions to (0.5,6.0) </p>
<p><strong>Other attempts</strong></p>
<ul>
<li>Creating Model over different time event 0-10, 10-20, 20-30 minutes and using this model oof on overall models, It was best single model but dropped due to bad performance on public LB(CV - 0.591, PL - 0.582, PVTLB - 0.563) </li>
<li>Classification models to use in final regression models</li>
<li>mouse events features</li>
<li>VotingRegressor notebook, it worked well with our ensemble but it was not part of our best private submission</li>
<li>Experimented with Meta Pseudo Labels (inspired by GANs) and incorporating DeBERTa v3 XSmall embeddings, but these approaches did not improve the local CV score.</li>
<li>LGB custom loss functions </li>
</ul>
<p><strong>Acknowledgments</strong><br>
Many good public kernels shared in this competition by <a href="https://www.kaggle.com/kawaiicoderuwu" target="_blank">@kawaiicoderuwu</a> for Essay Constructor which we used as is, 165 features by <a href="https://www.kaggle.com/awqatak" target="_blank">@awqatak</a>. I found IDF features here quite fascinating by <a href="https://www.kaggle.com/olyatsimboy" target="_blank">@olyatsimboy</a>. Apologies if I missed crediting original work, considering there were many similar kernels. <br>
Also big thank you to my teammates - <a href="https://www.kaggle.com/aman1391" target="_blank">@aman1391</a>, <a href="https://www.kaggle.com/fightingmuscle" target="_blank">@fightingmuscle</a>, <a href="https://www.kaggle.com/sid00733" target="_blank">@sid00733</a> and <a href="https://www.kaggle.com/kanbehmw" target="_blank">@kanbehmw</a> 🙏</p>
<p>Thank you, <a href="https://www.kaggle.com/aman1391" target="_blank">@aman1391</a> did this part ! </p>
|
Linking Writing Processes to Writing Quality
|
Place 46 Solution, Place 11 Efficiency
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Linking Writing Processes to Writing Quality
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks! I want to clarify that the efficiency one is not sure yet, the X is a placeholder, as efficiency LB is not updated, but I think I might end up in the top 10, my efficiency sub runs 0.571 in a little bit under 2 minutes if I stopped the time right :D</p>
<p>Edit 1: Place in efficiency track -> 11</p>
<h1>Preface</h1>
<p>I'm really happy that I survived the shakeup and look forward to also see the results for the efficiency track!</p>
<p>I first want to thank everyone involved in this competition, especially the collaborative spirit of the community is always great to see! In the competition I've focused both on the efficiency and performance track, as I’ve had good experience with this approach in a previous one, so I’ll discuss both in one write-up. </p>
<h1>Solutions</h1>
<p><strong>Performance Track Place 46:</strong><br>
My final submission was mostly an ensemble of public notebooks. One addition I introduced was the transformer Deberta-v3-xsmall on reconstructed essays. The ensemble of public notebooks got me to 0.577 Public LB, the transformer got me to 0.576 LB and improved CV a lot.</p>
<p><em>Ensemble</em><br>
The ensemble included a blend of models from public notebooks and the transformer: <a href="https://www.kaggle.com/code/seoyunje/gan-with-tabular-data" target="_blank">Voting Regressor</a>, <a href="https://www.kaggle.com/code/kononenko/lgbm-x2-nn-fusion" target="_blank">Fusion</a>, <a href="https://www.kaggle.com/code/seoyunje/gan-with-tabular-data" target="_blank">GAN</a>, and a Transformer. The final prediction was a weighted average of these models, carefully balanced to optimize performance.</p>
<p><code>
y_pred_ensemble = vote_pred * 0.45 + gan_pred * 0.05 + transformer_pred * 0.15 + automl_pred * 0.05 + biglgb_pred * 0.05 + hugelgb_pred * 0.15 + fusion_pred * 0.1
</code></p>
<p><em>Transformer</em><br>
The approach here was to create essays, find common anonymized words and add them to a tokenizer, then train the model. I froze the first 6 of 12 layers of Deberta-v3-xsmall, but not the token embeddings, as the new tokens do not have useful embeddings at initialization. The implementation was inspired by a <a href="https://www.kaggle.com/code/tsunotsuno/updated-debertav3-lgbm-with-spell-autocorrect" target="_blank">popular notebook from a previous competition</a>. I only trained the model on the few texts given for the competition, but I think one might have improved this a lot by pretraining the q embeddings on different anonymized texts (not done due to time constraints and it would also miss the point of the competition a bit to be fair).</p>
<pre><code>important_anon_words = {word: count word, count word_counts.items() count > }
important_anon_words = {k: v k, v important_anon_words.items() (k) > }
tokenizer.add_tokens((important_anon_words))
inputs = tokenizer(, return_tensors=)
(, tensor([[ , , , , , , , , , , , ]]))
(, tensor([[ , , , , ]]))
</code></pre>
<p><strong>Efficiency Track Place 11:</strong><br>
Here I deployed a 5 fold x 5 model ensemble using CatBoost, XGB, LGBM, linear SVR, Ridge. Pretty similar to the Voting Regressor in the end with some differences in features and model selection. It runs in under 2 minutes.</p>
<p><em>Timing</em><br>
A significant amount of time was taken up by feature loading, with a focus on optimizing the selection of features for better efficiency. I used the <a href="https://www.kaggle.com/code/awqatak/silver-bullet-single-model-165-features" target="_blank">Silver Bullet features</a>, throwing out less relevant features based on LGB feature importance across CV folds. Only a few seconds in inference are used on model running. </p>
<p>I noticed that this time every second counts, based on observed differences in efficiency LB. I think that they took something like a 0 submission for base calculation which would make the difference between 580 and 579, if minimum score is 570:</p>
<p>First part of Efficiency equation: (580-579)/(3700-560) => 0.001 point on LB is worth around 1/3140 score in this case, same as around 10 seconds runtime based on second part of Efficiency equation!<br>
I've got 571 on private test with my 2 minute submission so really hope it will be enough for a good place!</p>
<p><em>Cross Validation</em><br>
I ended up using a 5 fold CV on half of data and then used the other half as test set (switching around). This way you can use early stopping and see performance gains from ensembling over folds, while still seeing performance on an unbiased set, when training the final models for inference you can then switch to using all data for training.</p>
<p><em>Post Processing and Distribution Shift</em><br>
Some things improved CV by a lot, like the addition of ridge or linear SVR to an ensemble of gradient boosting models, but did not translate to great improvements on LB. </p>
<p>I think the reason might be a distribution shift to test set, which is probably harder to handle for regression models. They are not automatically capped to one range by default. You can see them predicting negative numbers on CV sometimes for example. I tried post processing with both tracks to alleviate some of these issues, but nothing worked really well sadly. I hope this will clear up once more write-ups appear!</p>
<h1>Takeaways</h1>
<p>Good cross validation is really important, I tapped in the dark a lot in the beginning.<br>
Teaming up to cover more ground would have been good, I saw myself not able to pursue lots of good avenues, I hoped I could get solo gold for GM as I was really optimistic but that was probably a missed team gold instead.</p>
|
Linking Writing Processes to Writing Quality
|
Private 20th Solution
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Linking Writing Processes to Writing Quality
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Congratulations 3rd prize!</p>
<p>This is notebook of deberta-part (infer: <a href="https://www.kaggle.com/code/takai380/typing-debertav3-baseline-infer" target="_blank">https://www.kaggle.com/code/takai380/typing-debertav3-baseline-infer</a>)</p>
<p>I may also share the code for the training if necessary, but there are two specific points that are noteworthy:</p>
<p>I converted consecutive 'q's into numerical values; this was essential for working.<br>
I initialized the top (n=2) layers of BERT; this resulted in a slight improvement.<br>
Other than these, there are no significant changes that have a substantial impact!</p>
<p>The result was 20th place with a solo silver medal. Thank you to the organizers. My solution consists of two parts: a decision tree-based solution with feature engineering (almost identical to the public notebook) and a BERT model that predicts from reconstructed text.<br>
Feature Engineering: (I will omit this part as it is similar to the public notebook.)<br>
I used features similar to the public notebook, which include:<br>
Text Features:<br>
char_num<br>
Sentence statistics<br>
Paragraph statistics<br>
Punctuation statistics<br>
\n statistics<br>
\n\n statistics<br>
etc.<br>
Event Log Features:<br>
Count and nunique max min fe<br>
Statistical aggregations for all numerical columns<br>
P and R burst fe<br>
Pause-time agg<br>
BERT Part:<br>
Before using this model, I referred to the following notebook for preprocessing (<a href="https://www.kaggle.com/code/kawaiicoderuwu/essay-contructor" target="_blank">https://www.kaggle.com/code/kawaiicoderuwu/essay-contructor</a>) and reconstructed the text. Thank you for the excellent notebook.<br>
Before handling the BERT model, text preprocessing is performed. For example:<br>
qqqq qq qqqq (qq qqqqq qq). q'q q qqqqqq qqqqqq.<br>
4 2 4 (2 5 2). 1'1 1 6 6.<br>
Continuous 'q's are converted to consecutive numbers.<br>
Then, it is trained. This allows prediction based on the sequence of consecutive word counts and features of various symbols (.,;: () '! \n \n\n, etc.).<br>
Even if you use the public notebook as it is, the Private LB goes from 0.568 to 0.565.<br>
model:<br>
deberta-v3-base<br>
deberta-xlarge<br>
The predictions of these models were ensembled with weights.</p>
<p>Congratulations on the gold medal at the 5th position! I look forward to seeing your approach.</p>
<p>5 stratified-k-fold</p>
<p>deberta-v3-base:<br>
CV: 0.603 Pub: 0.600 Pri: 0.588</p>
<p>deberta-xlarge:<br>
CV: 0.600 Pub: 0.598 Pri: 0.578</p>
|
Linking Writing Processes to Writing Quality
|
[14th place solution] Keras ensemble
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Linking Writing Processes to Writing Quality
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>First of all, I would like to thank the organizers for organizing this competition.<br>
Thanks also to all the kagglers who shared information in notebooks and discussions.<br>
My model could not score better than the public notebook, but by ensemble I was able to improve the public notebook's score a bit.<br>
This is my first medal and I am very happy!</p>
<h1>Preprocessing</h1>
<p>I did some data cleaning.<br>
For example, during holding down SHIFT, even if nothing changed, it seemed be counted as a new event about every 30ms, so combined them into one.</p>
<h1>Feature engineering(similar to the public notebook)</h1>
<p>I created 69 features from essay, 90 features from train_logs aggregation and binning on idol_time and essay-related columns.<br>
(really appreciate <a href="https://www.kaggle.com/kawaiicoderuwu" target="_blank">@kawaiicoderuwu</a> for shareing <a href="https://www.kaggle.com/code/kawaiicoderuwu/essay-contructor" target="_blank">essay constructor</a>)<br>
I used nltk.tokenize to split the essay and then addressed grammatical errors such as sentences connected or single symbol left.</p>
<h1>Models</h1>
<p>ensemble of LightGBM, XGBoost and Keras<br>
10-KFold, tuned with optuna<br>
(single LightGBM | CV: 0.597, Public LB: 0.593, Private LB: 0.574)<br>
(single XGBoost | CV: 0.597, didn't submit)</p>
<h1>Keras model</h1>
<p>simple 3-4 layers model<br>
Score was scaled between (-1, 1) and output by softsign or tanh.<br>
Performance of single keras was poor, but ensemble with GBDT model improved LB scores.<br>
(single keras | CV: 0.620, Public LB: 0.605, Private LB: 0.577)<br>
Stacking and classification did not work.<br>
Since few people were using keras, it was probably just luck, probably not originally suited for this competition.</p>
<h1>Ensemble</h1>
<p>I used the following notebook for ensemble.<br>
Thanks so much for sharing!<br>
<a href="https://www.kaggle.com/code/kononenko/lgbm-x2-nn-fusion" target="_blank">LGBM (X2) + NN + Fusion</a> by <a href="https://www.kaggle.com/kononenko" target="_blank">OLEKSIY KONONENKO</a><br>
<a href="https://www.kaggle.com/code/yunsuxiaozi/writing-quality-fusion-notebook" target="_blank">Writing Quality(fusion_notebook)</a> by <a href="https://www.kaggle.com/yunsuxiaozi" target="_blank">YUNSUXIAOZI</a><br>
<a href="https://www.kaggle.com/code/cody11null/lgbm-x2-nn" target="_blank">LGBM (X2) + NN</a> by <a href="https://www.kaggle.com/cody11null" target="_blank">CODY_NULL</a></p>
<p>Finally I blended my model and (LGBM (X2) + NN + Fusion) in 3:7 or 4:6 ratio.<br>
My final Private LB Score was 0.564197, blended (keras_softsign * 0.25) + (keras_tanh * 0.05) + (LGBM (X2) + NN + Fusion * 0.7)</p>
<h1> </h1>
<p>Thank you to everyone who shared information in notebook and discussions!<br>
Thank you for reading!</p>
<p>Thank you for comment!<br>
Here is the code.</p>
<pre><code>early_stopping = EarlyStopping(=, =8, =0)
model = Sequential([
BatchNormalization(),
Dense(43, =),
Dropout(0.38013463195135017),
Dense(7, =),
Dropout(0.31511780144407464),
Dense(1, =)])
model.compile(=, =, =)
history = model.fit(
X_train, y_train, validation_data=(X_valid, y_valid),
=64, =32, =0, callbacks=[early_stopping])
</code></pre>
<p>Layer's units and dropout-rate are tuned by optuna, the number of epochs was adjusted by visualizing history.<br>
After 5 iterations of 10-KFold with the same seed(42), I submitted an average of 50 times.</p>
<p>Thank you for comment!<br>
After I created my lightgbm model, I added some features based on the public notebook, but the feature selection was based on my own CV, which may have been a good thing.<br>
It was just lucky for me to get a good score on Private LB more than expected.</p>
<p>Thank you for comment!<br>
Actuality, there were not enough days left after I had completed the model. (This is why I didn't submit the single XGB model.)<br>
I felt that the keras model was a good for ensemble, so made the ratio larger.<br>
There was no particular statistical basis for the decision, it was made by hand.</p>
|
Linking Writing Processes to Writing Quality
|
[1st place solution] Data Cleaning+FE+External Data+Model Ensemble
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Linking Writing Processes to Writing Quality
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>It is just because the minimum score in train dataset is 0.5. There can be essay with score 0 in hidden test dataset, but I didn't trust extrapolation ability of the models.</p>
<p>[Note for latecomers] My rank was originally 2nd, but finalized to be 1st due to <a href="https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/discussion/469199" target="_blank">some reasons</a>. I believe <a href="https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/discussion/467154" target="_blank">the original 1st place solution</a> is still worth reading.</p>
<h1>Thank You Everyone!</h1>
<p>I'd like to thank the organizers and all participants. This is my first solo gold and monetary prize in four years of kaggle experience. I am so happy with it 🤩. </p>
<p>The training and inference code is available <a href="https://www.kaggle.com/code/tomooinubushi/2nd-place-solution-training-and-inference-code" target="_blank">here</a>. This code includes so many redundant and/or unnecessary parts, but I opened it as is to avoid additional errors.</p>
<h1>Solution summary</h1>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F3754725%2Ff49ce3374a234e1333b60bd5b6067eb9%2FMicrosoft%20PowerPoint%20.jpg?generation=1704865612111526&alt=media" alt="Summary of my solution"></p>
<h1>Data cleaning</h1>
<p>In the era of deeplearning, data cleaning is one of the most under-emphasized parts of DS/ML. Since the training dataset of this competition is very small, I conducted data cleaning to reduce noises in train and unseen test dataset.</p>
<p>In summary, I conducted….</p>
<ul>
<li>Discard events ten minutes before first input.</li>
<li>Correct up times from zero and consistently increasing (see <a href="https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/discussion/447238" target="_blank">this discussion</a>).</li>
<li>Correct up times and down times so that gap times and action times are not too large (ten minutes and five minutes, respectively).</li>
<li>Fix unicode errors in up events, down events, and text change columns with <a href="https://ftfy.readthedocs.io/en/latest/#" target="_blank">ftfy</a> fix texts. <a href="https://www.kaggle.com/code/tomooinubushi/reduce-unseen-test-events-with-ftfy" target="_blank">It reduced unseen up events (29 -> 24) and down events (30 -> 26)</a> revealed by <a href="https://www.kaggle.com/kononenko" target="_blank">@kononenko</a> in <a href="https://www.kaggle.com/code/kononenko/lwp-unseen-test-activities-events" target="_blank">this notebook</a></li>
<li>Discard events with Unidentified (see user ID 2f74828d)</li>
</ul>
<h1>Sentence reconstruction and feature engineering</h1>
<p>The first thing I did in this competition is to reconstruct sentences from keyboard activities. Since the scores are determined solely based on final text, I thought this is the most important point in this competition.<br>
<a href="https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/discussion/447735" target="_blank">This very early discussion topic</a> by <a href="https://www.kaggle.com/kawaiicoderuwu" target="_blank">@kawaiicoderuwu</a> and <a href="https://www.kaggle.com/code/jasonheesanglee/updated-75-35-acc-revealing-hidden-words?scriptVersionId=148517101" target="_blank">this public notebook</a> by <a href="https://www.kaggle.com/jasonheesanglee" target="_blank">@jasonheesanglee</a> were very helpful for me.<br>
For better reconstruction, I improve some points.</p>
<ul>
<li>If cursor position and text change information do not match with reconstructed text, search sequence with nearest fuzzy match.</li>
<li>Correct Undo (ctrl+Z) operation if cursor position and text change information do not match with reconstructed text</li>
</ul>
<p>I did my best, but there are still 142 events with unexpected errors in training logs.</p>
<p>For feature engineering, <a href="https://www.kaggle.com/code/hengzheng/link-writing-simple-lgbm-baseline" target="_blank">this public notebook</a> by <a href="https://www.kaggle.com/hengzheng" target="_blank">@hengzheng</a> was a good starting point. Learning from other notebook (especially this <a href="https://www.kaggle.com/code/awqatak/silver-bullet-single-model-165-features" target="_blank">public notebook</a> by <a href="https://www.kaggle.com/awqatak" target="_blank">@awqatak</a> was so impressive!), I used 378 features in total.<br>
In summary, I used….</p>
<ul>
<li>Stats of Inter Key Latency, Press Latency, and Release Latency with gap 1</li>
<li>Total counts of each activity and event</li>
<li>Time to first reach 200, 300, 400, and 500 words</li>
<li>Pause related features</li>
<li>Word-time ratio, word-event ratio, etc.</li>
<li>Stats of reconstructed text (e.g., words per sentence, word length etc.)</li>
<li>Total counts of punctuation errors in reconstructed text (e.g., sequence like "qq qqq ,qqq" should be "qq qqq, qqq", and "qq qqq .qqq" should be "qq qqq. Qqq")</li>
<li>Pause and revision burst related features.</li>
<li>Tf-idf features of activities, events, and categorized Inter Key Latency.</li>
<li>Word-level and char-level tf-idf features of reconstructed text</li>
<li>Predictions of external essay scores based on word-level and char-level tf-idf features (explain later)</li>
</ul>
<p>Once tf-idf features are extracted, I used truncated SVD to reduce their dimensions to 64.</p>
<p>Here is a (part of) feature importance plot of light GBM, though I never checked it throughout this competition <br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F3754725%2F5baca557e7cfa1525fdeeed4412b989b%2Foutput_.png?generation=1704957648886814&alt=media"></p>
<h1>Use external data</h1>
<p>As the training dataset is very small, I used external data about essay evaluation. I anonymized all essays and extracted tf-idf features with the same feature extractor with the training dataset. Then, I trained light GBM models to predict external scores. <br>
The below scatter plot is the result of the model trained with <a href="https://www.kaggle.com/c/commonlit-evaluate-student-summaries" target="_blank">commonlit-evaluate-student-summaries</a> data. </p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F3754725%2Fb8d576705b1ce7b1f1ac6ef7da8c5a76%2Foutput.png?generation=1704865890059267&alt=media"><br>
To my surprise, the predicted external scores (x-axis) are well correlated with the scores of this competition (y-axis). Please note that light GBM models are trained only with anonymized external essays. I use these predicted external scores as features to increase generalizability of the models. I tried transformer models (e.g., deverta-v3), but they are never better than tf-idf+light GBM models.</p>
<p>I used eight datasets composed of 24 essay types.</p>
<ul>
<li><a href="https://www.kaggle.com/c/commonlit-evaluate-student-summaries" target="_blank">https://www.kaggle.com/c/commonlit-evaluate-student-summaries</a></li>
<li><a href="https://www.kaggle.com/competitions/asap-aes" target="_blank">https://www.kaggle.com/competitions/asap-aes</a></li>
<li><a href="https://www.kaggle.com/competitions/asap-sas" target="_blank">https://www.kaggle.com/competitions/asap-sas</a></li>
<li><a href="https://huggingface.co/datasets/whateverweird17/essay_grade_v1" target="_blank">https://huggingface.co/datasets/whateverweird17/essay_grade_v1</a></li>
<li><a href="https://huggingface.co/datasets/whateverweird17/essay_grade_v2" target="_blank">https://huggingface.co/datasets/whateverweird17/essay_grade_v2</a> (from <a href="https://www.kaggle.com/competitions/llm-detect-ai-generated-text/discussion/453372" target="_blank">this discussion</a> by <a href="https://www.kaggle.com/thedrcat" target="_blank">@thedrcat</a>)</li>
<li><a href="https://www.kaggle.com/competitions/feedback-prize-english-language-learning/overview" target="_blank">https://www.kaggle.com/competitions/feedback-prize-english-language-learning/overview</a></li>
<li><a href="https://www.kaggle.com/datasets/mazlumi/ielts-writing-scored-essays-dataset" target="_blank">https://www.kaggle.com/datasets/mazlumi/ielts-writing-scored-essays-dataset</a></li>
<li><a href="https://www.kaggle.com/datasets/nbroad/persaude-corpus-2/" target="_blank">https://www.kaggle.com/datasets/nbroad/persaude-corpus-2/</a></li>
</ul>
<p>I also tried <a href="https://www.cs.cmu.edu/~keystroke/" target="_blank">keystroke dataset</a>, but never worked.</p>
<h1>Construct various models and ensemble them</h1>
<p>Using both tree and NN models is important to improve the score. I learned light autoML in this <a href="https://www.kaggle.com/code/alexryzhkov/lgbm-and-nn-on-sentences" target="_blank">public notebook</a> by <a href="https://www.kaggle.com/alexryzhkov" target="_blank">@alexryzhkov</a>. For classifier models, I used the framework shown in <a href="https://www.kaggle.com/code/alexryzhkov/lgbm-and-nn-on-sentences" target="_blank">this discussion</a></p>
<table>
<thead>
<tr>
<th>Model</th>
<th>CV</th>
<th>public LB</th>
<th>private LB</th>
</tr>
</thead>
<tbody>
<tr>
<td>LGBRegressor</td>
<td>0.576</td>
<td>0.576995 (late submission)</td>
<td>0.558459 (late submission)</td>
</tr>
<tr>
<td>LGBClassifier</td>
<td>0.582</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
<td>XGBRegressor</td>
<td>0.580</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
<td>XGBClassifier</td>
<td>0.583</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
<td>CatBoostRegressor</td>
<td>0.582</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
<td>BaggingRegressor</td>
<td>0.594</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
<td>tabnet</td>
<td>0.609</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
<td>light autoML densenet</td>
<td>0.593</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
<td>light autoML resnet</td>
<td>0.587</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
<td>light autoML fttransformer</td>
<td>0.603</td>
<td>-</td>
<td>-</td>
</tr>
</tbody>
</table>
<p>Ensemble</p>
<table>
<thead>
<tr>
<th>Model</th>
<th>CV</th>
<th>public LB</th>
<th>private LB</th>
</tr>
</thead>
<tbody>
<tr>
<td>LinearRegressor</td>
<td>0.572</td>
<td>0.579468 (late submission)</td>
<td>0.557741 (late submission)</td>
</tr>
<tr>
<td>LogisticClassifier</td>
<td>0.575</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
<td>Mean</td>
<td>0.573</td>
<td>0.578796</td>
<td>0.559289</td>
</tr>
</tbody>
</table>
<p>For ensembling, I also tried forward ensembling shown in <a href="https://www.kaggle.com/code/cdeotte/forward-selection-oof-ensemble-0-942-private" target="_blank">this public notebook</a>. Actually, forward ensembling gave me better public LB score of 0.575, but CV (0.575) and private LB score (0.560) were worse. I used nested CV of six bags x five folds stratified with score for final submission.</p>
<h1>Postprocessing</h1>
<p>I just clipped predictions from 0.5 to 6.0. Rounding to 0.5, 1.0… never worked.</p>
<h1>Some remarks</h1>
<p>Unlike <a href="https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/discussion/444947" target="_blank">many people in the CV-LB thread</a>, my LB scores were always worse than CV scores. <a href="https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/discussion/456467" target="_blank">As I have shown that score distribution of public LB dataset is similar to that of train set</a>, I always trust CV score in this competition.<br>
Since I decided to use external data which impose extra inference time, I gave up efficiency prize. I selected three GPU models for submission. From these three models, the winning one is the model with the worst public LB score (0.578). Though I did my best for model generalizability, I have to admit that I am too lucky 😅. </p>
<p>I learned a lot from many public notebooks and discussions. I listed them below, but there would be some missing ones.</p>
<ul>
<li><a href="https://www.kaggle.com/code/hengzheng/link-writing-simple-lgbm-baseline" target="_blank">https://www.kaggle.com/code/hengzheng/link-writing-simple-lgbm-baseline</a></li>
<li><a href="https://www.kaggle.com/code/dangnguyen97/feature-eng-clean-outlier-lgbm-with-optuna#Train-OOF-LGBM-Models" target="_blank">https://www.kaggle.com/code/dangnguyen97/feature-eng-clean-outlier-lgbm-with-optuna#Train-OOF-LGBM-Models</a></li>
<li><a href="https://www.kaggle.com/code/ulrich07/tabpfn-and-xgboost-cv-0-19-lb-0-17" target="_blank">https://www.kaggle.com/code/ulrich07/tabpfn-and-xgboost-cv-0-19-lb-0-17</a></li>
<li><a href="https://www.kaggle.com/code/awqatak/silver-bullet-single-model-165-features" target="_blank">https://www.kaggle.com/code/awqatak/silver-bullet-single-model-165-features</a></li>
<li><a href="https://www.kaggle.com/code/hiarsl/feature-engineering-sentence-paragraph-features" target="_blank">https://www.kaggle.com/code/hiarsl/feature-engineering-sentence-paragraph-features</a></li>
<li><a href="https://www.kaggle.com/code/jasonheesanglee/updated-75-35-acc-revealing-hidden-words" target="_blank">https://www.kaggle.com/code/jasonheesanglee/updated-75-35-acc-revealing-hidden-words</a></li>
<li><a href="https://www.kaggle.com/code/alexryzhkov/lgbm-and-nn-on-sentences" target="_blank">https://www.kaggle.com/code/alexryzhkov/lgbm-and-nn-on-sentences</a></li>
<li><a href="https://www.kaggle.com/code/abdullahmeda/enter-ing-the-timeseries-space-sec-3-new-aggs" target="_blank">https://www.kaggle.com/code/abdullahmeda/enter-ing-the-timeseries-space-sec-3-new-aggs</a></li>
<li><a href="https://www.kaggle.com/code/cdeotte/forward-selection-oof-ensemble-0-942-private" target="_blank">https://www.kaggle.com/code/cdeotte/forward-selection-oof-ensemble-0-942-private</a></li>
<li><a href="https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/discussion/447238" target="_blank">https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/discussion/447238</a></li>
<li><a href="https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/discussion/457385" target="_blank">https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/discussion/457385</a></li>
<li><a href="https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/discussion/444905" target="_blank">https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/discussion/444905</a></li>
<li><a href="https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/discussion/447735" target="_blank">https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/discussion/447735</a></li>
<li><a href="https://www.kaggle.com/competitions/llm-detect-ai-generated-text/discussion/453372" target="_blank">https://www.kaggle.com/competitions/llm-detect-ai-generated-text/discussion/453372</a> </li>
</ul>
<p>Thank you for your comment. I quickly checked it, and here are the results.<br>
baseline CV: 0.5835446419837841<br>
baseline + tfidf CV: 0.5777270030350793<br>
baseline + external pred CV: 0.5813589302419466<br>
baseline + tfidf + external pred CV: 0.5769709134914177</p>
<p>Essay related features 1 are tfidf features of reconstructed essays from the competition data, while essay related features 2 are tfidf features of anonymized essays from the external data. <br>
It is feature extraction, rather than data synthesis.</p>
<p>External data is only used for training the light GBM models in step 1. I didn't use these data for step 2 and 3.<br>
Step 1 and step 3 correspond to 'External data trained light GBM' and 'Various models', respectively in the first schema figure.<br>
I tried deberta models, but it was not successful. It would be due to the lack of my skill.</p>
<p>I believe the idea to use external data must be the key, because only the 1st, 2nd, and 4th teams did so, as far as I saw. <br>
I expected that it would add generalizability to my model and should cause some shakeup, but never expected to be 2nd 😆.</p>
<p>Thank you for your comment. I did following things.</p>
<ol>
<li>Trained light GBM models with tfidf features of anonymized essays and their scores in external data</li>
<li>Made inference from tfidf features of reconstructed essays of this competition data</li>
<li>Add these predicted values to other features (e.g., action time, word count…) and trained the models</li>
</ol>
|
Linking Writing Processes to Writing Quality
|
[3rd place solution] Blend MLM pretrained DeBERTa & GBM
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Linking Writing Processes to Writing Quality
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>As a reference point, I can give [Private/Public] of GBM blend (incl MLP) [0.571/0.584]; as well as Deberta only blend [0.565/0.578].<br>
On CV - 8 fold - the individual Debertas were in the 0.584 +/- 0.002 range; while the individual GBMs were in the 0.6 +/- 0.01 range or a bit higher. </p>
<p>The blend is only weighted average of predictions. </p>
<p>Thanks to kaggle and everyone involved for hosting this competition. It was interesting to see how good we can predict essay scores just from keystroke information. Special thanks to <a href="https://www.kaggle.com/kawaiicoderuwu" target="_blank">@kawaiicoderuwu</a> for sharing the <a href="https://www.kaggle.com/code/kawaiicoderuwu/essay-contructor" target="_blank">essay constructor</a> we based much of our solution on.</p>
<h3>TLDR</h3>
<p>Our solution is an ensemble of two parts. Firstly, we build a Gradient Boosted Trees (GBT) ensemble based on popular public features on essay level. Secondly, we build an ensemble of deberta models using the final essay text, which have been mlm-pretrained on persuade corpus where we obscured the essays similar to the competitions train set. We weight GBT-Ensemble and deberta-ensemble by a ratio of 40/60.</p>
<h3>Cross validation</h3>
<p>We used 8fold cross validation and got a so-so correlation between CV and LB. One important insight is that GBM models have a way better LB/ CV ratio compared to deberta models. Or in other words, Deberta worked better on CV, while GBM were relatively bad on CV, but good on LB. That indicates a slight domain shift between LB and train set. Our guess is the essays might be split by topic or student year. <br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F213493%2Ff9a9768c6bbb99469e6ba717be941bbb%2Fcv_lb.png?generation=1704882140038566&alt=media"></p>
<h3>Data preprocessing</h3>
<p>Similar to most teams we extracted the final text for each essay, and trained a model to analyse it. Deberta models were quite strong when using the final obscured essay text. We found significant improvement by replacing the obscurification character <code>q</code> with <code>i</code> or <code>X</code>. For both cases one can understand that the pretrained debertas have a better tokenization compared to using <code>q</code>. For example a lot of texts the debertas originally have been trained on, have explicit tokens for i, ii, iii, or X, XX, XXX. This also meant the tokenized sequence was shorter than using <code>q</code>. Following that rationale, we also trained a custom tokenizer. Models based on that tokenizer helped the ensemble a bit.</p>
<h3>Model</h3>
<h4>GBT ensemble</h4>
<p>For all models within the GBT ensemble we used the same <a href="https://www.kaggle.com/code/awqatak/silver-bullet-single-model-165-features" target="_blank">165 features</a> as presented in the public kernel by <a href="https://www.kaggle.com/awqatak" target="_blank">@awqatak</a> (who deserves another special thanks 🙏). We then trained a few models similar to public kernels on those features.</p>
<p>The final components were as following</p>
<ul>
<li>LGB (params tuned with optuna)</li>
<li>XGB (params tuned with optuna)</li>
<li>CatBoost (params from public kernel)</li>
<li>Lightautoml (params from public kernel)</li>
<li>Shallow NN</li>
</ul>
<h4>Deberta ensemble</h4>
<p>A key component of our solution is an ensemble of transformer models (Deberta) trained on the reconstructed essay text. </p>
<h5>Training procedure:</h5>
<p>We found that pretraining the transformer on the persuade corpus with MLM-objective significantly improves CV and LB. For that, essays in the persuade corpus had to be obscured similar to the essays resulting from the train set. Then in a second step we fine-tuned those models on the training data, adding additional features like cursor position, etc and using a Squeezeformer layer to derive semantic features. Adding further keystroke features did not help, and we needed heavy dropout/augmentation on the three we added.<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F213493%2F5b7318584e25c3af0099f99b368606ab%2FScreenshot%202024-01-10%20at%2010.28.21.png?generation=1704882528155672&alt=media"></p>
<p>The final components were as following</p>
<ul>
<li>deberta-v3-base trained with q replaced by i</li>
<li>deberta-v3-large trained with q replaced by i (with first 12 layers frozen in finetuning, to avoid overfit)</li>
<li>deberta-v3-base trained with q replaced by X</li>
<li>deberta-v3-base trained with custom spm tokenizer </li>
</ul>
<h3>Postprocessing</h3>
<p>For some models we clipped predictions at [0.5,6.] but it did not really make a difference. </p>
<h3>Ensembling</h3>
<p>Within the Deberta ensemble as well as within the GBM ensemble we used positive Ridge Regression on Out-of-fold (OOF) predictions to determine blending weights. The final weighting of both parts was done manually, and represented if we trust CV or LB more. For final submissions we selected 50/50 kernel and one 40/60 kernel. </p>
<h3>What did not help</h3>
<ul>
<li>Using the deleted text</li>
<li>Stacking</li>
<li>Adding more keystroke features to the deberta based model. </li>
<li>More squeezeformer layers</li>
</ul>
<h3>Used tools/ repos</h3>
<ul>
<li>Pytorch</li>
<li>Huggingface</li>
<li>Optuna</li>
<li>Neptune.ai was our MLOps stack to track, compare and share models. </li>
</ul>
<h3>Code</h3>
<p>Training code repo <a href="https://github.com/darraghdog/kaggle-linking-writing-3rd-place-solution" target="_blank">here</a>.<br>
Inference script <a href="https://www.kaggle.com/code/darraghdog/3rd-place-lwq/notebook?scriptVersionId=160142140" target="_blank">here</a>.</p>
<p>Using the deberta tokenizer on the reconstructed essay with letter ‘q’ results in a very long sequence of tokens, as there is no ‘qqq’ or ‘qq’ token natively in the tokenizer. So we tried replacing with different letters to see if the tokenized sequence is shorter, and some letters resulted in much shorter tokenized sequences for the essay. We generally found a correlation between length of the tokenized essay and the model performance, and we could easily loop through all lower and upper case characters to check which resulted in the shortest sequences.<br>
Intuitively I believe that the model easily overfit and shorter sequences learn faster so give less overfit. Also as mentioned in the post the model already has a relationship for some such tokens, like ‘i’, ‘ii’, ‘iii’… eg. Roman numericals.</p>
<p>Thanks for the heads up - training repo is public now. </p>
<p>We did not use external labelled data like 1st place. As mentioned, we used external data in an unsupervised fashion. <br>
We tested it earlier, but unfortunately did not bring it into the final blend. </p>
<p>The competition data is student essay's obscured by a character. eg. "I just got back from your class, so I decided" -> "i iiii iii iiii iiii iiii iiiii, ii i iiiiiii". <br>
Deberta is pretrained on written word sourced from the web, etc. eg. "Once, I had a dog, named Spot."<br>
To make Deberta work better on our competition data, we first take a larger corpus of student essays (persuade), obscure it by a character, like in the competition data, and pretrain Deberta with MLM using this - eg. "i iiii iii iiii iiii iiii iiiii, ii i iiiiiii". <br>
So when we finetune Deberta on the competition data; Deberta has already learned what obscured essays look like. I hope this makes sense. </p>
<p>Thanks for your kind words; yes we did not mention, the final models for submission were all trained on the full data. We did a quick test on a single deberta model - 16fullfit seeds gave a lift of 0.001 LB over a 8ff+8folds. </p>
<p>We saved the individual out-of-fold (CV on 8 fold) predictions for each individual model. We then passed these as a features into a lassoo regressor, and trained that. The lasso regressor gives a weight for each model which can be used as weights in the blend. </p>
<p>However, we did two extra things given the variability in scores. </p>
<ul>
<li>For each individual model we checked the leaderboard and CV score and manually adjusted the lasso weight based on leaderboard score. For example <code>deberta-small</code> did pretty good on CV (it was our best model) but seemed to not work well on LB - so we downweighted it. </li>
<li>The main question for the variability, as mentioned above seemed to be GBM scores vs deberta scores. Deberta scores were relatively stable compared to each other; likewise GBM models. So we trained a Lasso on Deberta only predictions; and a separate Lasso on GBM only predictions. For final submissions we selected 50/50 kernel (GBM/Deberta) and one 40/60 kernel.</li>
</ul>
<p>In your case, with the 7 models; I would recommend changing the seed of each model so it is not overfit. Get the K fold OOF predictions; train a next stage Lasso; and look at the weights of each model. Generally there are two things which would be considered for the weight of the individual model in the blend - 1) score of the model individually 2) correlation of the model to the other models in your blend - the more different your models are, the better they will perform when combining them. </p>
<p>In our experiments the deberta based models were very stable on CV (8-fold score less than 0.001 variability) and relatively stable on LB (eg. we did not have surprises when submitting, single model gave ~0.003+/-0.002 uplift over CV) - blends of debertas were more stable. <br>
The tabular based models using feature engineering (GBM, MLP etc.) were unstable, some seeds worked well; some seeds not - we tried to mitigate this with bagging seeds, but there was still randomness. Generally, Deberta was better on CV than GBM (~0.01 better) but on public LB they were similar score. <br>
As our pipeline used 60% deberta & 40% tabular; and most teams used mainly tabular approach, my understanding was, the performance on private LB would depend on how well tabular data would perform on the private set. If tabular approach worked well (like on public LB) we could fall behind due to seed randomness, if tabular approach did not do well on private our pipeline should do well compared to other teams. I believe tabular did not do as well on private, compared to public LB; but it certainly did a lot better than CV - so using a mostly non tabular approach overall helped.<br>
This is just a working theory based on the results, maybe we were just lucky to do relatively well on private. </p>
<p><br>
See better explanation below.</p>
<p>The repo is not finalised but <a href="https://github.com/darraghdog/kaggle-linking-writing-3rd-place-solution/blob/77239f49e8cb7c64a49f6ac7c78d3816727f8fc8/models/mdl_dh_05s3.py#L697-L713" target="_blank">here</a> is the squeezeformer block. We had the same implementation on the fingerspelling competition so it was one of the initial things we tried.</p>
<p>Note, the squeezeformer did not add a lot to the model; but it helped. You can see in the code <a href="https://github.com/darraghdog/kaggle-linking-writing-3rd-place-solution/blob/77239f49e8cb7c64a49f6ac7c78d3816727f8fc8/models/mdl_dh_05s3.py#L757-L763" target="_blank">we tracked</a> an auxilliary loss on the text part only (deberta), as well as the features part only (squeezeformer) and you can see how this learned below. The model learned a lot more from the text than the features. I believe this is why it blended well with GBM - because that was good at pulling information out of the features. </p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F213493%2F06ec413bd494a119d8e3f074f6b9b20f%2FScreenshot%202024-01-20%20at%2012.02.53.png?generation=1705752197024410&alt=media"></p>
<p>Ah, I had not considered it, this is a valuable learning for me. Thank you for explaining. </p>
|
Linking Writing Processes to Writing Quality
|
[3rd place solution] Trust CV is all you need.
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Linking Writing Processes to Writing Quality
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>yes it is based on the score distribution of the training data.</p>
<p>Just simple stratified k-fold cross-validation with 5-10 folds like public notebooks.</p>
<p>sure, I have public all my code and please let me know if you have any questions.</p>
<p>I have reorganized the write-up, hope that helps.</p>
<p>I want to express my gratitude to the host for organizing this great competition, and I feel incredibly fortunate to have experienced such a significant shake-up!!!!!!😄<br>
I chose to trust my cv, which is about 0.580, and as I expected, the shake-up happened. While I anticipated some shake-up, I never expected to climb to the 3rd place.</p>
<p>The key component of my method is to <strong>align context features generated using a pre-trained Deberta-based regressor</strong>. </p>
<p>Firstly, using the reconstructed essays <a href="https://www.kaggle.com/datasets/hiarsl/writing-quality-challenge-constructed-essays" target="_blank">e.g., Essays reconstructed</a>, I trained a Deberta regressor by adding 3 nn layers at the bottom of Deberta. This procedure follows the NLP process like <a href="https://www.kaggle.com/competitions/feedback-prize-english-language-learning/data" target="_blank">Feedback Prize - English Language Learning</a>, except that the characters are replaced by "anonymous" character q. Please find the <a href="https://www.kaggle.com/code/leonshangguan/training-deberta-based-regressor-as-fe-extractor?scriptVersionId=158377154" target="_blank">code</a> for more details. Training the Deberta-based regressor can achieve a cv about 0.75.</p>
<p>After that, I dropped the last layer of the Deberta regressor, and used the second last layer's output, which is a 128-dimensional vector as the <strong>context feature</strong> extracted by the language model (i.e., Deberta).</p>
<p>Based on the features from public notebooks that performed well on the public leaderboard (mainly from <a href="https://www.kaggle.com/code/yunsuxiaozi/writing-quality-fusion-notebook" target="_blank">Writing Quality(fusion_notebook)</a> by <a href="https://www.kaggle.com/yunsuxiaozi" target="_blank">@yunsuxiaozi</a>), I trained lightgbm/xgboost/catboost and save the feature importance, then selected top 64/128/256 most important features from each model and take their union.</p>
<p>Finally, the selected features from the public notebook and my context features generated using Deberta were concatenated. I trained <a href="https://www.kaggle.com/code/leonshangguan/all-fe-of-tree-models-training-pipeline-saved-fe?scriptVersionId=158376408" target="_blank">lightgbm/xgboost/catboost models</a> which give cv around 0.588 to 0.595, and <a href="https://www.kaggle.com/code/leonshangguan/all-fe-of-nn-models-training-pipeline-saved-fe?scriptVersionId=158376311" target="_blank">nn models (mlp/autoint/denselight)</a> which have cv around 0.580-0.590. For the nn models, thanks to <a href="https://www.kaggle.com/code/alexryzhkov/lightautoml-nn-test" target="_blank">this notebook</a> by <a href="https://www.kaggle.com/alexryzhkov" target="_blank">@alexryzhkov</a> .</p>
<p>Due to the time limit, I only trained a Deberta-base model as the context extractor, but I believe other language models (e.g., Bert) and even llms (e.g., llama) are worth trying as well. As Deberta and nn models require GPU resources, I didn't consider the efficient track. </p>
<p><strong>All code are listed below:</strong><br>
Feature generation and processing: <a href="https://www.kaggle.com/code/leonshangguan/gpu-all-in-training-with-context-fe-generation/notebook" target="_blank">GPU all in training with context fe generation</a> The notebook shows feature engineering and tree-based model training. For convenience, I saved the processed features to a .csv and train nn/tree models separately.</p>
<p>Training: For each model, I train with 10 to 15 different random seeds and 5 to 10 folds (StratifiedKFold). <br>
Deberta-based regressor: <a href="https://www.kaggle.com/code/leonshangguan/training-deberta-based-regressor-as-fe-extractor?scriptVersionId=158377154" target="_blank">Training Deberta-based regressor as fe extractor</a><br>
nn models: <a href="https://www.kaggle.com/code/leonshangguan/all-fe-of-nn-models-training-pipeline-saved-fe?scriptVersionId=158376311" target="_blank">All fe of nn models training pipeline saved fe</a><br>
tree models: <a href="https://www.kaggle.com/code/leonshangguan/all-fe-of-tree-models-training-pipeline-saved-fe?scriptVersionId=158376408" target="_blank">All fe of tree models training pipeline saved fe</a></p>
<p>Inference: <a href="https://www.kaggle.com/code/leonshangguan/gpu-all-fe-inference?scriptVersionId=158374031" target="_blank">GPU all fe inference</a> I didn't tune the weights for each model, just some random numbers based on cv. A simple postprocessing <code>scores[scores<0.5] = 0.5
scores[scores>6.0] = 6.0</code> was conducted before submission.</p>
<p><strong>Thank you all and feel free to comment if you have any questions</strong></p>
<p>my cv for nn models are around 0.583, and for tree models are around 0.590. The final submission is the ensemble of these models.</p>
<ol>
<li>I followed <a href="https://www.kaggle.com/code/hideyukizushi/silver-bullet-single-model-optuna" target="_blank">this notebook</a> for tuning hyperparameters, which uses mse.</li>
<li>simple gain.</li>
<li>the final hyperparameters is based on all features, even after feature selection I still use the same hyperparameters.</li>
<li>I didn't tune early stopping as hyperparameter, and early stopping was set to 250 for tree models, and 8 for nn models. </li>
</ol>
<p>I followed <a href="https://www.kaggle.com/code/hideyukizushi/silver-bullet-single-model-optuna" target="_blank">this notebook</a> which uses Optuna to tune the hyperparameters.</p>
<p>Yes, I agree. My Deberta-base model performs not well with only 0.75 cv. If I could figure out how to improve the Deberta model (e.g., replace "q"s with "i" or numeric characters), I think the feature extracted could be more informative and thus improve the final score. I realize many other teams are doing so, e.g., <a href="https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/discussion/466906" target="_blank">4th solution</a>, but honestly, my current score also involves a big part of luck.</p>
<p>For this competition I joined very late, my first submission was only 2weeks before the competition deadline. Thanks to the public notebooks, and I nearly used all my 5 submissions every day. </p>
<p>For the stabilization, I think it's because I trained a lot of models using different seeds. After fixing the features, I trained 45x10 folds for xgb and lgb models, 15x10fold catboost models, and (5-10) x (5-10) folds for mlp/denselight/autoint, all using different seeds.</p>
|
Linking Writing Processes to Writing Quality
|
[42nd Place Solution] Ensemble + Classification
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Linking Writing Processes to Writing Quality
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>First of all, I’d like to express my gratitude to Kaggle and the host for organizing this great competition. It’s grateful to obtain our first silver medal, and to become a competition Expert!</p>
<p>I also want to extend my thanks to <a href="https://www.kaggle.com/hiarsl" target="_blank">@hiarsl</a>, <a href="https://www.kaggle.com/awqatak" target="_blank">@awqatak</a>, <a href="https://www.kaggle.com/mcpenguin" target="_blank">@mcpenguin</a>, <a href="https://www.kaggle.com/alexryzhkov" target="_blank">@alexryzhkov</a>, and many other competitors for sharing their wonderful accomplishments and insights. We learned a lot from you all. And last but not least, I thank my teammates <a href="https://www.kaggle.com/kensumida" target="_blank">@kensumida</a> and <a href="https://www.kaggle.com/keisnoopy" target="_blank">@keisnoopy</a> for their amazing contributions. Thanks!</p>
<h1>Solution</h1>
<p>Here’s a brief illustration of our model.<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F16204669%2Fa0c6d5a561f69343341682db43e6a295%2Ftyping_model.png?generation=1704870816942505&alt=media" alt=""></p>
<h2>Ensemble Public Notebooks</h2>
<p>Among high-scoring public notebooks, we referred the following.<br>
・LGBM (X2) + NN | LB: 0.582 <a href="https://www.kaggle.com/cody11null" target="_blank">@cody11null</a><br>
・Writing Quality(fusion_notebook) | LB: 0.580 <a href="https://www.kaggle.com/yunsuxiaozi" target="_blank">@yunsuxiaozi</a><br>
・LGBM (X2) + NN + Fusion | LB: 0.578 <a href="https://www.kaggle.com/kononenko" target="_blank">@kononenko</a><br>
・VotingRegressor (7 models) + 165 Features [optuna] | LB: 0.580 <a href="https://www.kaggle.com/minhsienweng" target="_blank">@minhsienweng</a></p>
<p>We blended each single model by 0.1 * (LGBM + NN) + 0.2 * (Public LGBM) + 0.3 * (fusion_notebook) + 0.4 * (VotingRegressor).</p>
<h2>Classification of High-scoring Essays</h2>
<p>Since the scoring metric was RMSE, a small portion of outliers could largely impact our score. Using the public LGBM model by <a href="https://www.kaggle.com/awqatak" target="_blank">@awqatak</a>, we assessed how much edge targets (0.5 or 6.0 pts) contribute to worsen the score. As shown below, these targets had a larger influence on errors though they accounted for only 1.7 % of the train data. <br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F16204669%2Fad607a399264700f0d032345d6235d7a%2Ferrors.png?generation=1704870933532969&alt=media" alt=""></p>
<p>This was because the LGBM model was not super good at predicting those edge values, as its minimum and maximum predictions were 1.3 and 5.4, respectively. </p>
<p>To deal with this, we separately trained a LGBM classification model to detect essays with 6.0 pts, and post-processed ensemble submission by substituting the scores if the probability of being 6.0 pts is high. The ROC-auc was ~0.90, which was high enough to boost our model performance. In our top selections, replacing the prediction values to 5.5 worked for us. </p>
<p>This idea comes from discussions on the nature of RMSE and suggestions from <a href="https://www.kaggle.com/alexryzhkov" target="_blank">@alexryzhkov</a> that explained the possibility of applying classification. Thank you!</p>
|
Linking Writing Processes to Writing Quality
|
[48th place solution] Multi-label K-Fold for CV Strategy
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Linking Writing Processes to Writing Quality
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks to <a href="https://www.kaggle.com/kaggle" target="_blank">@kaggle</a> and The Learning Agency Lab for this amazing competition. Also thanks for kagglers who made amazing public notebooks.</p>
<p>Though I didn't do extensive research to prove my assumption, I think using Multilabel Stratified K-Fold <a href="multilabel-k-fold" target="_blank"></a><a href="https://github.com/trent-b/iterative-stratification" target="_blank">https://github.com/trent-b/iterative-stratification</a> for to make my CV strategy more robust and helped me to make a more stable solution.</p>
<p><strong>Features</strong></p>
<p>Besides the public notebook features, I used TF-IDF Vectorizer (char_wb) and Count Vectorizer (only char) to extract more features from the reconstructed essay. But the downside is this makes the feature engineering process more slow.</p>
<p><strong>CV Strategy</strong><br>
I used other important features as additional labels to the score. I selected these features based on EDA and Linear Correlation Analysis.<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F2111256%2F510decd74c2fd0e47af05fe4e015950d%2FUntitled.png?generation=1704900035424740&alt=media" alt="cv-strategy"></p>
<p><strong>Modeling</strong><br>
For the modeling part, I used 6-seed 10-fold LGBM for training and averaging model results for the final LGBM prediction part.</p>
<p><strong>Weighted Sum with Public Models</strong></p>
<p>Last Prediction = 0.65 * LGBM + 0.35 * Denselight Prediction (from Public Notebook)</p>
<p>This pipeline scores:</p>
<ul>
<li>Public LB 0.576 (48th place)</li>
<li>Private LB 0.567 (48th place)</li>
</ul>
<p><strong>What didn't work</strong></p>
<ul>
<li>Encoder-based transformer model (used only reconstructed essays)</li>
<li>LSTM with Attention mechanism (used reconstructed essay with features)</li>
<li>Feature Selection Network</li>
<li>K-Best Feature Selection</li>
</ul>
|
Linking Writing Processes to Writing Quality
|
[617th Solution Write-Up] Summary and Reflection.
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Linking Writing Processes to Writing Quality
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h3>1. Conclusion</h3>
<p>I am very pleased to have participated in this meaningful competition. Although I did not win a medal after the shakeup, I learned a lot in the feature type table competition. Hope to apply what I have learned next time and achieve better results. <br>
My thoughts aren't of much reference value, just simply serve to put a definitive end to this competition and share some findings.</p>
<h3>2. Feature Selection</h3>
<p>Thanks to these excellent public notebooks: <a href="https://www.kaggle.com/code/hiarsl/feature-engineering-sentence-paragraph-features" target="_blank">Feature Engineering: Sentence & paragraph features</a>, <a href="https://www.kaggle.com/code/awqatak/silver-bullet-single-model-165-features" target="_blank">Silver Bullet | Single Model | 165 Features</a>, <a href="https://www.kaggle.com/code/cody11null/lgbm-x2-nn" target="_blank">LGBM (X2) + NN</a>.</p>
<ul>
<li><p>Important features:</p>
<ol>
<li><code>sentence_features</code>, <code>word_features</code>, <code>paragraph_features</code></li></ol>
<pre><code>**use word count with different lengths**
for word_l in [, , , , , , , , , ]:
word_agg_df[f] = df[df[] == word_l].groupby([]).count().iloc[:, ]
word_agg_df[f] = word_agg_df[f].fillna()
</code></pre>
<ol>
<li><code>pause_time_features</code></li></ol>
<pre><code>** one feature**
pauses_zero_sec=pl.().(
pl.() <
).(),
</code></pre>
<ol>
<li><code>time-related features</code>, <code>word count features</code>, <code>cursor position features</code></li></ol>
<pre><code>temp = df()(
pl()(),
pl(num_cols)(),
pl(num_cols)(),
pl(num_cols)(),
pl(num_cols)(),
pl(num_cols)(),
pl(num_cols, )(),
pl(num_cols, )()
)
</code></pre>
<ol>
<li><code>gaps = [1]</code></li>
<li><code>punctuations count</code></li></ol>
<pre><code>def match_punctuations(self, df):
tmp_df = df.groupby().agg({: }).reset_index()
= ()
li in tqdm(tmp_df[].):
cnt =
= (Counter(li).())
item in :
, v = item[], item[]
in self.punctuations:
cnt += v
.(cnt)
= pd.DataFrame({: })
</code></pre></li>
<li><p>Features with not very obvious effects</p>
<ol>
<li><code>activity count</code>, <code>event_count</code> (Tried using Tf-idf and regular proportion calculations, there was basically no difference.)</li>
<li><code>gaps = [10, 20, ..., 50, 100]</code></li></ol></li>
</ul>
<p>In the end, used about 210 features. I tried more features (for example, constructing 300+, 600+, and 700+ features), but the scores on the leaderboard were poor, only around 0.595+. Therefore, I did not adopt them in the final model. In fact, when there are only about 2,500 training data entries, there shouldn't be too many features.</p>
<h3>3. Models</h3>
<ul>
<li>Used LGBM, XGB, and CB, three traditional tree models, with equal allocation in the model proportions.</li>
<li>Unable to obtain desired results with NN and TabNet.</li>
</ul>
<h3>4. Ideas that Could Not be Realized</h3>
<p>After reading this creative discussion <a href="https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/discussion/451852" target="_blank">here</a>. I tried using a classification model to assist in making certain adjustments to the regression model. </p>
<ul>
<li>Binary Classification</li>
</ul>
<pre><code> =
=
create_binary_score(score):
count_label0, count_label1
score <= . or score >= .:
+=
:
+=
</code></pre>
<p>I hoped to use a binary classification method to differentiate between marginal scores and middle scores, but the final accuracy was only around 82%. After combining it with the regression model, the results were not satisfactory, so I ultimately abandoned this approach.</p>
<ul>
<li>Five-category classification</li>
</ul>
<pre><code> convert_score_to_category(score):
score <= .:
score == .:
score == .:
score == .:
score == .:
score >= .:
</code></pre>
<p>Here, in order to balance the data volume of each label, I set the division method as mentioned above. Previously, I tried treating each score as a separate category and added weights to minimize the impact of sample imbalance. However, due to the large discrepancy, the model was ultimately unable to train properly. Even when I divided it into the five categories mentioned above, the final classification accuracy was only just over 50%.</p>
<p>After reviewing others' solutions, it seems that no one used this idea, indicating that this method indeed does not work well.</p>
<h3>5. Summary</h3>
<ul>
<li>In this competition, it seems that features are not particularly important. Many high-scoring solutions are also based on making minor modifications to the baseline.</li>
<li>How to extract more information from text and even use language models to construct features is a very effective approach.</li>
<li>Building a trustworthy CV is crucial. In the competition, my CV has consistently lacked a strong correlation with the LB, which directly led to shakeup.</li>
</ul>
<h3>6. End</h3>
<p>Thanks to <code>Kaggle</code> and <code>THE LEARNING AGENCY LAB</code> for hosting a very meaningful competition. The tabular competition has been a process of accumulating experience, and I have learned a lot during this process. Wish everyone good luck.</p>
|
Linking Writing Processes to Writing Quality
|
[64th Place Solution] - 60 Features Ensemble
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Linking Writing Processes to Writing Quality
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>First and foremost I would like to thank my great teammate <a href="https://www.kaggle.com/roysegalz" target="_blank">@roysegalz</a> who did tremendous work in the competition.</p>
<p>Trusting our CV and intuition worked well for us in the shakeup - from 708 Public LB -> 69 Private LB.</p>
<h2>Feature extraction:</h2>
<p>We started with a baseline using the amazing <a href="https://www.kaggle.com/code/awqatak/silver-bullet-single-model-165-features" target="_blank">Silver Bullet notebook</a> by <a href="https://www.kaggle.com/awqatak" target="_blank">@awqatak</a> </p>
<p>From there we extracted many more features. A brief explanation of some of our features:</p>
<ul>
<li>Segmenting<br>
We segmented with two methods for this feature: equal length means that every recording was segmented by 1/X to X parts. Dynamic means that longer recordings were segmented to more pieces. The intuition is that we want to capture the semantic “end” or “beginning” meaning in the segments. </li>
<li>Information Theory Features<br>
We extracted E[Activity], E[Small Cursor Jump] across segments, and E[Big Cursor Jump] for jumps that answer abs(cursor jump) > 2. Then we extracted the conditional entropy E[Activity_i |Small/Big Cursor Jump]. </li>
</ul>
<h2>Feature Selection:</h2>
<p>Because we used ensembles by KFolding and by changing seed and KFolding, to avoid overfit, we chose features per Fold. This means we set the seed to 42+i and for every repeat (i) and for every Fold in every seed, we took the training data for that particular fold and seed and split it again to train and validation sets. Then, we used CatBoost’s RecursiveByShap to find the best 60 features on the validation.</p>
<h2>Modeling</h2>
<p>In our approach, we used an ensemble of 4 models: CatBoost, LGBM, <a href="https://arxiv.org/abs/2301.02819" target="_blank">ExcelFormer</a>, and MLP.</p>
<p>For the deep learning models we used np.log1p() for the features to reduce the skewness. It improved our CV significantly.<br>
Also, as part of the training loop for the deep learning models, we added a simple torch.randn() * 0.4 to increase the robustness of the model.<br>
We also wanted to use Dropout for the MLP but it behaved strangely on validation (we believed it happened because it's a regression problem). Our solution was to output a vector of size 12, softmax it, and perform a weighted average with a vector of the scores (0.5 to 6).</p>
<p>Our model CV scores:</p>
<table>
<thead>
<tr>
<th>Model</th>
<th>CV</th>
</tr>
</thead>
<tbody>
<tr>
<td>ExcelFormer</td>
<td>0.5916</td>
</tr>
<tr>
<td>MLP</td>
<td>0.5953</td>
</tr>
<tr>
<td>CatBoost</td>
<td>0.6061</td>
</tr>
<tr>
<td>LGBM</td>
<td>0.5988</td>
</tr>
</tbody>
</table>
<p>We had notebooks that scored higher in terms of CV but we were worried it was overfitting.</p>
<h2>Things that didn't work</h2>
<ul>
<li>Deep learning using sequence models (extensively and to no avail)</li>
<li>Deep learning, getting the features, and using them with GB trees.</li>
<li>MOA 1d CNN architecture - it worked ok but the other deep learning models performed better</li>
</ul>
<p>Thank you!</p>
<p>It was our first time as well! The model gave us surprisingly good results and it was easy to implement using their <a href="https://github.com/WhatAShot/ExcelFormer" target="_blank">GitHub repo</a></p>
|
Linking Writing Processes to Writing Quality
|
[66th Place Solution] LightGBM and Public Notebook
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Linking Writing Processes to Writing Quality
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>First of all, I would like to express my gratitude to the staff and the Kagglers who shared great information and knowledge. My result is not so good one, but I am posting this writeup in the hope that it will be helpful to someone else and as a record for myself.</p>
<h2>Overview</h2>
<p>I created my own LightGBM model and blended it with Public Notebook models. The best score was achieved with a submission that ensemble the Public Notebook with 0.7 weight and my LightGBM model with 0.3 weight. My model alone had scores of Public 0.582878 / Private 0.571849, which is almost the same as the public model (single model). But it seems that my model have added a bit of diversity to the ensemble, which leads to the improved score.</p>
<table>
<thead>
<tr>
<th>model</th>
<th>CV</th>
<th>Public Score</th>
<th>Private Score</th>
<th>final subs</th>
<th>private best</th>
</tr>
</thead>
<tbody>
<tr>
<td>My model 1</td>
<td>0.6001</td>
<td>0.582878</td>
<td>0.571849</td>
<td>[x]</td>
<td>[]</td>
</tr>
<tr>
<td>My model 2</td>
<td>0.6018</td>
<td>0.584491</td>
<td>0.572845</td>
<td>[]</td>
<td>[]</td>
</tr>
<tr>
<td>My model 2 * 0.5 + <a href="https://www.kaggle.com/code/cody11null/lgbm-x2-nn" target="_blank">Public1</a> * 0.5</td>
<td>-</td>
<td>0.580021</td>
<td>0.568756</td>
<td>[x]</td>
<td>[]</td>
</tr>
<tr>
<td>My model 1 * 0.3 + <a href="https://www.kaggle.com/code/kononenko/lgbm-x2-nn-fusion" target="_blank">Public2</a> * 0.7</td>
<td>-</td>
<td>0.578381</td>
<td>0.568015</td>
<td>[x]</td>
<td>[x]</td>
</tr>
</tbody>
</table>
<p>My model 1 and 2 are almost same models with a little different features and hyperparameters.</p>
<h2>My Model</h2>
<p>I built my LightGBM model as follows. First, I used Stratified Kfold with 5 folds. In each fold, I trained the LightGBM model three times with different seeds. I repeated this process five times, changing the seed for Stratified Kfold. In other words, I trained LightGBM models with 5 folds * 3 model seeds * 5 fold seeds. This was made to minimize the impact of the random seed as much as possible. For inference, I used the average of these 75 models as the predicted score.</p>
<p>With regard to feature engineering, I adopted <a href="https://www.kaggle.com/code/awqatak/silver-bullet-single-model-165-features" target="_blank">the Silver Bullet Notebook</a> as the baseline and made several changes. The number of features amounts to 192.</p>
<ul>
<li>Deleted some features that were almost identical.</li>
<li>Corrected anomalies in the data that appeared to be bugs. This allowed me to correct data for several IDs that had logs significantly over 30 minutes.<ul>
<li>Logs where the down_time was reversed by more than one second were corrected so there was no reversal.</li>
<li>Logs where the difference in down_time was more than 20 minutes were corrected to a 10-second difference.</li>
<li>Logs where more than 20 minutes had passed at the first log were corrected to a 2-minute lapse.</li>
<li>Delete some events which are down_event==Process and have too long action_time.</li></ul></li>
<li>Added and modified some features about the typing process.<ul>
<li>Created another P-bursts feature, using bursts of consecutive inputs within 0.3 seconds.</li>
<li>The number of characters and the maximum cursor position at the 20 and 25-minute mark.</li>
<li>The number of keyboard shortcut.</li>
<li>Some gap features of word_count with event_id shift 200.</li></ul></li>
<li>Added many features about the essay.<ul>
<li>Reconstructed the essay at 15 minutes and compared it to the final essay, add editing distance in the first 100 characters as a feature.</li>
<li>Add aggreated features of words and sentences.</li>
<li>The number of sentences with the first word being over six characters and containing a comma.</li>
<li>The proportion of sentences with a one-letter first word.</li>
<li>The number of sentences ending with a comma within the first three or four words.</li>
<li>The average number of characters in sentences up to the first eight words.</li>
<li>The number of sentences ending with a question mark.</li>
<li>The number of sentences ending with an exclamation mark.</li>
<li>The number of long sentences containing hyphens.</li>
<li>The number of long sentences with a comma around the middle.</li>
<li>The median of the total number of characters in 10 consecutive words.</li>
<li>The number of 5 consecutive words where the total number of characters exceeds 35.</li>
<li>And so on.</li></ul></li>
</ul>
<p>I added and removed features, checking whether it improved CV and LB. However, while CV improved, LB hardly did. Looking at the decimal scores after deadline, it seemed that LB's score was moving in the right direction, but the improvement was quite small. The hyperparameters for LightGBM were decided by optimizing the basic parameters with optuna. However, I didn't spend much time on it, as it seemed to be overfitting to the training data.</p>
<h2>Some Reflections</h2>
<p>It was good to know that the silver medal score was achieved with blending of public Notebook and my model that has the almost same score as public single model itself. It is interesting to see that some top solution uses NLP models and techniques, because I didn't come up with those approaches. I would like to learn them from solutions. </p>
<p>My code can be found in <a href="https://github.com/KazuakiTokunaga/kaggle-LWP" target="_blank">this github repository</a>.</p>
|
Linking Writing Processes to Writing Quality
|
[77th LB Solution] Silver by a Hair 👱
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Linking Writing Processes to Writing Quality
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks - congratulations on the silver as well!</p>
<p>First off, I’d like to thank Kaggle, The Learning Agency Lab and <a href="https://www.kaggle.com/julesking" target="_blank">@julesking</a> for such an interesting competition! It was also awesome working with my teammates <a href="https://www.kaggle.com/yeoyunsianggeremie" target="_blank">@yeoyunsianggeremie</a>, <a href="https://www.kaggle.com/gauravbrills" target="_blank">@gauravbrills</a>, <a href="https://www.kaggle.com/aayushpatni" target="_blank">@aayushpatni</a> and <a href="https://www.kaggle.com/ravi20076" target="_blank">@ravi20076</a>, and I definitely learnt a lot from this competition. I personally think this is a huge accomplishment for me, especially since I’m still in university.</p>
<p>This competition is pretty speical to me since apart from the (tentative) competition silver, I also contributed two gold medal notebooks (Baseline, Baseline V2) and had numerous discussion posts which got a silver or above. It was also one of the first times where I had to venture out and read research papers, often for ideas for feature engineering.</p>
<p>Our final inference notebook can be found here: <a href="https://www.kaggle.com/code/yeoyunsianggeremie/writingquality-feature-set-ensemble/notebook" target="_blank">https://www.kaggle.com/code/yeoyunsianggeremie/writingquality-feature-set-ensemble/notebook</a></p>
<h1>Summary</h1>
<p>The idea of our final submission was a nested ensemble of ensembles of models trained on feature sets of different sizes, based on features that we worked on over the course of the competition. The weights of the sub-ensembles for each feature set and the main ensemble were both tuned using hill climbing.</p>
<h2>Sub-Ensembles</h2>
<table>
<thead>
<tr>
<th>Name</th>
<th># Features</th>
<th># Models</th>
<th>Models</th>
<th>Ensemble Weight</th>
</tr>
</thead>
<tbody>
<tr>
<td>Public Silver Bullet 0.582</td>
<td>165</td>
<td>10</td>
<td>3 lgbm, 3 cat, scaler+ridge, scaler+lasso, extra trees, lightautoml</td>
<td>0.14303686</td>
</tr>
<tr>
<td>Gaurav Multiseed V8</td>
<td>422</td>
<td>4</td>
<td>3 lgbm, lightautoml</td>
<td>0.37337084</td>
</tr>
<tr>
<td>Marcus V317</td>
<td>939</td>
<td>2</td>
<td>lgbm, lightautoml</td>
<td>0.48359229</td>
</tr>
</tbody>
</table>
<p>Thanks to <a href="https://www.kaggle.com/code/awqatak/silver-bullet-single-model-165-features" target="_blank">https://www.kaggle.com/code/awqatak/silver-bullet-single-model-165-features</a> for providing your solution - your notebook was part of our final submission.</p>
<h2>Feature Engineering</h2>
<p>We went hard on the feature engineering. For more information, please check out the inference code - apologies if it’s a little messy. Here’s a list of the features used in the 939-feature set (the 422 and 165 ones had similar ones) - the ones only included in our private submission have been bolded for clarity:</p>
<ul>
<li><strong>tfidf vectorization of the words in the essay, only considering <code>"q" * l for l in range(2, 16)</code></strong>, taking inspiration from <a href="https://www.kaggle.com/code/yongsukprasertsuk/writing-processes-to-quality-0-584" target="_blank">https://www.kaggle.com/code/yongsukprasertsuk/writing-processes-to-quality-0-584</a></li>
<li>total essay length (character count)</li>
<li>aggregations on the words</li>
<li><strong>aggregations on the sub-sentences (split by <code>, ; . ? ! \n</code>)</strong></li>
<li>aggregations on the sentences, <strong>including aggs on the # of punctuation in sentences</strong></li>
<li>aggregations on the paragraphs, <strong>including aggs on the # of punctuation in paragraphs</strong></li>
<li><strong>we modified the public essay code to also “assign” action/down times to each character in the essay, and did standard/rolling aggregations on this</strong></li>
<li>tfidf + normal counts of activities</li>
<li>tfidf + normal counts of text changes</li>
<li><strong>revision related features</strong> <strong>from <code>https://link.springer.com/article/10.1007/s11145-021-10222-w</code></strong></li>
<li><strong>burst related features</strong></li>
<li><strong>pause time feats, including aggs on IKI information</strong></li>
<li><strong>verbosity related features</strong></li>
<li>space features, <strong>including filtering pauses by whether they were within words, between words, between sub-sentences, between sentences, between paragraphs</strong></li>
<li>some other features</li>
</ul>
<h2>What didn't really work</h2>
<ul>
<li>CNNs or other sequential models trying to imitate transformers</li>
<li>Automatic feature selection based on feature importance / RFE</li>
</ul>
<p>Sure - the idea of hill climbing is that you incrementally add models to the ensemble, where you choose the weights based on what makes the CV the lowest (since our metric is RMSE). I've been using the same code for hill climbing for a while, which was originally inspired by a notebook that I've forgotten - you can find in the notebook I linked above.</p>
|
Linking Writing Processes to Writing Quality
|
[7th place solution] Essays predictions as features
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Linking Writing Processes to Writing Quality
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h3>Acknowledgement</h3>
<p>Since public notebooks already have a strong baseline of using action features <a href="https://www.kaggle.com/awqatak" target="_blank">@awqatak</a> <a href="https://www.kaggle.com/code/awqatak/silver-bullet-single-model-165-features">silver bullet notebook</a>, I spend most of my time trying to create features from the annoymized essay using the reconstructed notebook by <a href="https://www.kaggle.com/jasonheesanglee" target="_blank">@jasonheesanglee</a> <a href="https://www.kaggle.com/code/jasonheesanglee/updated-75-35-acc-revealing-hidden-words">notebook</a> and <a href="https://www.kaggle.com/kawaiicoderuwu" target="_blank">@kawaiicoderuwu</a> <a href="https://www.kaggle.com/code/kawaiicoderuwu/essay-contructor">notebook</a>. And special thanks to many many others for their knowledgeable and resourceful notebooks!</p>
<h2>Baseline features</h2>
<p>Select top 100 LGBM feature via feature importance from the 165 features from <a href="https://www.kaggle.com/awqatak" target="_blank">@awqatak</a> <a href="https://www.kaggle.com/code/awqatak/silver-bullet-single-model-165-features">notebook</a>. The validation strategy is 5-fold cross validation (Group-Kfold) which provides a good positive correlation between both CV and LB.</p>
<h3>Essays feature engineering</h3>
<ul>
<li><strong>no_comma</strong>: no of commas "," in the essay</li>
<li><strong>no_quotes</strong>: no of quotes " and ' in the essay</li>
<li><strong>no_spaces</strong>: no of spaces in the essay</li>
<li><strong>no_dot</strong>: no of "." in the essay</li>
<li><strong>no_dot_space</strong> = np.log(no_dot) * np.log(no_spaces)</li>
</ul>
<h3>Generate bag of words using words and paragraphs => 90 features</h3>
<ul>
<li><strong>BOW (words)</strong>: given an essay "qq qqqq qq", the bag of words is [qq: 2, qqqq: 1] for that essay.</li>
<li><strong>BOW (paragraphs)</strong>: given an essay of paragraphs "qqq q qq\n\nqq q qq" the bag of words is ["qqq q qq": 1, "qq q qq": 1] for that essay.</li>
</ul>
<h3>Label preprocessing</h3>
<p>If we look into the distribution of label, the mean value is 3.711. I create another label called "binary label" by encoding the original label into 1 if label >= 3.7 else 0. Also the distribution of the binary label (0: 1224, 1: 1247) is balanced, which is good for training a classification model. A quick sanity test that this binary label works is by leaking this binary label as part of your features, you can get an extremely low CV of 0.4X. Hence if we can predict the encoded label accurately (0 or 1), we can improve our essay prediction by a large margin!</p>
<h3>Essay predictions as feature</h3>
<p><br>
To use essays as feature we train a simple <a href="https://www.kaggle.com/code/datafan07/train-your-own-tokenizer">custom BPE tokenizer</a> on the q's to generate BPE tokens which is then use in both CountVectorizer and TfidfVectorizer with ngram_range=(1,3). Finally train two LGBM models on both vectorizers respectively and use their individual binary and regression prediction as another feature.</p>
<ul>
<li><strong>(x2 essay_binary_preds)</strong><ul>
<li>Two LGBM trained with Count/Tfidf vectors with binary objective and binary_logloss as metric using encoded/binary label as the target.</li>
<li>1 if probs >= 0.5 else 0</li>
<li>The essays CV accuracy is 86%.</li></ul></li>
<li><strong>(x2 essay_regression_preds)</strong><ul>
<li>LGBM trained with Count/Tfidf vectors regression objective and rmse as metric using original label as the target.</li>
<li>The essays CV rmse is 0.614</li></ul></li>
</ul>
<h3>Models</h3>
<p>All models are train with the same features and are tuned using optuna. Final weights are determined by using nelder-mead optimization.</p>
<ul>
<li>LGBM (100 features + BOW (words) + BOW (paragraphs) + (x2 essay_binary_preds) + (x2 essay_regression_preds))</li>
<li>Denselight</li>
<li>Tabnet</li>
</ul>
<p>CV: 0.568, public: 0.573, private: 0.562</p>
<p>Initially for essay tfidf/countvec I concatenated on top of my baseline features (100), the gains are negligible. Hence adding meta preds from "essay only model" works well for my case, it improves both CV and LB by 0.001-0.003, since these "essay only model" also has some predictive power in predicting the label. BOW essay definitely helps, despite having low feature importance, adding BOW features bring me good boost in CV and LB, as it is also more natural to add them as the essays are annoymized.</p>
<p>Hi! Essay predictions as features are concatenated to my base 100 features to train another LGBM model which are used as the final model.</p>
|
Linking Writing Processes to Writing Quality
|
[CPU Only]6th Place Solution for "Linking Writing Processes to Writing Quality"
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Linking Writing Processes to Writing Quality
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F3848554%2Fde9703af5ea3d35216168ad69fe801df%2F6-th-place-solution-pipeline-kazukiigeta.png?generation=1706122590541722&alt=media" alt="Pipeline diagram"></p>
<h2>Trust CV is important</h2>
<p>Based on the following assumptions, I hypothesized that notebooks with better CV (Cross-Validation) scores, rather than LB (Public Leaderboard) scores, are likely to perform well on the Private LB.</p>
<ol>
<li><p>From the following observations, I inferred that public notebooks with good LB scores were overfitting to the LB:</p>
<ul>
<li>There was a correlation between my CV scores and LB score.</li>
<li>When I calculated the CV scores of public notebooks that had better LB scores than mine, I found that my notebooks had better CV scores.</li>
<li>Adding some features I created to the public notebooks improved both CV and LB scores.</li></ul></li>
<li><p>From the following observations, I speculated that the LB contains more instance of easier to predict data than the training data. Additionally, I surmised that fitting to the LB can lead to a less robust model and increase the likelihood of shake-down on the Private LB:</p>
<ul>
<li>In experiments, all notebooks had better LB scores than CV scores.</li></ul></li>
</ol>
<p><br></p>
<h2>Context</h2>
<ul>
<li>Business context: <a href="https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/overview" target="_blank">https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/overview</a></li>
<li>Data context: <a href="https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/data" target="_blank">https://www.kaggle.com/competitions/linking-writing-processes-to-writing-quality/data</a></li>
</ul>
<hr>
<h2>Overview of the approach</h2>
<p>I performed all the computations on the CPU, without utilizing the GPU.</p>
<p><br></p>
<h3>Preprocessing</h3>
<p>I refer to the <a href="https://www.kaggle.com/kawaiicoderuwu" target="_blank">essay constructor notebook</a> by <a href="https://www.kaggle.com/kawaiicoderuwu" target="_blank">@kawaiicoderuwu</a> to reconstruct the essays.</p>
<p><br></p>
<h3>Feature Engineering & Feature Selection</h3>
<p>All the features I generated, along with the reconstructed essays, have been made available as a <a href="https://www.kaggle.com/datasets/kazukiigeta/linking-feature-engineering-data001/data" target="_blank">public dataset</a>.</p>
<p>In terms of feature engineering, my approach aimed to keep the number of features as low as possible, while adding features that I thought were really effective. The total number of features were only 169.<br>
This was because the sample size was quite small, 2471, and I felt that having several hundreds of features was too many.</p>
<p>I referred to the <a href="https://www.kaggle.com/code/awqatak/silver-bullet-single-model-165-features" target="_blank">silver bullet notebook</a> created by <a href="https://www.kaggle.com/awqatak" target="_blank">@awqatak</a> in my Kaggle solution. </p>
<p>For instance, I conducted Feature engineering & selection like the following:</p>
<ul>
<li>Following the acquisition of character-level TF-IDF vectors for the reconstructed essays, I introduced additional features, such as incorporating a vector created by compressing the TF-IDF vectors with an n-gram range of (1, 5) into 29 dimensions using TruncatedSVD.</li>
<li>Introducing a feature to express the number of times the 'Ctrl' key was pressed (as I believed it could be relevant to the quality of the essay).</li>
<li>Removing features that exhibited a correlation coefficient of 1 or close to 1 with each other, among other modifications after feature engineering.</li>
</ul>
<p><br></p>
<h3>Validation</h3>
<p>I used Repeated Stratified K-Fold Cross Validation to enhance the reliability of the OOF predictions and CV scores.</p>
<pre><code> i range(n_repeats):
skf = StratifiedKFold(=5, =seed ** i, =)
</code></pre>
<p><br></p>
<h3>Models/algorithms</h3>
<p>I decided to prioritize diversity in model selection rather than increasing the number of features in my solution. To achieve this, I opted for various types of models within my approach.</p>
<p>For many of these models, I ensured diversity in feature combinations through feature bagging.</p>
<p>Additionally, I implemented Random seed averaging to further enhance the performance.</p>
<p><br></p>
<h4>Level-0 model</h4>
<ul>
<li>LightGBM Classifier</li>
<li>LightGBM Classifier (ExtraTrees)</li>
<li>LightGBM Regressor</li>
<li>LightGBM Regressor (ExtraTrees)</li>
<li>CatBoost Regressor</li>
<li>XGBoost Regressor</li>
<li>RandomForest Regressor</li>
<li>Ridge</li>
<li>Lasso</li>
<li>KNN</li>
<li>SVR</li>
<li>LightAutoML<ul>
<li>MLP</li>
<li>Dense Light</li>
<li>Dense</li>
<li>ResNet</li></ul></li>
<li>TabPFN</li>
<li>TabNet</li>
</ul>
<h4>Level-1 model</h4>
<ul>
<li>ExtraTree + Bagging</li>
<li>BayesianRidge</li>
<li>MLP</li>
</ul>
<h4>Level-2 model</h4>
<ul>
<li>Geometric mean blending</li>
</ul>
<p><br></p>
<h3>Postprocessing</h3>
<p>It's possible that the test data for the Private LB includes essays with a score of 0, which aren't present in the training data. However, I believed that typing behavior alone is insufficient to accurately predict essays that would score 0, and unanonymized essays would be necessary for this task. Therefore, I set the lower limit for clipping to 0.5.</p>
<pre><code>.clip(submission, ., .)
</code></pre>
<p><br></p>
<h3>What didn't work</h3>
<ul>
<li>Word2Vec for the reconstructed essays</li>
<li>Word-level TF-IDF</li>
<li>NN models for the raw time-series data</li>
</ul>
|
Linking Writing Processes to Writing Quality
|
[No place] Influence Graphs and GNN
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Linking Writing Processes to Writing Quality
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Hello everyone! just wanted to share my approach.<br>
First competition that I take this seriously and it was everything I was hoping for.<br>
Thanks for sharing your approaches and discussions, and to the organizers for such an interesting problem formulated.</p>
<p>It ocurred to me that typography has an inherent structure based on the influence any action has over the others. That is, for every key pressed (Action); What actions taken before did it influence? Maybe we wrote a character a while ago that this action is deleting?</p>
<p>So, what Action wrote that character? lets define the relation between these two actions as an Influence. We <strong>deleted</strong> a character <strong>written</strong> by an action before. It nullified the effects the action had on the text.</p>
<p>So, apart of the sequence nature our data has, we count with added structural information.</p>
<p>I was aiming to model the sequence of actions and their Influence relations as a directed Graph for later learning with an hybrid GNN-CNN model.</p>
<p><strong>The nodes I implemented were:</strong></p>
<ul>
<li>Input node (Green): Input or paste action</li>
<li>Deletion node (Red): Deletion action</li>
<li>Replacement (Gray): Replace action</li>
<li>Pause (Purple): Pause taken between two actions (Artificial node).</li>
</ul>
<p><strong>The relations I managed to think about were:</strong></p>
<ul>
<li>Sequence (Green): An action is taken before another action.</li>
<li>Deletion (Red): An action deletes a character written by another action.</li>
<li>Replacement (Gray): An action replaces a character written by another action.</li>
<li>Position (Blue): An action ends up in the same position as another action.</li>
<li>Pause (Purple): The relation taken by a pause node with the action taken after.</li>
</ul>
<p><strong>I proposed several features for each node:</strong></p>
<ul>
<li>Node type: Type of the node.</li>
<li>WInput: Input written by each Input node ('.' , ',', ' ', '\n', 'q').</li>
<li>Weight: number of actions that node represents (I applied a coarse method).</li>
<li>Time: Time taken by the action or the pause.</li>
<li>Len_ : len of the text change produced by the action.</li>
<li>Anulada: If the action was nullified by another action.</li>
<li>Pos_change: Magnitud of the change in position the action took(compared to the position before).</li>
</ul>
<p>I just kept the first four, the other ones damaged my CV. </p>
<p>Here is an example for each graph of targets 0.5, 1.0, 1.5, 2.0 ; 4.5, 5.0, 5.5 , 6.0 (in that order left-to right).</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F4335892%2Fb2737c0560efb9ed194e4f94c53e34c3%2FSuper_Tool_Collage.jpeg?generation=1705032934977888&alt=media"></p>
<p>In the left, node sizes were determined by Time and colored by Node type.<br>
In the right, node sizes were determined by Weight and colored by WInput.</p>
<p>Here is a zoom on 5.0, 5.5 and 6.0 graphs.</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F4335892%2F3eb8e8e26fa4a0dc831e0f29b21c2175%2F50_weights_page-0001.jpg?generation=1705032996005716&alt=media"></p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F4335892%2F3151a2275766f5368e3949cd9ee825d3%2F55_times_page-0001.jpg?generation=1705033023513612&alt=media"></p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F4335892%2Fd8af8642f6ed7e5ac719f3a27d08e911%2F60_times_page-0001.jpg?generation=1705033046281084&alt=media"></p>
<p>The model used was an adaptation of a DGCNN architecture, with a custom ordering of the sort pooling layer followed by transformers blocks, interpreting the output of ordered sort pooling as a time series.</p>
<p>The intuition behind the hybrid model was that the GNN layers were going to embed the influence relations of the neighborhood into selected nodes that later will form a shorter, more informative sequence (length K), to be consumed by Transformers blocks as a time series, being able to learn influence and temporal patterns.</p>
<p>I consider I lacked experience building this models, not sure if an improvement can be done easily.</p>
<p>For better learning, I concatenated to the GNN a FFN architecture learning from the features engineered by the community and made them optimice together. I'm sure this step can be easily improved, I lacked all the experience on NN on tabular data and had no time to learn.</p>
<p>Here are the training losses of GNN+FFN (the noisy part is when I introduce the F.E Information and the FFN Arch).</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F4335892%2F922fc32a7899a7ab73311212e3cb7ab1%2FSuper_Tool_Collage%20(3).jpeg?generation=1705034671417473&alt=media"></p>
<ul>
<li>The GNN achieved 0.65 on stratified CV.</li>
<li>The FNN achieved 0.69 on stratified CV.</li>
<li>The GNN+FNN achieved 0.62 on stratified CV.</li>
<li>Silver Bullet achieved 0.618 on my local CV.</li>
<li>Silver Bullet ensembled with GNN+FNN achieved 0.608 on my local CV.</li>
<li>Ensemble with LightAutoML gave a score of 0.600 on my local CV.</li>
</ul>
<p>I have the suspicion that the graphs have minor errors (I'm actually sure, but I know little). The building algorithm was not an easy task, at least for me (it had to be efficient too!). Position relations, for example, were doing damage on CV.</p>
<p>I lacked experience developing this kind of models. There may be a direct, easy improvement on the GNN-Transformer arch.<br>
I believe FFN can be easily improved.</p>
<p>The size of the data was also a natural limit the problem had, especially influential on deep learning approaches.</p>
<p>Here is an idea: maybe me can have the history of written essays and their qualifications with the task of predicting the score of the next time step. Knowing how a determined person behaves when scores badly or fine may be a better source of predictive patterns. This could be useful if we have recurrent students.</p>
<p>That was my approach! I may keep working on this, just wanted to share it.<br>
Cheers and congrats to you all!</p>
<p>Thank you very much!</p>
<p>The hardest part for me was to implement the graph building algorithm, it was too computationally expensive if done without the proper care.</p>
<p>Glad to hear about Graph approaches!<br>
I do believe that this structures can provide interesting insights on the writing process, so I will keep investigating their properties.</p>
<p>If you have any idea on added topological information I would be glad to hear it!</p>
<p>Maybe there was simply too little data for DL to success</p>
|
Lux AI
|
11th solution
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lux AI
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Hahaha thanks for your sharing. I thought I would be beaten by your Unet bot</p>
<p>I feel so sorry for those people who want to merge with me that i did not response. And I really appreciate <a href="https://www.kaggle.com/zaharch" target="_blank">@zaharch</a> 's rejection to let me get this solo gold! I think <a href="https://www.kaggle.com/shoheiazuma" target="_blank">@shoheiazuma</a> , <a href="https://www.kaggle.com/huikang" target="_blank">@huikang</a> and <a href="https://www.kaggle.com/zaharch" target="_blank">@zaharch</a> should deserve a special award for their insights sharing! <a href="https://www.kaggle.com/stonet2000" target="_blank">@stonet2000</a> </p>
<p>Firstly, special thank to <a href="https://www.kaggle.com/stonet2000" target="_blank">@stonet2000</a> for hosting such an amazing competition! Thanks <a href="https://www.kaggle.com/shoheiazuma" target="_blank">@shoheiazuma</a> for the wonderful public kernel and <a href="https://www.kaggle.com/zaharch" target="_blank">@zaharch</a> for the UNet approach sharing. And many other people who shared ideas and insights… You guys did really good job!</p>
<p>My solution is based on <a href="https://www.kaggle.com/shoheiazuma" target="_blank">@shoheiazuma</a> 's public kernel <a href="url" target="_blank">https://www.kaggle.com/shoheiazuma/lux-ai-with-imitation-learning</a>. (THANKS AGAIN!) I list the modification I did below for your convenience to read. I will also mark those making my bots better than the original kernel and <a href="https://www.kaggle.com/shoheiazuma" target="_blank">@shoheiazuma</a> 's best kernel ;)</p>
<ul>
<li>bto = better than original one; btb = better than the sazuma's best bot</li>
</ul>
<ol>
<li>Center action (bto)</li>
<li>SE block (bto; btb)</li>
<li>Single Unit level network (probably btb)</li>
<li>Learn City actions: Stay, Build worker and research (bto)</li>
<li>more data (~2300 episodes) (bto; btb)</li>
<li>Learn 2nd place bots as well (bto; btb)</li>
<li>Expand the channels in the hidden layers (bto; btb)</li>
</ol>
<p>Here I list things that might be useful but I did not implement below:</p>
<ol>
<li>Use three-by-three grids as output head ( I can do it since i use unit-level policy, this can keep the spatial information)</li>
<li>Ensemble with UNet model (add some global information to consider)</li>
<li>Add some RULES to avoid some stupid moves (that is because imitation learning's overfitting)</li>
</ol>
<p>Finally, insights that I suppose but might be wrong:</p>
<ol>
<li>For imitation learning, all the SAME settings, unit-level policy outperforms the map-level policy. But they should handle the performance-time trade-off.</li>
<li>If you want to do the transfer learning (from imitating to reinforce learning), you should use map-level policy. That is because RL performs better with map-level policy.</li>
</ol>
<p>Thank you for your reading! Hope to see you guys in Season 2!</p>
<p>My theory is the first few dimensions indicates the current worker’s information. And that makes the magic happen, by this, the entire network within one single inference would all be utilized to determine the move of current unit, which is more accurate than predicting for every block. I will upload my model then so you can measure by yourself.</p>
|
Lux AI
|
4th Solution (Team Durrett): IL from multiple agents
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lux AI
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Firstly, we'd like to thank the organizers and other participants. We were able to learn much through the competition, such as reinforcement learning and CNN architectures. The only regret is that we couldn't make RL work out. On the other hand, if it were easier to utilize RL, we wouldn't have obtained such a good result due to our lack of knowledge and skills. Fortunately, we will be able to learn from the successful top teams using RL, so we're looking forward to using this experience for the next time.</p>
<h1>Summary</h1>
<p>Like many of the other participants, our final solution is imitation learning from top 7 agents using the almost same network architecture shared by <a href="https://www.kaggle.com/shoheiazuma/lux-ai-with-imitation-learning" target="_blank">Sazuma's notebook</a>.<br>
Since it would not be desirable to train the network from a complete mixture of data from different agents, we prepared as many last FC-layers as the number of agents to learn, while the CNN architecture is shared.<br>
In inference, we used only the FC-layer which is trained with the top agent.</p>
<h1>Model</h1>
<p><img src="https://user-images.githubusercontent.com/22230913/147354382-37ff4bd6-9300-4870-99b5-4fe72b0d73a9.jpg" alt="model picture"></p>
<ul>
<li>Channel Size: 384</li>
<li>The actions of all units and all citytiles output by one forward.</li>
</ul>
<p>We've noticed that the representation power of the network in the original notebook is insufficient, so inserted FReLU, SE-Layer, and transformer encoder. In addition, we increased as many layers and parameters as possible. In our model, in one turn, only one forward is executed, so we could save inference time and maximize the network's representation power (On average, it seems that it takes about 1.5sec per turn except for the first turn, which may need to load the model parameters.). In terms of training error, validation error, and self-play results, we observed the improvements by this network architecture refinements.</p>
<h1>Training</h1>
<ul>
<li>Optimizer: AdamW(lr=1e-03, weight_decay=1e-05)</li>
<li>Epochs: 100</li>
<li>LRScheduler: reduce the learning rate by 0.1 at the 50 epochs and 80 epochs.</li>
<li>Loss: Weighted Softmax CrossEntropy (only reduce the weight for move center)</li>
<li>Data Augmentation: Rotate 4 directions</li>
</ul>
<p>It's worth mentioning that the number of epochs plays an important role. It costs the training time much (about 1 week for the final model), but through the self-plays and LB results, we observed that the model trained by many epochs showed better performance.</p>
<h1>Actions</h1>
<p>Our actions model is not so different from others' solutions.</p>
<h2>Worker's Actions</h2>
<ul>
<li>Move x 4</li>
<li>Move Center</li>
<li>Build City </li>
<li>Transfer x 4</li>
</ul>
<h2>Citytile's Actions</h2>
<ul>
<li>Research</li>
<li>Build Worker</li>
<li>Do Nothing</li>
</ul>
<h1>Network Interpreter</h1>
<p>Using the network's output itself as the output of the agents didn't give a satisfactory performance. So we added some rules to interpret the network's output. The followings are some examples.</p>
<ul>
<li>Prohibit workers go to the same cell except for citytile.</li>
<li>Prohibit workers in the citytile go to the same citytile's cell. (If this is allowed, some multiple workers continue to take the same actions.)</li>
<li>As to citytile's actions, the proportion of "Do Nothing" is so large and this prevents imitating the original agent correctly. So in the situation where building workers is allowed, prioritized "Build Worker" in the order of the output score.</li>
</ul>
<p>We've evaluated these rules through thousands of self-plays.</p>
<h1>Code</h1>
<p>We published the code for the final model <a href="https://github.com/takuwwwo/LuxAI" target="_blank">here</a>.</p>
<h1>Dataset</h1>
<p>Dataset for the final solution is uploaded <a href="https://www.kaggle.com/bomac1/luxai-replay-dataset" target="_blank">here</a>.</p>
|
Lux AI
|
RLIAYN's approach - Online deep reinforcement learning
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lux AI
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Hi folks!<br>
We apologize for the late postmortem, but better late than never… <br>
First, we would like to thank everyone for this amazing competition. We all learned a lot throughout this journey. Special shout-out to the discord folks with whom we had very interesting discussions, to Stone, to the kaggle team and to our best competitors: the Toad’s Brigade!</p>
<p><strong>TLDR:</strong> We trained an RL agent using PPO to maximize a hand-crafted dense reward function. A KL-divergence penalty is added to the PPO loss in order to distill previous best models. The agent receives an observation of size 32x32x|features| and output an action map of size 32x32x|actions|. The agent is modelized using a simple ResNet with 17 blocks of 32 convolutions with kernel of size 3x3, which is about 300 000 parameters (only!). During data generation, we sample previous iterations as opponents using Prioritized-Fictitious Self-Play (PFSP). We implemented the RL algorithms from scratch, without using open-sourced RL libraries.</p>
<p><strong>I) Observations</strong></p>
<p>Our features space consists of 37 features (28 related to information on the map and 9 general information, repeated across the map). These features have been carefully chosen using a behavior cloning pipeline as it was faster to iterate and try new things. Key learnings:<br>
Feature normalisation and feature clipping are really important. We observed a real gap in performance when we resized all our features between roughly the same range ([0, 1] or [-1, 1]). Feature clipping ensures that the values the network will encounter on the leaderboard does not differ much from training, which helps for robustness. For instance, as carts were (sadly) not used, we decided to consider all units as workers and clip features accordingly.<br>
When analyzing predictions, we discovered that workers wanted to build city tiles even when their cargo were not full but almost full (with 99 woods for exemple). At that time, we only had the sum of all ressource in cargo as a feature. The network had a hard time making a difference between 99 and actually 100 (where you can build city tiles). To mitigate that, we added boolean features that were actually action masks like is_cargo_full, is_case_buildable, map's edge… This helps by roughly 2 pts on the accuracy of the behavior cloning task. We now describe our features.</p>
<p></p>
<ul>
<li>turn, turn divided by 359, range [0,1]</li>
<li>turn in the day/night cycle, turn % 40 divided by 39, range [0,1]</li>
<li>day / night, True if it is daylight, bool</li>
<li>research point related for each players</li>
<li>research point, divided by 200, range [0,1]</li>
<li>can farm coal, research point >= 50, bool</li>
<li>can farm uranium, research point >= 200, bool</li>
</ul>
<p></p>
<ul>
<li>ressources (wood, coal, uranium), divided max wood, coal, uranium resp., range [0,1]</li>
<li>map edges, 1 at the edge of the map 0 instead, bool</li>
<li>case buildable (no resource, no citytile), bool</li>
</ul>
<p></p>
<ul>
<li>unit's owner, 1 if our unit, -1 if it's opponent unit, 0 otherwise, range[-1, 1]</li>
<li>unit's cooldown, divided max worker cooldown, range [0,1]</li>
<li>unit's cargo (wood, coal, uranium, sum_of_ressource), divided by 100, range [0,1]</li>
<li>total fuel carried, divided by max fuel for a worker (4000), range [0,1] </li>
<li>cargo is full, cargo >= 100, bool </li>
<li>numbers of units on the case, 1 + 0.1 for every other unit (1.2 if there is 3 units), range [0, ~2]</li>
<li>will survive the night, True if the unit have enough resource to survive the current cycle night, bool </li>
</ul>
<p></p>
<ul>
<li>city tile's owner, 1 if our city tiles, -1 if it's opponent city tiles, 0 otherwise, range[-1, 1]</li>
<li>city tile's cooldown, divided max city tile cooldown, range [0,1]</li>
<li>will survive the night, True if the city have enough fuel to survive the current cycle night, bool </li>
<li>will survive the game, True if the city have enough fuel to survive the game, bool </li>
<li>number of night steps that it can survive, min(fuel // city_light_upkeep, 60.) / 60., range [0, 1]</li>
<li>number of citytile you can add with your excess of fuel, min(max(fuel - (city_light_upkeep * night_left_count_total), 0) // (18 * night_left_count_total), 15.) / 15., range [0, 1]</li>
</ul>
<p>In order to help the value model, we also add the resource (wood, coal, uranium) and units from the first step, we also add the unit, the city tiles and the difference of woods from the previous timestep.</p>
<p><strong>II) Actions</strong></p>
<p>Our agent controls all units with only one action map. This makes the whole action space tremendously large: N_UNIT_ACTION ** (map_width * map_height). This number is way orders of magnitude bigger than the number of atoms in the universe for N_UNIT_ACTION of 6 in 32x32 maps! Therefore we first tried to simplify the game by ignoring the transfer mechanism and implemented a very basic heuristic for citytiles (build if you can, otherwise research) and actually achieved good results with it on the LB. So we started our journey with only 6 actions: Do nothing, Go North, Go South, Go West, Go East, Build Citytile. </p>
<p>In our quest of simplifying the problem and reducing the action space, we masked unvalid actions. For example, we mask “Build Citytile” if the unit cargo is not full. When masking an action, we set its log-probability to -infinity to ensure it is not sampled. This was critical for RL to work at all, but also brought its bunch of challenges, see the “RL algorithm” part. </p>
<p>When thing started to go well, we decided to improve the agent with 2 ways:</p>
<p>1) Adding Transfert action to the action space. Instead of 4 transfer actions for each direction (which would have blown up the action space), we only added only one action for transfer. When the transfer action is sampled, we hard-coded its behavior. First, we always transfer the maximum possible amount of resources. Then, we give priority to resources with more fuel (uranium, then coal, then wood). Finally, if there are multiple potential receivers, we had a priority to the unit on city tiles then to the unit with more space left on his cargo. When creating those rules, we bottleneck the theoretical final performance of the RL agent. But in practice, it drastically reduces the action space, which saves a lot of compute.</p>
<p>2) As we didn't want to increase the actions space more than that, we decided to train a separate model for citytiles. This model had only 3 actions: Do nothing, Research, build workers (we never activated the cart mechanism). We used behavior cloning using data from the top 5. This helped us to have a good enough city tiles policy without the cost of a larger actions space. Sadly, by lack of time and resources, we never tried to add the citytiles actions into the main model. </p>
<p><strong>III) Reward function</strong></p>
<p>Reward functions are often tricky to get right (there is a lot of literature on this subject). </p>
<p>The most natural and purest learning signal is the win/loss reward function which is a binary sparse reward of 0 on all steps, -1 for loss and 1 for win on the very last step. However, this kind of reward signal gives rise to the well-known problem of credit assignment in RL. Because the reward is 0 on most of the steps, it makes it difficult for the algorithm to figure out what were the good moves that led to the win, and what were the bad ones. This problem is especially present in Lux, as one action is in fact multiple simultaneous unit actions. And it is very plausible that some units did great moves while others did not. We tried this reward function at the very beginning, starting from totally random play and without any kl-divergence term to distill previous models. It worked, but gave us at most a 1200 elo agent after multiple training days.</p>
<p>To partially deal with this credit assignment problem, we decided to switch to a hand-crafted dense reward function. The drawback of doing so is that the prior knowledge we encode in this reward function is often flawed. As an example, one could want to say that farming more than the opponent is great. However, there may be scenarios where you may want to let the opponent farm more and over-extend its city, because it will later run out of fuel. And even if we suppose that our prior knowledge was totally right, the way we encode it into the reward function is also often imperfect (e.g. who knows how should the farming reward signal be weighted compared to the win/loss reward signal?). </p>
<p>Our dense reward function is the first time derivative of a score i.e. r(t) = score(s_{t+1}) - score(s_t). The score function has multiple components.</p>
<p> it is the sum of all resources farmed by the units since the beginning of the game. This score is normalized by the total initial resource amount of the map in order to not overweight maps with lots of resources compared to others.<br>
we attribute each case of the map to one of the two players, given our estimation of who can get to the case first, taking cooldowns into account. If the two players can get to a case on the same turn, the case is “shared”. To compute who can get to location and when, we run a modified version of the Voronoid algorithm, taking opponent citytiles and units as obstacles. This control score is flawed, but still gives a good estimation of who controls what. Given this segmentation, we compute how much resources are controlled by a player, weighted by their distance (the farther a controlled resource is, the less it contributes to the total controlled resources. This gives us a control score, which is also normalized by the initial total map resources. <br>
given the current fuel amount of cities, we can compute how much citytiles will survive the whole game if we stopped playing. we add this number to the score.<br>
we add +50 for winning and -50 for losing a game to the score.</p>
<p>The total score function is then the weighted sum of all score sub scores:</p>
<p>score(s_t) = a * farming_score(s_t) + b * control_score(s_t) + c * citytiles_score(s_t) + d * win_loss_score(s_t).</p>
<p><strong>IV) Transition function</strong></p>
<p>The transition function gives the distribution of the next state given the current state and the performed action: s_{t+1} = T(s_t, a_t). In practice, this new state is computed by the game engine from kaggle. However, the engine was super slow. We spent a significant amount of time trying to optimize it, but did not get any significant improvements. If we had to do it again, we would re-implement a vectorized version of the engine directly on the GPU. Even after our optimizations, we spent 80% of the training time in the env.step call.</p>
<p>We used the SubProcVecEnv from OpenAi to run env in multi-process <a href="https://github.com/openai/baselines/blob/master/baselines/common/vec_env/subproc_vec_env.py" target="_blank">https://github.com/openai/baselines/blob/master/baselines/common/vec_env/subproc_vec_env.py</a>. <br>
We also tried to use the python environment. This required quite a lot of changes in our code. Unfortunately, this was not as fast as we expected. We had to do further work like pre-computing millions of initial maps to avoid generating them at train time. We also optimized our masking mechanism and our observation computation. With all those improvements, we roughly gained a factor of 2 in the time spent in the .step method.</p>
<p>Our main computer was using a RTX2080Ti as GPU and a i9-9900k processor.<br>
In the end the data collection part was around 300 steps per second (which is a bit more than 1M steps per hour). </p>
<p><strong>V) Model</strong></p>
<p>In order to find a good architecture, we used a behavior cloning task on the Citytiles. Based on the assumption that if a model that performs well in BC it would also be good for RL. We have no proof that this is correct but DeepMind did the same for StarCraft, therefore we behavior-cloned them :).</p>
<p>When creating an image to image architecture only with convolution layers, one has to be very careful about the field of view of each output. It is important that each output sees the whole input observation, otherwise it cannot take everything into account when deciding what to do. We went through a bunch of different architectures. Namely: ResNet, Unet, Res-Unet, Attention Unet…</p>
<p>The best performing model was a fully convolutional ResNet, very similar to the one used in AlphaGo, but with fewer convolutions and fewer layers. We also got rid of the BatchNormalization layers as they are not good for on-policy algorithms. The problem with ResNet is that unlike Unet architectures, the feature map is never down-scaled. Therefore each forward pass requires a huge amount of computation. We observed that deeper and larger networks constantly performed better, but they would then become too slow for our RL algorithm. So we had to find the best compromise between speed and performance.</p>
<p>We observed that Gelu activation function gives a little performance boost compared to ReLU.</p>
<p><strong>VI) RL algorithm</strong></p>
<p>We use Proximal Policy Optimization from John Schulman that we coded from scratch (no use of external RL libraries). PPO is quite easy to implement. Moreover, it is an on-policy RL algorithm, which often has better asymptotic performance than off-policy RL algorithms, at the cost of sample efficiency. Therefore we went for it. However, if we knew how slow the environment was to sample, we would have gone for an off-policy algorithm (or alternatively we should have re-coded the game engine on GPU..) because even after 4 full days of training, we never reached any plateau in the agent’s performance. </p>
<p>In PPO there are two networks. The policy network and the value network. Both take the current state as input. When the input has a high dimension like images, it has been shown that sharing some of the first layers between the policy and the value is beneficial (Cobe K. Phasic Policy Gradient paper) because it helps to create good features. However in our experiment, we have not been able to do so. Every time we tried, the gradients from the value loss completely destroyed the policy. We therefore have two separate networks with their own optimizers.</p>
<p>Learning everything from random play in a pure self-play setting is very challenging and compute intensive. Moreover, it has been observed that higher performance and faster<br>
training can be achieved in deep RL by first training an agent, then subsequently training a new agent on the identical task whilst performing policy distillation from the first agent (Czarnecki et al., 2019; Furlanello et al., 2018; Schmitt et al., 2018). We therefore re-use models obtained in previous iterations when training new ones with a kl-divergence loss in addition to the vanilla PPO loss.</p>
<p>We use a slightly modified version of PPO in order to mask invalid actions. To do so we had to augment the CategoricalDistribution from Pytorch. This has to be done properly, otherwise one might get into trouble with the on-policyness of the algorithm (we need to record what was the forbidden actions during environment interactions in order to evaluate the log probabilities of the policy properly!). Moreover, when computing the log probabilities, we sum the log probabilities of each unit-action during a step. This gives us the log probability of the whole step-action. Another possibility would have been to only use the unit-action log probability. It seemed to also work but it converged slower. We think that it is because it over-weights too much the steps where there are a lot of units. Finally, when computing the step-action log probability, we mask the input to ignore all positions where n_available_action <= 1. Therefore the policy gradient will only be computed using the positions where a decision has actually been made, and was not completely forced.</p>
<p>In all our experiments we use the AdamW optimizer, which is a correct version of Adam optimizer when we want to add weight decay regularization. We have a linear learning rate annealing schedule for the RL training (3e-3 to 3e-5).</p>
<p><strong>VII) Matchmaking</strong><br>
In all our experiments, opponents are also models, but used in a deterministic manner (not sampling the predicted Gaussians but only using the mean) because the models play better this way.</p>
<p>In order to sanity check our implementation, we first tried to beat a fixed opponent. Once the opponent becomes too weak, we copy-paste the current model weights in the opponent model, and run the experiment again. The drawback of this method is the lack of diversity in opponents, which leads to an “opponent overfitting” of the current model.</p>
<p>Then, we tried pure self-play, in which the current model always matches itself. However this kind of training often leads to instabilities as well as RSP behaviors.</p>
<p>Finally, our ultimate training protocol is based on Prioritized Fictitious Self-Play (PFSP). In Fictitious Self-Play, we not only train against the current model, but also all its previous checkpoints. It has been done in the Dota 2 paper from OpenAI. We additionally added prioritization when sampling the checkpoints so that we would sample more checkpoints against which we have a small learning rate. For those who are interested, the next step in matchmaking would be to do league training, with exploiters as in the StarCraft paper from DeepMind. However it would have required way too much compute for my little computer.</p>
<p><strong>VIII) Data augmentation:</strong></p>
<p>When training CT models in BC, we augment the data with the 8 possible symmetries. Moreover, we slightly randomize the resources on the map of +- 1%.</p>
<p>We would have loved to use this kind of data augmentation for the RL algorithm. However, data augmentation is not possible when doing on-policy RL, as the agent would have acted differently in the augmented observation. We would have loved to explore this idea though, but we did not have enough time as RL experiments take so long.</p>
<p><strong>IX) Comparisons to Toad’s Brigade approach:</strong></p>
<p>Both submissions have a lot in common. We can learn quite a lot by comparing them.</p>
<p></p>
<ul>
<li>Reinforcement learning: The two submissions use RL, which seemed to be the key here. They use IMPALA, which is an off-policy algorithm using some off-policy correction tricks. This should achieve less good asymptotic performance but this has a higher sample efficiency. Given the slowness of the environment, this was definitely a good choice.</li>
<li>ResNet: Both approaches use a ResNet. We do not have shared parameters between the value network and the policy network while TB do. Also, TB has a way bigger network than us. </li>
<li>Distillation of past models: Shared in both sub.</li>
<li>Forbidden action masking: Shared in both sub.</li>
<li>Data augmentation: as TB are doing off-policy RL, they can do data augmentation in the RL phase (do they?). This is not possible for on-policy RL. However, at test time, we predict the logits for the 8 augmented maps and average them.</li>
</ul>
<p></p>
<ul>
<li>TB feature map masking: We do not use this trick. However, I am not sure this architecture choice makes much difference.</li>
<li>Reward function: They first started with a dense reward function to heat things up, then switched to a sparse one (win/loss), which is a really good idea. In our case we went the other way round. We first experimented with the sparse reward function and got very poor results. Then we switched to a dense reward function and things started to work, but we stuck to it. We should have changed it in the last iterations as we think the distillation loss would have helped the training enough.</li>
<li>CT in the RL training: We do not have the same model for the units and the citytiles, because we thought it would have been too difficult at first. We planed to do it when the RL became good enough with the unit model but again, got caught by the deadline.</li>
</ul>
<p>Finally, we believe that the biggest difference between the two approaches is scale. Both in terms of training time (4 days vs 20 days) and number of parameters in the network (300k vs XM). </p>
<p>Thanks again for this amazing competition, I hope you learned a bit reading this postmortem. Feel free to ask questions!</p>
<p>Best,<br>
RLIAYN</p>
|
Lux AI
|
[12th] Unet IL
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lux AI
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thank you! It was 50/50, oscillating in [10, 16] interval 😄 And congrats you with solid gold</p>
<p>Thanks a lot the Lux AI and Kaggle for organizing such a great competition. It was very fun and entertaining, almost like playing a game. </p>
<p>I had very limited resources: less than 3 weeks, Kaggle's quota and 1060 6Gb, so my main goal was to learn a bit of RL. I decided to start with basic Unet IL, because it was successfully used by some teams in the last Halite competition, and then use it as starting policy for RL. But thanks to great <a href="https://www.youtube.com/playlist?list=PLqYmG7hTraZDVH599EItlEWsUOsJbAodm" target="_blank">DeepMind's RL course</a> and some experiments, i understood that due to several seconds inference time per match it would require a lot of time and luck to find the right reward shaping, and chances were not that high for off-policy method with bootstrapping. So i sticked to improving my IL model.</p>
<p>My basic Unet model had 3 levels and 64 channels and was trained using CSE weighted loss, 1/10 for no-op. Features were pretty basic, i didn't even use distance metrics.<br>
At first, due to memory constrains, i used only 1 Toad team submission, 300 episodes. Then i moved scalar features to separate input, embed them and concat as additional channels at top level of Unet. This with custom background loader allowed me to efficiently train model with 3 submissions, 1100 episodes. </p>
<p>My basic model used deterministic action predictions only for workers and scored at 1350.<br>
Each of these changes gave a +60 score:</p>
<ul>
<li>city action model</li>
<li>3 submissions</li>
<li>flip-rotate augmentations</li>
<li>switching to stochastic-deterministic (deterministic if probability > 60%)</li>
<li>128 channels Unet</li>
</ul>
<p>Winning submission was slightly better and less noisy. It used 3 models for early, mid and endgame; each trained with different loss weights. Also i stacked states from current and previous timestamp but have to use fp16 mode.</p>
<p>Focal loss, 2head models and additional features didn't work for me that well. </p>
<p>I used <a href="https://github.com/catalyst-team/catalyst" target="_blank">catalyst framework</a> for training.</p>
<p>Conclusions: it is possible to score a gold having limites resources and if you want to use RL you have to start as early as possible because you will need all available time </p>
|
Lux AI Season 2
|
1st place solution
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lux AI Season 2
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>First of all, I have to acknowledge <a href="https://www.kaggle.com/ttigga" target="_blank">@ttigga</a> and <a href="https://www.kaggle.com/danmctree" target="_blank">@danmctree</a> for co-producing the most uncertain and stressful race to the finish I could have imagined. Huge congrats to both of you.</p>
<h1>Background</h1>
<p>The Lux game specification can be found <a href="https://www.kaggle.com/competitions/lux-ai-season-2/overview/lux-ai-specifications" target="_blank">here</a>.</p>
<h1>Overall Strategy</h1>
<p>I competed in the <a href="https://www.kaggle.com/competitions/lux-ai-2022-beta" target="_blank">Lux Beta</a> just before this competition began, but threw out most of my strategic code when the post-beta rule changes were announced. The major change was that lichen now produced power. I decided then that I'd really push lichen growth early and often to generate as much power as possible. That mostly stayed true throughout the competition, even when robot-produced solar power was being promoted as a viable alternative. I just didn't have the discipline necessary to keep a robot stationary for long - there are so many other things for it to be doing!</p>
<h3>My state-of-the-art visualizer</h3>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F9709029%2F11d8af058a0c975d0fb7edcda449f913%2FIMG_5429.jpg?generation=1683587685788613&alt=media" alt=""></p>
<h3>Forward simulation</h3>
<p>I would determine actions for all units and factories, update state, then do it all over again. I'd do that for about 2.9 seconds every invocation, which gave me anywhere from 5 to 50+ steps worth of planning, depending on unit count and pathfinding complexity. I simulated just about everything including my future units. I tried to guess at opponent unit movement in limited combat situations. I never added logic for handling self-collisions or my factory explosions - probably due to optimism that maybe it'll work out differently when we get there! I assumed opponent lichen values were static, which was never correct, but never too far off.</p>
<h3>Factory placement</h3>
<p>Basically: adjacent to ice, close to ore, close to no-/low-rubble territory. I went back and forth on the relative value of nearby ore vs nearby flatland. Flatland can be incredibly valuable during the early game. Instead of digging (expensive), my light robots can go antagonize nearby opponent lights (cheap), throwing off their early plans. But I can't just avoid ore and end up completely outnumbered by mid-game. I eventually added some logic for measuring ore scarcity and comparing my current factories' ore situations vs my opponent's to determine a dynamic bonus for ore proximity. There's also the matter of ice vulnerability/security (i.e. can this location readily be denied access to ice), but I'll cover that in more detail shortly.</p>
<h3>Mining resources and building robots</h3>
<p>My strategy largely depended on growing lichen until my power income was greater than my current (estimated) power usage. Then I'd build some units and go back to mining ice and growing lichen - until my power income was ready for more units. This was definitely not a perfect strategy but it worked ok. I tended to err on the side of under-building units so that I always had plenty of power to hand out. I never knew for sure how to decide when to build a light vs save metal to build a heavy. I tried to maintain some minimum number of lights per factory and then build heavies beyond that point.</p>
<h3>On chains</h3>
<p>I used chains heavily during the beta, to limited success. My code was error-prone, and it seemed too easy to disturb a whole chain of activity with only a single light robot. I decided early on I would avoid chains except in the trivial factory-adjacent case. Clearly Tigga and Siesta proved me wrong in the end. Their economic system based on chains is definitely superior. I was rarely able to adequately disturb a chain for long. And using chains allows for more flexible factory spawn locations - ice no longer necessarily needs to be factory-adjacent. All resources are just 1 chain away! Very powerful.</p>
<h1>Roles and Goals</h1>
<p>For every step I simulated, I would set or update a "role" and "goal" for each unit. A role is a long-term but non-permanent job/responsibility. A goal is a single multi-step objective that typically involves movement and/or hitting some resource or power threshold. Each role controlled a different goal state machine. The current role and goal would be persisted between invocations. Every step I would:</p>
<ol>
<li>Check each unit to see that the current role is still valid</li>
<li>Check each unit for special role transition situations</li>
<li>Iterate over all units, assigning roles to units without one, until all units had a role</li>
<li>Update goals for all units</li>
</ol>
<p>I ended up with about 10 unique roles: antagonizer, attacker, blockade, cow, miner, pillager, protector, recharge, relocate, power_transporter, water_transporter.</p>
<p>Role selection looked something like this, and would depend on unit type and factory situation:</p>
<pre><code>new_role = (
RolePillager.from_lichen_cell(step, unit, max_dist=, max_count=)
RoleAntagonizer.from_chain(step, unit, max_dist=, max_count=)
RoleRelocate.from_assist_ice_conflict(step, unit)
RoleAntagonizer.from_mine(step, unit, max_dist=, ice=, max_water=)
RoleAntagonizer.from_mine(step, unit, max_dist=, max_count=)
RoleCow.from_lowland_route(step, unit, max_dist=, min_size=)
)
</code></pre>
<h1>Prioritizing Action Selection</h1>
<p>Not all units are created equal. I didn't want a low-priority light robot to claim a cell that a heavy robot urgently needed to move to, or pick up power that could be better used elsewhere. I used a list of prioritized situations to ensure a reasonable order that units (and factories) locked their actions into place. I wrote some nifty python to do this in a relatively clean way.</p>
<pre><code> :
():
self.step = step
self.entities = entities
():
attr self.__dict__:
():
e self.entities:
e.last_action_step < self.step:
e.action = (e, attr)(self.step, *args, **kwargs)
e.action :
e.last_action_step = self.step
func
().__getattr__(attr)
</code></pre>
<pre><code>group = EntityGroup(step, board.player.units() + board.player.factories())
group.do_pickup_resource_from_exploding_factory()
group.do_move_win_collision()
group.do_protector_transfer(heavy=)
group.do_protector_pickup(heavy=)
group.do_protector_move(heavy=)
group.do_factory_end_phase_water()
group.do_factory_build()
</code></pre>
<h1>Ice Conflicts</h1>
<p>During sprint 2, I noticed some matchups would incidentally result in two factories fighting over ice. It felt like a crazy idea at the time, but I figured it might be worth purposely choosing an otherwise suboptimal factory spawn position if it meant I was well-positioned to deny ice to an opponent’s factory, while using light water transporters to outlast them. I called this strategy “ice conflicts”. I started doing this during sprint 2 by giving a huge boost to my final factory placement if it was within 4 distance or so of all nearby ice deposits around an opponent factory. This led to my agent winning sprint 2, and temporarily breaking Kaggle’s matchmaking algorithm, sending my score to 36k+ (RIP Homeostat). I figured this strategy would be copied or countered but it never really was. While Bovard was fixing the matchmaking algorithm, I deactivated the ice conflict logic from my “production” build to save it for a rainy day (i.e. the last day). I continued to make improvements to this strategy, including using a pair of light "blockade" units to block opponent water transporters. In the end, ice conflict spawning is the only thing that kept me competitive with Siesta's and Tigga’s improved economic strategy. Interestingly, this did not work at all against flg, who tended to use heavies to flexibly move ice around the map wherever it was needed. This resulted in very few factory kills, and I just had to live with the otherwise suboptimal factory placements. This weak matchup really hurt my final score.</p>
<h1>Coordination Among Units and Factories</h1>
<p>There were a few situations where units and factories needed to coordinate with one another to make sure they weren't trying to do/use the same thing.</p>
<ul>
<li>Enforce unique unit->cell assignments<ul>
<li>Units would claim a cell whenever they were tasked with digging/antagonizing/standing there.</li>
<li>Some units could “displace” another unit’s assignment, invalidating its role and forcing a new role to be determined. This usually happened when a heavy took over a job from a light.</li></ul></li>
<li>Enforce unique unit->unit assignments<ul>
<li>Only really relevant for units with the attacker role. I didn't need more than one unit pursuing an opponent unit at a time.</li></ul></li>
<li>Enforce unique cell->factory assignments<ul>
<li>Ice cells are assigned to my various factories over time, determined by whichever factory sends a heavy robot there first.</li>
<li>This ensures factories can rely on relatively stable ice income over time (no risk of “losing” an ice cell to a friendly factory)</li>
<li>Any unit can mine any ice cell if its available, but if a unit belonging to the owner factory wants it, they get it, displacing whoever was there previously.</li></ul></li>
<li>Collision avoidance<ul>
<li>As described earlier, units determine their actions in priority order. This means I often needed to determine if a high priority unit could safely move to a cell currently occupied by a lower priority unit. Eventually I settled on simply comparing the low-priority unit's power to the power necessary to move <em>anywhere</em>, assuming at least one safe move was possible. Similarly, I needed to check for situations where a high-priority unit might move onto a cell that was the only remaining safe option for a lower-priority unit to move <em>to</em>. These checks were a little messy, and there were still small gaps in the logic, but it worked most of the time.</li></ul></li>
</ul>
<h1>Reflection / Looking Ahead</h1>
<p>I had very few expectations coming into this competition. I had no idea how much time I was going to put into it, and I was mostly under the impression that RL was going to reign supreme as in season 1. The game proved to be very challenging, surprisingly deep, and well balanced. I so enjoyed tinkering on this project for 3+ months. Thanks to <a href="https://www.kaggle.com/stonet2000" target="_blank">@stonet2000</a> and <a href="https://www.kaggle.com/bovard" target="_blank">@bovard</a> for putting this all together. And a special shout out to the folks who were constantly pushing the bounds of the game/meta: <a href="https://www.kaggle.com/harmbuisman" target="_blank">@harmbuisman</a>, <a href="https://www.kaggle.com/danmctree" target="_blank">@danmctree</a>, and <a href="https://www.kaggle.com/ttigga" target="_blank">@ttigga</a>. And to <a href="https://www.kaggle.com/ferdinandlimburg" target="_blank">@ferdinandlimburg</a> and <a href="https://www.kaggle.com/philippkostuch" target="_blank">@philippkostuch</a> who pushed radically different and competitive solutions over the last month or so. I look forward to seeing you all on future leaderboards.</p>
<p>Edit:</p>
<p>My open sourced code for Season 2 (Python) can be found <a href="https://github.com/ryandy/Lux-S2-public" target="_blank">here</a>. And Season 2 NeurIPS Edition (C++) <a href="https://github.com/ryandy/Lux-S2-neurips-public" target="_blank">here</a>.</p>
<p>Congrats to you too, Master Harm!</p>
<p>I started working on the blockade role with about 3 weeks remaining. I originally thought it wouldn't be too terribly challenging.. I had already done a thing where two attacking robots can team up to chase an opponent robot, effectively limiting its safe movement options to only half the board by always denying 1 direction plus the center move. But for blockade I ended up writing 1100+ pretty gross lines of code that try to handle all sorts of various special case situations. It was tricky due to the coordination of the two units, the time sensitivity, the unpredictability of the opponent unit's path, dodging various other opponent units, and the necessity of maintaining more power than the target unit in both blockade units. It definitely doesn't <em>always</em> work. I never quite smoothed everything out, and sometimes rough terrain just makes it near impossible to cut off a unit while still having more power than it.</p>
<p>In general though, I would transition two light units at an ice conflict factory into the blockade role whenever I noticed a light robot picking up water somewhere on the map. I would anticipate what the water transporter's route would be, using up to ~10 steps of movement from its currently advertised action queue, then filling in the blanks from there, using a compromise route somewhere between a straight line and the lowest cost route. Then I'd evaluate every cell along and adjacent to that route using a crazy scoring metric that basically prioritized being near the blockade units' home base but not terribly close to any opponent factory (there can be lots of annoying traffic around factories). One of the two blockade units would be designated the "primary" and would head for the chosen cell, and the secondary would head to some neighbor of that. The primary's goal cell would be re-evaluated every turn, and I really tried to prevent there being too much thrash, which can waste a lot of power. Once the target unit got close (within 2-3 cells) I would check a bunch of specific situations to determine what the best movement would be (this is where the Catan pieces really shined!). The goal was to spend as little power as possible, stay between the target unit and the low-water factory, and make sure to move <em>somewhere</em>, often just swapping positions, if a collision may be possible.</p>
<p><a href="https://s2vis.lux-ai.org/#/visualizer?input=50712318" target="_blank">This replay</a> shows the strategy working three times:</p>
<ul>
<li>step 108 at (16, 39) near factory_2<ul>
<li>Mostly static until they do a little dance around steps 224 and 298. Factory_2 explodes at step 311.</li></ul></li>
<li>step 128 at (37, 17) near factory_4<ul>
<li>The blockade has to slide along with the water transporter for a distance of about 12. Factory_4 explodes at step 151.</li></ul></li>
<li>step 155 at (14, 13) near factory_6<ul>
<li>Pretty quick and easy. Factory_6 explodes at step 168.</li></ul></li>
</ul>
<p>If you watch carefully you can see the blockade units going to pick up power and get into position well before the water transporter arrives near its destination. I only allowed for one blockade pair per ice conflict, so the blockade could be overcome by using multiple water transporter units. You can see that happen at step 199 in the above replay where a second water transporter arrives at factory_2 while the existing blockade continues its standoff with unit_77.</p>
|
Lux AI Season 2
|
7th place IL-based solution
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lux AI Season 2
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Hello</p>
<p>Sharing my 7th place imitation learning solution. Bidding model trained on ry_andy_ episodes. Factory placement and unit/factory actions trained on flg's episodes. </p>
<p><a href="https://github.com/skyramp/luxai_season2" target="_blank">https://github.com/skyramp/luxai_season2</a></p>
|
Lux AI Season 2
|
8th place solution
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lux AI Season 2
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Hello Folks</p>
<p>Responding to a certain request and fullfilling my obligations, I'm sharing my humble solution:</p>
<p><a href="https://github.com/loh-maa/luxai-s2-submission" target="_blank">https://github.com/loh-maa/luxai-s2-submission</a></p>
<p>It's a rather ordinary rule-based agent with some extra quirks, none of which are particularly unique -- they already have been described in other, better solutions.</p>
<p>See you next time<br>
loh-maa</p>
|
Lux AI Season 2
|
FLG's Approach - Deep Reinforcement Learning with a Focus on Performance - 4th place
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lux AI Season 2
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Hey, you are right, you don't need the factories to be a grid, since there number is very limited. <br>
I use the grid, since all actors (units, spawns, factories) share the same torso, which has the same shape as the map 48x48 (x num_features). With this architecture getting all factory actions can be done with a single convolutional layer, which outputs, 48x48x num_actions. I could use a lower output dim for the factories, but given how fast the convolution is, I would assume that might even be slower. The result should be the same, however.</p>
<p>Yes, all the actions are sampled independently. However, the model providing these probabilities controls all robots / factories at once and has global vision. Because of that it can decide e.g. robot A goes north, robot B goes south with probabilities close to one. I do it this way to keep the action space simple (and the heavy lifting of coordinating units is done by the model).<br>
Your approach of using a smaller action space should work just as well, but you'd have to deal with variable-length sequences of actions instead of a fixed shape.</p>
<p>Hey, yes it's definitely possible without IL. In then end I only needed IL for architecture search. Training worked fine from scratch with RL if you used very shaped rewards (like go to resource, mine resource, return resource). Afterwards I switched to a zero-sum reward which was still hand-crafted but mostly relied on game result.</p>
<p>The training of the agent itself was 2-3 days for the starting agent (IL or RL with heavily shaped reward) and afterwards it was a little over a month training time for the main phase.<br>
The NN architecture search I don't know exactly, it was many small experiments. A couple of days of GPU time probably.</p>
<p>Hey loh-maa,<br>
I created a wrapper around the regular python environment. The wrapper transformed the dict / list observations of units, factories etc. into one large 48x48x105 array (see the "observation space" part). I then used a gym.AsyncVectorEnv to run multiple of these in parallel for training.<br>
I didn't use the jux env simply because I set things up early before jux was available and because my GPUs were almost always 100% utilized while my CPU wasn't. Running the regular (CPU) env simply didn't slow anything down for me.<br>
The Kaggle-style-agent, that communicated via stdout I never used for training, only for performance optimization and preparing the final agent.<br>
Congratz on you finish!</p>
<p>Thanks, that's very good to know. I didn't try that at all. Maybe it was better though - in terms of happiness 😄</p>
<h1>1. Introduction</h1>
<h2>Lux Season 2</h2>
<p>LuxS2 is a two player, zero-sum game in which each participant controls a swarm of robots racing to terraform Mars faster than their opponent. It is played on a 48x48 square map in multiple phases:</p>
<ol>
<li>A simultaneous-move bidding phase to decide who goes first,</li>
<li>A sequential placement phase in which players place 2-5 factories (number chosen randomly) and</li>
<li>A simultaneous-move main phase.</li>
</ol>
<p>During main phase players acquire metal to create robots, water to grow lichen and clear rubble to make space for the lichen farms. At then end of 1000 turns the player with the larger lichen amount wins. </p>
<p>The main phase is split into 20 day-night-cycles, each lasting 50 turns out of which 30 are day and 20 night.<br>
There are three types of actors:</p>
<ol>
<li>Factories grow lichen, produce robots and turn raw ore/ice into usable metal/water,</li>
<li>Heavy units excel at combat and resource gathering but are somewhat sluggish to move around especially in high-rubble areas,</li>
<li>Light units are good at moving around efficiently but mine less resources and lose in combat to heavies.</li>
</ol>
<p>Units require power for almost all actions. Power is gained each turn by factories, slowly by all units during the day and by growing lichen. A unit without power cannot take any actions and needs to (slowly) recharge.</p>
<p>When two units collide (move to the same target position), heavies destroy lights and among same units of the same type the one with more power wins. This collision handling also applies to your own units!</p>
<p>On top of these mechanics there is also a planning component: players can send a queue of up to 20 actions to each of their units. This is useful since each time the action queue is updated, a small power charge needs to be paid by the affected unit. Example:</p>
<ol>
<li>A heavy unit digs 20 times (60 power each) and the dig action is sent each turn anew (10 power per update): power cost: 20 * 60 + 20 * 10 = 1400.</li>
<li>Same case but a queue of 20 dig actions is sent once: 20 * 60 + 10 = 1210.</li>
</ol>
<p>The unit used almost 15% less power in the second case. Power is pretty much the scarcest resource so this efficiency gain makes a very big difference.</p>
<h2>Comparison with last season</h2>
<p>The game increased in complexity compared to last year quite a bit:</p>
<ul>
<li>the map is 2.2x as large,</li>
<li>a match lasts 3x as many turns,</li>
<li>there are three different game phases,</li>
<li>for learning approaches, like mine, the power system (especially in combination with the need to clear rubble to gather resources and grow lichen) made random exploration a lot harder,</li>
<li>the action queue system changed the game from a single-step problem to a multistep planning one.</li>
</ul>
<h1>2. Method</h1>
<h2>Plan</h2>
<p>The matches of the competition are run on Kaggle using CPU-only VMs that seemed to have varying performance but mostly be single-core machines. Because of this performance was the main consideration on every decision and I came up with a plan focused on it:</p>
<ol>
<li>Simplify the action and observation space to manageable size,</li>
<li>Handle collisions and action queues,</li>
<li>Use imitation learning and small map RL to find a neural network architecture that combines CPU-performance, large receptive field and sample efficiency,</li>
<li>Train a small model using RL,</li>
<li>Train a larger main model using the small one as a teacher,</li>
<li>Optimize the final model for cpu inference.</li>
</ol>
<h2>Action and observation space</h2>
<h3>Action space</h3>
<p>I structured my model to have seven different actors:</p>
<ol>
<li>Bid: Discrete(10): [0, 10, 20, 30, 40, 50, 70, 100, 150, 200],</li>
<li>Spawn location: Discrete(48*48),</li>
<li>Spawn resource amount for water: Discrete(7): [50, 100, 120, 150, 200, 250, 300],</li>
<li>Spawn resource amount for metal: Discrete(7): [50, 100, 120, 150, 200, 250, 300],</li>
<li>Factories: Grid(4): [noop, build light, build heavy, grow lichen],</li>
<li>Light units: Grid(23): [moves in 5 directions (incl. noop), dig, self-destruct, pick-up all power available, transfers in 5 directions for [ore, ice, power]]</li>
<li>Heavy units: Grid(23): same as light units.</li>
</ol>
<p>Grid(k) means a 48x48xk action space in which for each position of the 48x48 map one of k actions is sampled independently.<br>
On transfer actions a unit transfers everything it holds for ice and ore and 90% of it’s current value for power. When performing a spawn action, a location and a starting resource amount for water and metal need to be selected at the same time. I first sample a location then predict the water/metal amounts for all locations in parallel and sample one of the 7 actions at the chosen spawn location.<br>
Note: there are no actions for transferring or picking up refined resources like metal and water. So the agent could only use unrefined resources for transferring over long distances.</p>
<h3>Observation space</h3>
<p>I encoded the positions of all actors using 0/1 variables, most other quantities (power, resources, rubble) were taken as continuous variables normalized to usually be in the -1 – 1 range. I tried using explicit embeddings for all discrete observations but couldn’t find any difference in performance. The one exception to this was the lichen ownership: each factory has its own lichen strain. With up to five factories per player that’s eleven discrete values when you add one more for “no lichen”. I embedded these using a 16 dimensional embedding layer and summed the result with a 16-dim embedding of the player id to indicate the owner of that lichen.<br>
Global features like the current turn or the spawn resources remaining are encoded as separate feature layers (with the same value repeated for every position in the 48x48 feature layer).<br>
In total this gave me 54 different features. To these I added historic information: the positions and resources of all actors as well as lichen and rubble values on the board for the last three turns (17 features per turn). The final observation space had a shape of 48x48x105 (54 + 3*17=105).</p>
<h2>Collisions and action queues</h2>
<h3>Collisions</h3>
<p>Self collisions were very punishing this season since all but one of the colliding units died. During early RL I realized that my agent avoided having units work next to each other and in general didn’t like making many units. This seemed to be caused by the fact that a somewhat random policy (which is needed for exploration) will cause many harmful self collisions. To counteract this I canceled all moves that would result in self collisions, so that units performed a noop instead. This required reproducing quite a bit of game logic but it increased (early) learning speed a lot.</p>
<h3>Action queues</h3>
<p>To fill the action queues with multiple actions at inference time I used forward prediction: the agent predicts actions for itself and the opponent then steps the environment and repeats the process. Since the opponent’s action queue is part of the public game observation, I had one agent on the LB that used it for forward prediction (and falling back to its own prediction if no move from the queue is available) – it performed similar to just using predictions.</p>
<p>During training I did not use action queues and only had the agent predict its next action. This method only had one problem: the amount of power used to update action queues differs in both cases. This causes the agent’s expectations about how long it can mine, which parts of the map it can reach etc. to be off for longer sequences. To combat this I used an expected communications cost approach: I randomly applied the comm cost with p=0.2, simulating an average length five action queue (which was pretty close to the effective action queue length that the agent achieved after all optimizations).</p>
<h2>Neural network architecture search</h2>
<p>I used some beta agents and later a few early submissions to create a dataset for imitation learning (IL). More precisly, I:</p>
<ul>
<li>downloaded around 2000 matches from top-scoring agents via MetaKaggle</li>
<li>transformed the obs and actions into the spaces mentioned above when creating the dataset</li>
<li>stored everything as compressed HDF5 dataset (the final dataset was around 300GB and HDF5 allows for very fast random access without loading everything into RAM).</li>
</ul>
<p>Submissions that used actions I did not support were excluded (some agents were trasferring water between factories).</p>
<p>I evaluated different NN architectures based on their unit-accuracy on this dataset (I also trained and evaluated for factory- and spawn-locaction-accuracy but these were much easier to learn). The main traits I was looking for were:</p>
<ul>
<li>CPU performance</li>
<li>Receptive field (“see the whole board quickly”)</li>
<li>GPU-Memory usage</li>
<li>Sample efficiency.</li>
</ul>
<p>The best result I got was a “DoubleCone” network, a DoubleCone(4, 6, 4) is depicted below. It performed a decent share of its compute at a downscaled resolution of 12x12 (instead of 48x48) which helped with respect to all goals above except sample efficiency. To avoid a loss of fine grained control there is a skip connection around the DoubleCone-block. Additionally before and after that block there are multiple full resolution ResBlocks. The actor heads are simple 3x3 convolution layers without activations, the one exception to this is the bidding head, which uses the critic architecture (minus one Conv-Layer).</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F2360589%2F047dcaede92d9da504c479852e3b9971%2Fnn-arch.png?generation=1683117990007566&alt=media" alt="DoubleCone(4, 6, 4)"></p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F2360589%2F94da0139e55fca3108cd69630ec66c6a%2Fnn_critic.png?generation=1683118310164650&alt=media" alt="Critic"></p>
<p>The critic is depicted above, its architecture did not seem to be very important in my tests. The slightly unusual AdaptiveAveragePool is there since many of my early RL tests were done with 16x16 and 24x24 maps and I wanted a truly resolution-independent architecture.</p>
<p>I also experimented with layer optimizations, especially ResBlock design. Here I tested recent advances from computer vision (e.g. ConvNext) with some task specific optimizations. Some results:</p>
<ul>
<li>I did not use any Bottleneck or InverseBottleneck blocks as the 1x1 convolutions are fairly GPU-intensive but do not provide receptive field. </li>
<li>I used way less activations, in particular there is no activation at all after the second convolution, only SqueezeAndExcitation.</li>
<li>With my compute budget I couldn’t find real differences between ReLU, LeakyReLU or GELU.</li>
<li>3x3 and 5x5 convolutions performed similarly if you roughly double the depth when using 3x3s (lower parameters / receptive field).</li>
<li>There are no normalization layers as I couldn’t find any benefit in them, as long as there are SqueezeAndExcitation layers. Without these performance dropped significantly but part of this could be recovered e.g. with LayerNorm.</li>
</ul>
<p>A comparison between my final architecture and a ResNet can be seen here:</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F2360589%2F9c3f15ae406ea47cb78aae76d2afeb5b%2Fil_performance.png?generation=1683118089236048&alt=media" alt="IL Performance"></p>
<h2>Reinforcement Learning</h2>
<p>My agent was trained using self-play and reinforcement learning. I used shaped rewards that were strongly focused on the game result to avoid biasing the agent as much as possible.</p>
<h3>Rewards</h3>
<p>In a set-up phase (around 65M steps) the agent was trained using heavily shaped rewards focusing on gathering resources. It received rewards for:</p>
<ul>
<li>moving towards its closest resources</li>
<li>clearing rubble from resources</li>
<li>mining resources</li>
<li>moving to closest factory when carrying e.g. > 100 resources</li>
<li>dropping resources on factories</li>
<li>bonus for mining ore and ice</li>
<li>making units</li>
<li>growing lichen</li>
<li>placing factories near resources.</li>
</ul>
<p>These rewards were “selfish” for each agent (not zero-sum).</p>
<p>After this phase, I switchted to zero-sum rewards:</p>
<ul>
<li>{-1, 0, 1} for game result</li>
<li>[-1, 1] for relative lichen advantage at the end of the game</li>
<li>0.3 for each factory</li>
<li>[-0.8, 0.8] relative unit advantage</li>
<li>[-0.1, 0.1] for relative lichen power production.</li>
</ul>
<p>Each reward was given relative to its opponent's performance to yield a zero-sum reward in the range of [-1, 1]. One exception was the factory reward: here the agent received a flat + or - 0.3 for each factory it had more / less than its opponent. Rewards were only given when a change was made (e.g. when the factory was lost), not each turn afterwards. This way the (undiscounted) sum of all relative rewards equals the relative advantage at the end of the game.<br>
I tested many different reward weightings over the course of training and the agent seemed very robust to changes, probably because the game result and lichen advantage dominate the reward.</p>
<h3>Reinforcement learning method</h3>
<p>My RL method uses a single-learner-multiple-actor approach. I implement everything using Python’s Multiprocessing: each actor and evaluator is its own process and all processes communicate via queues. The architecture can be seen below. I use Pytorch for all NNs and vectorized compute but no RL framework.</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F2360589%2Ff913c0f00e3d5ea22e4cac9a934a0346%2Frl-arch.png?generation=1683118426313787&alt=media" alt="RL architecture"></p>
<p>In the beginning I tested PPO and Vtrace for advantage calculation on 16x16 and 24x24 maps and achieved similar results. I went with Vtrace. All in all my agent learned using the following losses:</p>
<table>
<thead>
<tr>
<th>Type of loss</th>
<th>Method</th>
<th>Count</th>
<th>Main parameters</th>
</tr>
</thead>
<tbody>
<tr>
<td>Value</td>
<td>TD(λ)</td>
<td>1</td>
<td>λ=0.95, γ=0.9995, weighting coef: 1.0</td>
</tr>
<tr>
<td>Policy gradient / advantages</td>
<td>Vtrace</td>
<td>7 (1 per actor)</td>
<td>λ=1.0, γ=0.9995, clipping c/ρ = 1, weighting coef: 1.0</td>
</tr>
<tr>
<td>Entropy</td>
<td>KL</td>
<td>7</td>
<td>Weighting coef: 1e-5 .. 1e-4, depending on actor</td>
</tr>
<tr>
<td>Teacher</td>
<td>KL</td>
<td>7</td>
<td>Weighting coef: ~5e-3</td>
</tr>
</tbody>
</table>
<p>I lowered the entropy very slowly over training and updated the teacher regularly, keeping it around 30M steps behind the agent.</p>
<p>One problem with my approach was that bidding and spawning factories are fairly rare events, they only occur on ~1% of all steps. This meant that a typical batch of size ~500 contained 0-2 of these events which didn’t allow stable learning. To counteract this I “upsampled” spawns and bidding by having a dedicated spawn actor. Every 16 update steps this actor played around ten matches from the starting position for roughly 50 steps each then abandoned these games.</p>
<h3>Training larger models</h3>
<p>It was my plan to only use the DoubleCone(4, 6, 4) network shown above as a teacher for a second and maybe third generation of larger models. However due to problems described below with runtime performance, I had to cancel the training of a DoubleCone(6, 8, 6) model after around 100M steps. I then continued finetuning the smaller model. Its training performance can be seen here:</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F2360589%2F2b3c46c03fc3662bdf740524666a0a04%2Ftraining_progress.png?generation=1683118499788164&alt=media" alt="Training progress"></p>
<h2>Optimizing Kaggle Performance</h2>
<p>The fact that each unit had to pay an engergy cost when updating its action queue meant that solutions that only predicted few steps ahead had a strong disadvantage. Over the course of the competition I ran many local and leaderboard tests to evaluate the impact of energy efficiency. Results were fairly consistent: one should aim for at least 4-6 step predictions, below that performance was crippling (especially single step). Getting more steps only provided modest advantages in my tests. Some results can be seen here:</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F2360589%2F9a1de816ff9044508fdae3e46604a1ce%2Fpred_steps.png?generation=1683118552693371&alt=media" alt="Prediction steps influence on performance"> </p>
<p>When you compare these results with prediction performance of ResNet and DoubleCone architectures, you can see that large models were very hard to use. See below. The 24 block ResNet is similar to what was used by last year’s winner and it would barely be able to predict a single step. </p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F2360589%2Fe6916e3ff69a821ac7a3ffa77eb17312%2Finference_speed.png?generation=1683118597376763&alt=media" alt="Inference speed"></p>
<p>One very important detail is that no fast inference runtime (like onnxruntime with platform-specific execution providers like OpenVino mentioned above) was available in the Kaggle environment. Since it wasn’t possible to install any packages, me and a couple of other competitors tried packaging onnxruntime ourselves but as far as I know no one was successful. The fast execution providers like OpenVine somehow weren’t working on the competition environment (although it worked everywhere else including Kaggle notebooks). It also was close to impossible to debug this as all error logs were 404 for me. </p>
<p>When looking at the performance numbers above and the fact that for example OpenVino doubled/tripled performance in all my tests, it was clear it was make or break for using larger models on Kaggle hardware. After unsuccessfully debugging the issue for a couple of days, I decided to give up on it, cancel the DoubleCone(6, 8, 6) model I was training and went back to fine tuning the smaller one.</p>
<p>After this I tried many other approaches for speeding up inference:</p>
<ul>
<li>static post-train quantization</li>
<li>dynamic post-train quantization</li>
<li>model compression</li>
<li>jit trace and script.</li>
</ul>
<p>Most of these either failed as they had some kind of setup time which was too long on Kaggle hardware or they had unfavorable accuracy-performance trade-off compared to using a tiny model to fill up action queues:</p>
<h3>Filling up action queues</h3>
<p>My agent usually managed to predict 3-5 steps ahead using a DoubleCone(4, 6, 4). To improve on this, I used transfer learning with a DoubleCone(2, 6, 2) network with only 64 (instead of 128) channels. The action queues were then built as follows:</p>
<ol>
<li>Predict up to 3 step with the DoubleCone(4, 6, 4) network.</li>
<li>Fill up with predictions from the tiny net until time runs out.</li>
<li>Use pattern matching to fill the queue to 20 actions.</li>
</ol>
<p>Always doing 1-3 slow predictions meant that any mistakes made by the tiny net during previous predictions would be corrected. This way the agent usually managed 6-8 predictions, with effective (corrected) queue length between 5 and 6.</p>
<p>The pattern matching used common behaviors to naivly fill the queue: units moving constantly back and forth in combat, (light) units picking up power and transferring it to adjacent mining units and digging. If none of these worked, it just copied the last action.</p>
<p>For switching between these stages I used predictive time management. This was necessary as VM performance was somewhat unreliable. </p>
<p>Transfer learning was done with a (Q)Dagger-inspired approach: first training on the teacher’s trajectories and then switching to the student’s to correct remaining mistakes. The strength of the teacher was reduced over the course of training.</p>
<h1>3. Conclusion</h1>
<p>The competition was a bit of up and down for me. On the one hand the lack of fast deployment options for NNs was a huge letdown and the debugging problems made it very frustrating to work with. On the other hand the environment was very interesting and fun to work with. My solution worked quite well and I had a chance to use a wide array of tools from IL and architecture search over RL to transfer learning and performance optimization. But most importantly the community especially on Discord is just amazing. Lots of thanks to Stone Tao, Bovard and the sponsors for running this competition! Thanks to Agenlu for helping with performance optimization, Tigga, ry_andy_, Harm and SiestaGuru for being the people I battled with the most and finally thanks to ry_andy_ and loh-maa for (unknowingly) providing an IL dataset.</p>
|
Lux AI Season 2
|
Final notes and parameter tweaking
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lux AI Season 2
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>A lot of it is desire based. To determine where a robot should go I calculate how much it wants to go there. For example an ice tile might get a base desire, a penalty for distance, a bonus for having a nearby factory low on water and a penalty for being in the last 100 turns. The exact bonuses and penalties are slowly learned to create a agent that mostly does what it's supposed to.</p>
<p>An example of a bit of code that might be turned on or off based on a parameter is a bit of code I wrote that said that robots would be banned from returning to their previous spot if not in combat. I had no idea whether that was a smart decision so I had the learning system check it. Turns out, yes,it's slightly better that way for my bot</p>
<p>The codebase is indeed massive, I don't have it in front of me now, but it was at least 15k lines last I checked. Much of that though is quickly written low impact code just adding support for another parameter</p>
<p>Cool! Sounds like your approach was very similar with missions and score functions.I really want to try rl too, perhaps in some hybrid way replacing those scoring functions? Seems difficult to train for though</p>
<p>Hey yes! I was wondering if there were some more halite veterans around! What handle did you use? Hope to compete with you again</p>
<p>While the final games of Lux AI 2 are playing and I'm still uncertain of my final ranking in what's still looking like a close 2-5th place, I thought I'd do a little (long) writeup. I thought this was an exciting competition to take part in, with a deep and very well balanced game that really rewarded different types of strategies. I think we probably only just tapped the surface level of this game, and I'd definitely recommend checking it out even post-competition for fun or perhaps research</p>
<p><strong>Approach</strong></p>
<p>My main approach in this competition was to use C++ logic forming as a skeleton for a large selection (about 1500) of custom parameters that I would tune using custom made statistical analysis tooling. Everything from target selection to combat micro and move conflict management was deeply affected by these parameters. These parameters ranged from serving as a desire adjustment for further tiles, factory spawn tile evaluation, to booleans that could adjust critical if statements or even turn entire functionalities off to overarching multipliers like META_SIMCITY, which would adjust my strategic level desire for peaceful actions (collecting resources, clearing rubble) versus aggressive actions like trying to kill enemy units or digging up enemy lichen. I tried to get most 'opinionated' logic captured in at least some parameter so that I could discover whether my intuition was good. It often was, but there were some real stinkers in there too</p>
<p>I chose this approach because I know it's a very reliable way for me to do well and because it's a lot of fun. I think it combines some of the good parts of rule based bots, such as the ability to really calculate out an optimal solution in places (eg. pathing) and a certain flexibility in strategy and game mechanics, while also taking some of the good parts of reinforcement learning, such as your software slowly intuiting optimal proportions of types of actions. I do believe that reinforcement learning strategies may have somewhat higher potential here, but I didn't go for that as the process has always felt a little unpredictable to me, and just not as fun. And well, I'm not a research group with the available hardware funds to achieve it reliably</p>
<p><strong>Parameter Optimization</strong></p>
<p>I tried to tune my parameters by running a lot of games, in each of which I'd randomize a significant proportion of the parameters (normal distribution for floats, uniform for ints). On every game I'd generate a file with the values of all parameters, whether I'd win or lose and also an assortment of game statistics I thought might be useful, for example the amount of light units I built, the amount of turns units spend digging rubble, the starting rubble on the map, etc. Then, outside of the game in my stats tool I built for halite 2, I would check to see if there was any way to improve the parameters. </p>
<p>For that, I've tried several approaches and rewards. For rewards, some options I picked were chance of victory, the lichen difference with my opponent, the amount of power I produced, the match making rating of associated versions, and even a neural net output trying to estimate my matchmaking rating based on statistics such as the proportion of time my units spend mining ice.</p>
<p>Using this reward, I'd try to find better values using several automatic and manual methods: I've used basic statistical tools such as the Pearson correlation coefficient and Spearman's rank correlation coefficient to see if there was a slope in the data (perhaps I'd win slightly more often if I made my units dig a little bit more ore). Neural nets and random forest tree learning approaches to try to find better values. Just plain old average values of integers or weighted averages of floats. And sometimes I'd just stare at graphs myself and hope to make sense of it. Basically I treated the parameter reward space as an unknown noisy multidimensional function to find a maximum on, but generally made the assumption that complicated interactions between the parameters would be small enough that I could fairly effectively hillclimb by adjusting individual parameters on their individual contributions. I just couldn't generate data fast enough to try and work with anything else </p>
<p>I picked this type of approach over more standardized approaches like simulated annealing, because the amount of games I could run was tiny compared to the amount of parameters I had and there was a lot of noise and I was constantly changing the code as I went. Under those circumstances, that approach doesn't tend to do well</p>
<p>After parameter changes, I'd check to see if there was an improvement on the leaderboard, and revert if not. The leaderboard was extremely noisy, so that may not always have been correct, but I figured it'd be correct more often than not. A nice advantage of this stats orientated approach is that I could often make improvements with low time and brain commitment. I would often take 5 minutes to automatically tweak and upload a new version or two before work, and then the same before going to sleep. Some of my biggest periods of growth were in weeks I had no time to mess with the code while doing this learning</p>
<p>Initially I mostly had both of the agents in a game randomized and learning, for a double learning rate. Later I switched to static reference players to better track my progress. In the end I'm still not quite sure which is better. Static reference players give purer data, but less of it, and I felt there's some advantage in playing against more randomized players too to prevent overfitting. </p>
<p>Some lessons learned here were:</p>
<ul>
<li>This learning approach, even despite all of its randomness, is pretty good at finding the low hanging fruit of improvements</li>
<li>It's also very inconsistent and has a lot of trouble finetuning less important parameters in all the noise. </li>
<li>You would think that if you have thousands of clean datapoints, where you know for sure a causation exists, and you take some parameter and your odds of victory get a Pearson correlation coefficient of 1.05 and a corresponding p-value of 0.0000001 for the null-hypothesis. And on top of that the average victory odds of that parameter are in fact observably higher on a graph. That if you then adjust this parameter upwards, you will start winning more, at least locally. Nothing could be further from the truth, almost every time it will have absolutely no measurable impact. I don't know what this implies, maybe just that I'm bad at stats, but I feel like there has to be some kind of fundamental effect here that consistently overexaggerates or invents apparent effects where there are none. I know it's not just that sometimes with many parameters you just hit the low p value odds, because it consistently happened to more parameters than you would expect. I feel like I might take some time post competition to more properly explore this</li>
<li>Victory chance was probably overall the most effective at getting results. Optimizing for mmr or opponent win rate did almost nothing for me this time (but was very effective in halite). </li>
<li>I found that varying my used reward seemed to work a bit better than consistently applying the same one. Likewise with the used approach for tweaking values. Some rewards I think had insidious side effects, such as if you optimize for proportion of turns spend digging, combat units may want to start dying on purpose. By varying rewards, that effect is limited a little</li>
<li>Manual adjustments using a combination of the Pearson correlation coefficient and my insight into the games generally gave me the most gains. Automatic tweaking using Pearson was fairly effective too. For that I generally used: newvalue = oldvalue + (abs(oldvalue) * pearson * scaler), sometimes with a max change, or requiring a p value below some level. At the start I was very careful, using a low scaler ( < 1), later I discovered using a fake parameter simulation thing, that high scalers and frequent tweaks actually get you to the best value much faster, even with lots of noise and low sample sizes ( < 1000). That did seem to work better, though I often had to manually correct drift. I had a few parameters doing absolutely nothing, and these drifted from 1->0.88, 2->3.81, 3->3.7, 4->2.75, -5 -> -5.39. Which honestly wasn't that bad. Meanwhile actual parameters I must've initially estimated wrong could shift by a factor of 10-100 over the course of the competition, I presume for the better</li>
<li>Using neural networks and random forest trees to try to predict improvements was a waste of time. I think there just wasn't enough data, and enough random noise in parameters for extreme overfitting.</li>
<li>Correlation between local results and the leaderboard were not great but tolerable</li>
<li>It was critical to have a parameter indicating my version number, and to adjust the reward based on the average for that version. This erased a lot of weird artifacts and allowed me to fairly reliably use data across different versions without too much of an impact on results</li>
<li>In the end I probably would've honestly done a little better if I didn't spend so much time on the parameter finetuning, and instead spend more time designing deep game specific algorithms and by watching games and fixing bugs, but I think the experience I gained using this approach was probably more valuable</li>
</ul>
<p><strong>Graphs and power</strong></p>
<p>As a fun side effect of collecting in game data, I could easily find interesting observations and draw cool plots. Honestly I mostly underused this, but there was one graph that had a huge impact on my strategy. But first, let's introduce lichen power generation for those less familiar with it. <br>
For every lichen tile you had, you would generate 1 power per turn. Power was a super critical bottleneck, so that's pretty nice. To create lichen you need to spend water at your factory to water your tiles. This costs ceil(tiles/10) water for both new and already existing lichen tiles. On turns you don't water, all your lichen tiles decay by 1. In most games, most water comes from ice mined by heavy units. You can expect to spend a minimum of 12 power per water, plus probably a bit of loss on inefficiencies. Now much has been analyzed about this mechanic already, but the basics are that ignoring weird integer cutoffs of the watering, you can expect that on a turn that you're watering, you have a cost of 1.2 power per tile, and a gain of 1, for a total change of -0.2. On tiles that you're not watering, you have a gain of 1 power per tile. So if you alternate watering and not watering, you can expect a gain of 0.4 power per tile per turn while keeping your lichen field intact. <br>
This sounds pretty good. By just spending a bit of upfront power, you can grow a large, profitable lichenfield, which additionally is your source of points at the end of the game. Through the power gains, you could invest back even more into the factory, collecting more ice, more lichen, more power. About 1-2 months into the competition, I think the dominating thought was that this was a totally obvious way of making economies work.</p>
<p>The main catch was, that it didn't actually really work. Now, results may be a bit different for other players, but for me it looked like this:</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F557674%2Fc91f315e69ae44daa7a3a26b4cf64bc8%2Ficeprofit.png?generation=1682417547993146&alt=media" alt=""></p>
<p>This is a graph with on the x-axis, the amount of ice I've collected throughout the game ). On the y-axis, it's my total ice profit. Both are divided over starting factory count. Ice profit here is the amount of power I gained from my lichen, minus the amount of power I spend digging for lichen-ice (ice used for the factory upkeep is not counted). The blue lines are different fit lines, purple dots are victories, red dots are losses. The green/red line shows the running average with red meaning few data points</p>
<p>Now I see two main things here. First, I never really made all that much of a profit from ice, on any game. Second, the amount of ice I collected doesn't affect profits as much as you'd hope. The only reason you seem to get a bit more profit on the far right end, is that those are overwhelming victories. For the bulk of games and for losses, there might even be a bit of a downward trend. Now critically, this graph did not include the rubble clearing costs and move/requeue costs necessary for the process. If I include the rubble clearing costs, you get this graph:</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F557674%2F535e0ba0e1b9f2b10b2d73d8ff70475a%2Ficerubbleprofit.png?generation=1682417568260059&alt=media" alt=""></p>
<p>On top of this seeming lack of profits, most of the gains tend to be at the very end of the game where power isn't as useful anymore. Basically, big lichen power is a scam! There's no profit here. Reasons why range from the awkward shapes lichen fields often have to form, which means you require longer water investment stages, to enemy units clearing out your rubble.</p>
<p>Of course you need the points so you might as well water the lichen early to at least sort of run even. But it just isn't quite what it was chalked up to be. Anyway, all of that is just kind of to illustrate that collecting data of this kind can be super useful. In this case, it lead me to go for unit based power generation much earlier, and made me realize that the popular lichen canals used were actually not that good of an idea. While they saved you rubble digging costs of digging out everything around the factory, the shape of the lichen actually meant you ran a bigger loss on the lichen itself, and additionally canals were very vulnerable to harassment. <br>
On the other hand, building units for power generation was much more obviously profitable. You just need to have your units stand still often enough that they don't just burn their generated power. This was far from trivial in a many units style approach like mine. Clogged situations around factories in particular can force many moves when scary enemy units pass by and you gotta handle your conflicts so that units don't run into each other. Getting units to calm down and stop clogging was always one of my largest battles. In the end, most of my units ended up self sufficient, never taking any power from the factories so that I could just direct most factory power to making more units. Here's two graphs showing ice and ore based power profits in a typical game for me (ice profits here ignore rubble costs):</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F557674%2F6cb5369b88d05c07c19ed43cb01901c2%2Ficeprofitabilityreplay.png?generation=1682417603348006&alt=media" alt=""><br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F557674%2Feb5b40c0ba036755630f3e617aeca40f%2Foreprofitability.png?generation=1682417621598366&alt=media" alt=""></p>
<p><strong>Replay viewer</strong></p>
<p>Besides my stats tool, I also used a custom replay viewer designed for my own replay format, which was arguably even more useful. I generated the replay data from within the code of my agent, allowing me to visually present not just objective game data, but also various forms of debugging data.</p>
<p>Here's a quick peak of my replay viewer. The shape of units shows their movement. The fill of units shows their power for easy at a glance viewing. There's some little side-things too like highlights for unit deaths (magenta) and transfers (yellow) and a water carrier highlight. </p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F557674%2F823005a28c53f2b01a83255bab8d7a37%2Freplayviewer.png?generation=1682417639130120&alt=media" alt=""></p>
<p>This image shows the 'base' desires for every tile on the map, this corresponds to how much units will want to go there, before unit-specific adjustments such as distance from the tile</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F557674%2F106ed8896acf4b109cde46ee836fad58%2Freplayviewerdebug.png?generation=1682417661219381&alt=media" alt=""></p>
<p>This viewer was insanely useful for debugging purposes. It's much easier to see what is going on when you can easily see it across the screen like this instead of having to dig through logs. For example, I had an bug in my spawning logic at some point, where I messed up an x and y coordinate, so factories would be preferably spawned on the same column as tiles adjacent to ice. Probably would never have found it if I didn't spot the weird vertical lines in my spawn desire output</p>
<p>For anyone who likes frequenting these kinds of competitions, I'd strongly recommend taking the time to invest a bit in both a reusable custom replay viewer and possibly your own tool to analyze stats. The time invested in any such infrastructure easily pays itself back through ease of debugging, and it's otherwise a great learning experience. </p>
<p>Speaking of learning experiences. I largely chose c++ as my agents language of choice because I wanted to learn the language. That task mostly failed, in that I ended up mostly just sticking to some really basic usages of the language, but at least it was much more performant than alternatives might've been. I mostly used an ugly but effective style, where I had a large collection of global variables I could easily access everywhere at very low performance cost. One critical trick is to precompute everything you can precompute. Perhaps my most used thing throughout the codebase is to iterate over the neighbors of a tile. It was a huge help to just precompute that all once at the start, and never have to worry about performance impact and literal edge cases anymore. Outside of one awkward O(n^2) algorithms that went haywire near ~900 units I never really experienced timeouts. The game still was rather sluggish locally, but a significant part of that was I/O I couldn't really speed up without a total redesign. Oh yeah, preprocessor definitions to avoid logging overhead is cool</p>
<p>Long, accurate action queues were very beneficial here, I mostly did queues through going turn by turn into the future, having every unit determine its course of action for that turn, resolving any move, transfer or pickup conflicts and then forward simulating the next turn. It unfortunately failed quite frequently, especially when units had to adjust for combat, made others scoot over, which then prevented transfers from landing, etc. Overall though my requeue costs were not that bad because I at least got the heavy units on the mines adjacent to the factories (and solar panels) to work predictably. The one thing I really wish I could've done is some system to really have significant information from predicted further turns carry back down to earlier turn in the queue. That unfortunately proved a little too challenging for me to come up with a good performant system, maybe in a follow-up competition!</p>
<p>Throughout most of the competition and until the very end I've been in a tight race with a few other competitors. In particular ry_andy_, Tigga and Harm Buisman. Later to be joined by reinforcement learning player flg. Thanks to them for making this competition very exciting and of course to Stone Tao and to Bovard Doerschuk-Tiberi for organizing this and creating such a fun game. Hope any of that helps someone and I guess I'll see some of you in some future competitions!</p>
<p>Hey loh-maa, good to hear from you! We had been wondering what your approach was, curious to hear more</p>
<p>Looks like my bot online takes about 0.9 secs per turn near the end of the game with lots of units, and about 0.1 the first few turns. Interestingly I could never quite account for a significant part of the used time and think a lot probably gets lost in transfer time to the environment. For example, I just locally measured my code taking a total of 78 seconds for agent 1, 76 for agent 2, but the game last 236 seconds. I think generally C++ is generally significantly faster than python, but if you add functionality until you can't tolerate the runtime anymore, you'll end up with similar runtimes. The difference kind of depends though. For example if you heavily use vectorized numpy functions in python, those are blazing fast. Manually written for loops on the other hand are abysmally slow compared to what you can do in C++. In C++ you can with enough effort and knowledge make anything fast, but it's often not easy to match skilled python library builders, let alone exceed them in speed. </p>
<p>I'm not super familiar familiar with the python cache, but that definitely seems like a great fast solution for most problem. I do recon that the C++ method of storing it in an array is probably a tiny bit faster, since you'd be directly accessing memory locations, which is as fast as it gets, whereas the Python cache probably has to at least include a check internally whether your item is cached before it can return it (or worse: it needs to check some dictionary). The difference is probably negligible in all but the tightest of loops though so the flexibility of caching probably does trump precompution for all but the most difficult performance cases</p>
<p>Must've averaged about 30 hours a week throughout the competition. I didn't compete in beta, so I guess somewhere around 350 hours</p>
|
Lux AI Season 2
|
RL PPO Self-play Solution (Digs and Transfers Water, Survives Full Game)
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lux AI Season 2
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Kaggle code submission: <a href="https://www.kaggle.com/code/sgoodfriend/luxs2-rl-algo-impls-v0-0-12-rl-ppo-selfplay" target="_blank">https://www.kaggle.com/code/sgoodfriend/luxs2-rl-algo-impls-v0-0-12-rl-ppo-selfplay</a></p>
<p>Training repo: <a href="https://github.com/sgoodfriend/rl-algo-impls/releases/tag/v0.0.12" target="_blank">https://github.com/sgoodfriend/rl-algo-impls/releases/tag/v0.0.12</a> (the specific commit the model was trained on was <a href="https://github.com/sgoodfriend/rl-algo-impls/tree/1c3f35f47cfcdb542e10e1666c0a0968dc6f7779" target="_blank">1c3f35f</a>)</p>
<p>Weights & Biases report: <a href="https://api.wandb.ai/links/sgoodfriend/v9g3qfbd" target="_blank">https://api.wandb.ai/links/sgoodfriend/v9g3qfbd</a></p>
<p>After 20 million steps, the agent learned the following skills:</p>
<ul>
<li>Dig for ice and transfer the ice to base. The agent usually manages to survive the game if the opponent doesn’t intervene.</li>
<li>Grow lichen on the map over the course of the game.</li>
</ul>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1298%2Fc5be5b5f760a11d32600d042c3e3868d%2FLuxS2MapResult.png?generation=1683140601660520&alt=media" alt=""></p>
<h2>RL Algorithm: PPO</h2>
<p>The PPO implementation mostly reproduces <a href="https://github.com/vwxyzjn/ppo-implementation-details/blob/main/ppo_multidiscrete_mask.py" target="_blank">vwxyzjn/ppo-implementation-details/main/ppo_multidiscrete_mask.py</a> and uses similar hyperparameters to the Gym-μRTS paper [1]. Lux uses a much bigger map (48x48 vs 16x16 in the Gym-μRTS paper), which required a lot more memory to train. In order to get it to fit I reduced the <code>batch_size</code> to 1152 (from 3072) for an Nvidia A10 GPU and 2304 for an Nvidia A100. <code>n_steps</code> was reduced to keep the 4 minibatches per epoch.</p>
<p>Initial bidding is a random distribution with mean 0 and standard deviation 5. Factory placement logic uses the logic from Abhishek Kumar’s <a href="https://www.kaggle.com/code/scakcotf/building-a-basic-rule-based-agent-in-python" target="_blank">Building a Basic Rule Based Agent in Python</a> with a slight weighing towards building factories near opponents.</p>
<p><strong>“Spike” learning rate decay:</strong> Instead of using linear decay for learning rate, I implemented a learning rate schedule that started 100 times lower, raises to peak at 10% of total timesteps, and drops to 1000 times lower at the end. I hoped the initially low learning rate would allow me to use a higher peak learning rate (<code>4e-4</code>, about 60% higher than Gym-μRTS), since the biggest errors and jumps occur at the beginning. The estimated KL-divergence hovered around 0.005-0.02 for much of the training, not catastrophic, but a higher than the standard recommended 0.01 threshold.</p>
<p><strong>Transitioning dense reward to sparse(-ish) reward over the course of training:</strong> At the beginning of training, the agent gets rewards for digging and transferring raw resources to the factory and gets penalized for losing factories. At the end of training, the agent only gets rewarded/penalized for win/loss, lichen generation, and difference vs opponent in lichen generation. In between, the reward is a linear interpolation based on number of training steps.</p>
<p><strong>Training curve:</strong>The chart below shows ice generation significantly climbing at just before 5 million steps. At 3.3M steps, the agent is averaging a dig action’s worth of ice. By the end, ice generation averages over 40K . Water generation isn’t shown because it closely mimics ice except 4-fold less accounting for the conversion ratio. Episode length lags behind ice generation a bit, but crosses the important 150 step threshold at 5.2M steps (each factory was given 150 water+metal [last factory got less for any used in the bidding]). The training mean score tapers down to ~5 by the end because the reward by the end is primarily win/loss (+10/-10).</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1298%2Fb89c39489680fd10a9e6b4b6cf73787a%2FSubmissionTrainingCharts.png?generation=1683140790910775&alt=media" alt=""></p>
<h2>Autocurriculum</h2>
<p>The agent trained with half the agents playing themselves while the other half played agents with weights from prior versions. The prior agents were selected from snapshots taken every 300,000 steps with a window size of 33 (~10M step history). Every 144,000 steps (6000 steps per environment) the weights are switched out randomly.</p>
<h2>Model: U-net-like</h2>
<p>The Gym-μRTS paper uses an encoder-decoder; however, I went with something U-net-like as it was similar to the paper’s encoder-decoder with the addition of skip connections at each resolution level. The model scaled down the map 4 times to a size of 3x3 at the bottom. The model had ~3.8M parameters.</p>
<p><strong>Critic:</strong> The value head was attached to the bottom of the U-net with an AvgPool2D to allow the map size to change while using the same model.</p>
<p><strong>Actor:</strong> The actor head generates a MultiDiscrete action output for every grid position (what the Gym-μRTS paper refers to as Gridnet). Each grid position has the following discrete action outputs (30 bools):</p>
<ul>
<li>Factory action (4, includes do nothing)</li>
<li>Unit action<ul>
<li>Action type (6)</li>
<li>Move direction (5)</li>
<li>Transfer direction (5)</li>
<li>Transfer resource type (5)</li>
<li>Pickup resource type (5)</li></ul></li>
</ul>
<p>Transfer, pickup, and recharge action amounts are the maximum capable by the robot. The actions are enqueued repeating effectively indefinitely.</p>
<h2>Input</h2>
<p>The LuxAI_S2 PettingZoo ParallelEnv is wrapped in gym Wrappers and an AsyncVectorEnv reimplementation.</p>
<p><strong>Mapping the Lux observation to Gym Box Space:</strong> The Lux observation dictionaries are converted to a Box space of WxH and ~80 boolean and float outputs. Each grid position has information on the following:</p>
<ul>
<li>Board ice, ore, rubble, lichen;</li>
<li>Factory ownership, tile occupancy, cargo, and water survival info;</li>
<li>Unit ownership, cargo, and enqueued action;</li>
<li>Turn, day index, and day cycle info.</li>
</ul>
<p><strong>Invalid action mask:</strong> Actions that would be invalid to the LuxAI_S2 env are masked out by setting the logits of such actions to extremely large negative values, effectively zeroing the probability and gradients. Invalid actions masked out include:</p>
<ul>
<li>Not enough power to even enqueue actions</li>
<li>Not enough power to move to a location (whether base power requirements or rubble) or illegal move into opponent factory</li>
<li>No chance a transfer would lead to a valid destination (so if another friendly robot could be in that location, it’s not masked)</li>
<li>Nothing possible to pickup</li>
<li>Not enough power to dig or self-destruct</li>
</ul>
<p>Generating the above action masks “appears” to be very expensive. Training steps per second dropped from ~120/second to starting at 20-30/s. The reason I say “appears” is that over the course of training, training steps/second eventually climbs to ~250/s. My guess is that early slowness is from the game resetting every ~15 steps (without masking the agent picks invalid actions doing nothing vs the masked agent doing actions that cause factory destruction):</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1298%2F6982bb693c8e4eeee135597cae2606a3%2FTrainStepsPerSecond.png?generation=1683141143403629&alt=media" alt=""></p>
<h2>Performance</h2>
<p>The above chart on training steps/second probably explains why my attempts at improving performance through increased caching and asynchronous execution of environments did not help very much. Even using a modified version of gym’s AsyncVectorEnv to handle passing along action masks through shared memory (<a href="https://github.com/sgoodfriend/rl-algo-impls/blob/1c3f35f47cfcdb542e10e1666c0a0968dc6f7779/rl_algo_impls/shared/vec_env/lux_async_vector_env.py" target="_blank">LuxAsyncVectorEnv</a>) helped little.</p>
<h2>Reproducibility</h2>
<p>The submitted agent was my first agent to exceed mean episode length above 150 steps (each factory got at most 150 water). This important milestone meant the model learned how to dig for ice and transfer the ice to the factory. This agent was also the best performing agent, outperforming followup agents during the competition and apparently outperforming an agent trained on the same commit:</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1298%2Fade52a0a09a270700b41f16efef17bce%2FReproducingSubmissionTraining.png?generation=1683141239740251&alt=media" alt=""></p>
<p>The submitted agent is red. Blue is an agent trained at <a href="https://github.com/sgoodfriend/rl-algo-impls/commit/4f3a500cf1e575c55b06ebc2409d6537493f9207" target="_blank">4f3a500</a> (immediately after the submission version [v0.0.12] and meant to use the same hyperparams as the submission agent). The green line is being trained on the same commit as the submission, but it did worse than both!</p>
<p>The submission agent isn’t a one-off. The blue line is trending towards 1000 step episode lengths (and most runs near the end are averaging over 990 steps [faded blue line]). With more steps and tweaking of the reward shape, training would likely catch up. However, this demonstrates how the same code and hyperparams can lead to drastically different training results.</p>
<h2>Transfer Learning from a Simpler Map</h2>
<p>The same U-net-like model can run on different sized maps since the actor is entirely convolutions-based and the critic uses an AvgPool2D before its fully-connected layers. Therefore, I tried training the agent on a smaller map (32x32) with one factory each for 20M steps and used this trained model as a starting point for the same 20M step full-game training.</p>
<p>The simple-env trained agent was promising. After 20M “pre-training” steps, the agent was producing water reliably (though at an average of 10 per episode, which isn’t enough to survive).</p>
<p>Even more promising, if this resulting model was the starting point of the full-game training, the agent nearly immediately lasts over 150 steps. However, the agent took a while to get out of this local optima, taking ~15M steps before exceeding 300 steps in episodes. By 20M steps, episodes were going for ~600 steps, despite likely collecting enough ice to survive (15K ice → ~3750 water → 3.75 factory-games). This is about one-third of the ice of the submission agent.</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1298%2F3e60de33ce8a76576f828ed1e9b05725%2FSmallAndTransferLearning.png?generation=1683141368677955&alt=media" alt=""></p>
<h2>Next Steps</h2>
<p>20M steps is not nearly enough for RL in a game of this complexity. With more time, I plan on training the agents for 100M+ steps, but with the following improvements:</p>
<ul>
<li><strong>Distinct phases for reward weights, <code>gamma</code>, and <code>gae_lambda</code>.</strong> The thought is to have a Phase 1 where rewards are skewed towards mining and survival lasting 30-50% of the training depending on total steps. Phase 3 will be sparse win/loss + score difference rewards (with higher <code>gamma</code> [0.999] and <code>gae_lambda</code> [0.99] for end-game only rewards), with a transitionary Phase 2. This resembles the Lux Season 1 paper using training phases [2], but with the addition of a linear transition period.</li>
<li><strong>Switch from lichen generation to power generation reward.</strong> Lichen generation is problematic because lichen can be lost by not watering, which the agent could exploit. “Current lichen” is a better metric, but I’m going to switch to power generation, which combines factory survival, number of robots, and number of lichen tiles.</li>
<li><strong>Asynchronous rollout generation instead of asynchronous rollout step generation.</strong> LuxAsyncVectorEnv isn’t that efficient because if one of the 18 environments is resetting, then the entire step has to wait for map generation to complete. Even in the best case scenario of 1000-step games, a reset in one of the environments will happen every 1/55 steps. If instead each rollout of 192 <code>n_steps</code> (A10 GPU) runs independently, then the resets are handled more equally (at most once per environment for 1000-step games, almost one-quarter reset pauses). This effect should be significantly larger at the beginning of training.</li>
</ul>
<p>The goal is for the agent to learn more advanced behaviors such as building robots, clearing rubble, direct competition with the opponent, and late-game strategies.</p>
<h2>References</h2>
<p>[1] Huang, S., Ontañón, S., Bamford, C., & Grela, L. (2021). Gym-μRTS: Toward Affordable Full Game Real-time Strategy Games Research with Deep Reinforcement Learning. arXiv preprint <a href="https://arxiv.org/abs/2105.13807" target="_blank">arXiv:2105.13807</a>.</p>
<p>[2] Chen, H., Tao, S., Chen, J., Shen, W., Li, X., Yu, C., Cheng, S., Zhu, X., & Li, X. (2023). Emergent collective intelligence from massive-agent cooperation and competition. arXiv preprint <a href="https://arxiv.org/abs/2301.01609" target="_blank">arXiv:2301.01609</a>. </p>
|
Lux AI Season 2
|
Solution from QuData
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lux AI Season 2
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h1>Decision for 58 place</h1>
<p>First of all, we are very happy to be part of such a well-developed and interesting competition, many thanks to the organizers for their support and to all the contestants who selflessly shared their knowledge and insights.</p>
<p>Many thanks to <a href="https://www.kaggle.com/kerrit" target="_blank">@kerrit</a>, a member of our QuData team! We are located and working in Ukraine and we want to thank everyone who now supports the people of Ukraine!</p>
<h2>Solution Description</h2>
<p>The solution is a library of several strategies for different stages of the game and active units, as well as some auxiliary functions.<br>
Each strategy is a set of rules on the basis of which the behavior of robots and factories is built.</p>
<p>The solution is based on the <strong>DefaultStrategy</strong> class from the basic.py file. It has a set of mandatory methods for implementing a full-fledged game strategy, in particular:</p>
<ul>
<li><em>getBid(…)</em> - bid selection</li>
<li><em>getSpawnPos(…)</em> - select the position of the factory</li>
<li><em>getActions(…)</em> - action definitions for factories and robots</li>
</ul>
<p>A complete strategy can be implemented in the <strong>DefaultStrategy</strong> class.</p>
<p>Next, the <strong>DefaultStrategy</strong> strategy is divided into two groups <strong>Early</strong> and <strong>Game</strong>.</p>
<h3>Early strategies</h3>
<p><strong>Early</strong> strategies are the strategies of the factory setup phase.<br>
Each of the strategies has a set of mandatory methods for implementing the strategy for the game phase, in particular:</p>
<ul>
<li><em>getBid(…)</em> - bid selection</li>
<li><em>getSpawnPos(…)</em> - select the position of the factory</li>
</ul>
<p>In total, 6 <strong>Early</strong> strategies were implemented, located in the corresponding files.</p>
<ul>
<li><em>default</em> - Basic strategy of the factory placement library. The position for the factory is chosen randomly based on a previously compiled weight matrix. An example of the algorithm can be viewed <a href="https://docs.google.com/spreadsheets/d/e/2PACX-1vSxd6FtgHrewPwfVBQtcwuRW0I46YdhTiy38FRarN9gOhW1b9-N3miff7Gg5rfQ92cEzD_BzV99Htkc/pubhtml?gid=986897905&single=true" target="_blank">here</a>.</li>
<li><em>from_kaggle_strategy</em> - This strategy is an extension of <em>default</em>. The strategy for calculating the weights uses algorithms from the notebook <a href="https://www.kaggle.com/code/istinetz/picking-a-good-starting-location" target="_blank">@istinetz</a>.</li>
<li><em>best_strategy</em> - This strategy is an improvement <em>default</em> in terms of position selection. The most important change was the elimination of randomness in position selection. In this strategy, the position of the factory is chosen based on the amount of rubble in the 3x3 square around the point. In addition, the coefficients of the weight matrix have been slightly changed.</li>
<li><em>single_strategy</em> - Strategy for test training of RL model. Based on <em>best_strategy</em>. A distinctive feature is that only one factory is exposed in the strategy.</li>
<li><em>new_from_kaggle</em> - Strategy using algorithms from notebook <a href="https://www.kaggle.com/code/istinetz/picking-a-good-starting-location" target="_blank">@istinetz</a>. A distinctive feature is that the ratio of the total number of cells around the factory to the "bad" (> 25) cells is used as weights.</li>
<li><em>next_generation</em> - The last and, according to tests, the best strategy implemented in the library. The strategy calculates separate weight matrices for ice and ore, and when choosing a factory position, the amount of rubble in a 7x7 square around the point is taken into account. In addition, if all the best positions adjacent to the ice are occupied, the weight matrix for ice is recalculated.</li>
</ul>
<h3>Game strategies</h3>
<p><strong>Game</strong> strategies are the strategies of the game phase, which are divided into two groups <strong>Factory</strong> and <strong>Robot</strong>.<br>
Each of the strategies has a set of mandatory methods for implementing the strategy for the game phase, in particular:</p>
<ul>
<li><em>getFactoryActions(…)</em> - return actions for factories</li>
<li><em>getRobotActions(…)</em> - return actions for robots</li>
</ul>
<h4>Factory strategies</h4>
<p><strong>Factory</strong> strategies are strategies for how factories work.</p>
<p>In total, 6 strategies were implemented, located in the corresponding files.</p>
<ul>
<li><em>default</em> - Basic strategy for factories. If resources are available, it creates 1 heavy and up to 3 light robots, and after 700 steps it starts growing lichen, reserving 1000-step water.</li>
<li><em>mean_water</em> - Improved <em>default</em> strategy. The strategy uses the average water change per step to calculate the lichen planting step.</li>
<li><em>for_best</em> - New factory strategy for <em>best_strategy</em>. The strategy creates up to 20 light robots, while the number of robots is calculated by the formula $min(max(round(step-step_{start})/l_{ts}*l_{max}, l_{min}), l_{max} )$, where $step_{start}$ - to what step should be $l_{min}$ robots, $l_{ts}$ - in how many steps the number of robots should increase to $l_{max}$. The number of heavy robots is not limited. To calculate the planting time of the lichen, the coefficient of increase in the cost of the lichen per step is also used.</li>
<li><em>for_best_v2</em> - A branch of the <em>for_best</em> strategy. Added accounting for lichen to the strategy, which we will potentially grow in $min(300, 1000-step)$ steps.</li>
<li><em>no_limit</em> - Improved <em>for_best</em> strategy. In the strategy, the threshold for light robots has been increased to 100 per factory, and the number of heavy ones is limited to 6.</li>
<li><em>no_limit_v2</em> - An offshoot of the <em>no_limit</em> strategy. Added accounting for lichen to the strategy, which we will potentially grow in $min(300, 1000-step)$ steps.</li>
</ul>
<h4>Robot strategies</h4>
<p><strong>Robot</strong> strategies are robot behavior strategies.<br>
Robot strategies are the most complex among other strategies and use more auxiliary tools.</p>
<h5>General information about tasks</h5>
<p>In a general sense, the behavior of robots in strategies is determined by <strong>task</strong>.</p>
<p><strong>Task</strong> is a set of algorithms for implementing robot behavior. Initially, the library had two tasks MINER (mines ice) and CLEANER (removes rubble). Later this list was expanded.</p>
<p>The duties of the mining robot included:</p>
<ul>
<li>find the position of the ice,</li>
<li>build a route,</li>
<li>add digging actions if the robot is on a resource,</li>
<li>return to the factory if we can't dig anything else (run out of energy).</li>
</ul>
<p>The responsibilities of the cleaning robot included:</p>
<ul>
<li>find the nearest rubble,</li>
<li>build a route,</li>
<li>add digging actions if the robot is on rubble,</li>
<li>return to the factory if the energy runs out.</li>
</ul>
<h5>Description of strategies</h5>
<p>To implement the algorithms of robot tasks, some auxiliary tools were used. The first of these are <strong>Eyes</strong>.</p>
<p><strong>Eyes</strong> - This is a class that stores game state arrays, and also allows you to conveniently perform various operations with them.<br>
Initially, the <strong>Eyes</strong> data was updated inside the <strong>Game</strong> strategy at every step. In later versions of the library, the <strong>DataController</strong> class was implemented to control the state of the game.<br>
In total, N matrices were used in Eyes:</p>
<ul>
<li><em>factories</em> - Location of enemy factories. All the cells occupied by the enemy's factory were entered in the matrix.</li>
<li><em>units(version 1)</em> - Location of allied units.</li>
<li><em>units(version 2)</em> - Location of allied units or their next turn.</li>
<li><em>units(version 3)</em> - Location of allied units or their next turn. In the case of a collision, the values are added together.</li>
<li><em>u_move</em> - Ally's possible moves. Later versions used robot type instead of 1.</li>
<li><em>e_move</em> - Possible enemy moves. Later versions used robot type instead of 1.</li>
<li><em>u_energy</em> - The energy of an ally, distributed over possible moves.</li>
<li><em>e_energy(version 1)</em> - Enemy's energy distributed over possible moves.</li>
<li><em>e_energy(version 2)</em> - Enemy's energy distributed over possible moves. In the event of a collision, the values are added together.</li>
<li><em>e_energy(version 3)</em> - Enemy's energy distributed over possible moves. In the event of a collision, the values are added together. In the position of the robot - 0.</li>
<li><em>e_lichen</em> - Enemy lichen location.</li>
</ul>
<p>Using only <strong>Eyes</strong> the following 3 strategies were implemented.</p>
<ul>
<li><em>default</em> - The basic strategy of the robots' behavior, the essence of which is that the robots performed only the MINER and CLEANER tasks. The robots took into account the position of the allies when building the route, thereby avoiding the collision with the allies. The task was assigned as follows: heavy robots were always MINER, light ones up to 500 steps were assigned the task MINER after 500 - CLEANER. The strategy used the Eyes matrices: <em>factories and units(1)</em>.</li>
<li><em>cautious</em> - Runaway strategy for robots. The strategy implemented a mechanism for escaping robots. The essence of the mechanism was that if the difference <em>e_energy(1)</em>-<em>u_energy</em> > 0, then we could be crushed and the robot would return to the base. The strategy used Eyes matrices: <em>factories, units(1), e_energy(1), u_energy</em>. Also, this strategy was implemented as a separate GameStrategy as an example of the fact that any convenient approach can be used when implementing the strategy.</li>
<li><em>curious</em> - Catching up strategy. This is an improved <em>cautious</em> strategy. A pursuit indicator was added to the strategists, which was responsible for how many steps the robot would pursue the enemy in order to crush. The strategy used Eyes matrices: <em>factories, units(2), e_energy(2), u_energy, u_move</em>. In addition, the u_energy and u_move matrices were individual for each robot, which eliminated some problems.</li>
</ul>
<p>The next step was to implement the <strong>Observer</strong> auxiliary class, which dealt with the distribution of tasks to robots. The number of tasks has been expanded to: MINER, CLEANER, RETURN (go to base), JOBLESS (unemployed), WARRION (crushes opponents), LEAVER (runs away), RECHARGE (charges). This contributed to more flexible control of robots.</p>
<p>Using <strong>Eyes</strong> and <strong>Observer</strong> the following 2 strategies were implemented.</p>
<ul>
<li><em>optimised</em> - Improved and optimized <em>curious</em> robot strategy for new challenges. The strategy used Eyes matrices: <em>factories, units(2), e_energy(2), u_energy, u_move</em>.</li>
<li><em>fixed</em> - Fixed version of <em>optimised</em> strategy. The RECHARGE(recharging) task was added to the strategy. The Eyes matrices were used in the strategy: <em>factories, units(3), e_energy(3), u_energy, u_move</em>.</li>
</ul>
<p>The last auxiliary is the <strong>TaskManager</strong> class. The tasks of the class include a deeper indication of the tasks of the robot. On the <strong>Observer</strong> class, only the functions of monitoring the environment and informing that the task of the robot needs to be changed remained. In addition, new tasks were defined: WALKER (retreat if an ally is coming at us), CARRIER (removes rubble to the nearest resource), ENERGIZER (charges robots adjacent to the factory), DESTROYER (destroys enemy lichen), the MINER task is divided into ICE_MINER and ORE_MINER, and the tasks themselves were divided into permanent (ICE_MINER, CARRIER …) and one-time (WALKER, LEAVER …).<br>
Permanent tasks are assigned to the robot and are redefined when the robot has run out of queue, one-time tasks are determined only when a certain event occurs (an enemy is coming at us and he will crush us (LEAVER) or an ally (WALKER), we have run out of energy (RECHARGE)).</p>
<ul>
<li><em>next_generation</em> - This strategy fully implemented all the tasks of the robots, in addition, many errors were fixed. In the strategy, thanks to <strong>TaskManager</strong>, the number of robots on tasks was regulated, in particular, the ICE_MINER task was not assigned to three robots if there were only two ices next to us, etc. In addition, the number of ENERGIZER robots was controlled so that there were no more of them than ICE_MINER. CARRIER cleared the path to the resource only in the first 50 steps, and then went to extract the resource. For the ICE_MINER task, priority was given to heavy robots, if there were none, then light ones took their place. The amount of CLEANER was controlled. If the distance to the nearest rubble is > 14, then the robots become DESTROYER or WARRIOR if the enemy did not have lichen. In addition, the total number of MINER robots depended on the current step.</li>
</ul>
<h5>Auxiliary Functions</h5>
<p>The <strong>Path</strong> class was implemented to search for the path of bots.<br>
A distinctively and unexpectedly useful feature of pathfinding is the added window mode. Its essence boiled down to the fact that we are looking for a path not on the entire map, but on a cut-out area with a minimum size of 5x5. The starting point of the route and the end point were located in the corners of this area.</p>
<p>The picture below shows an example of a window mode:</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F11578546%2F4ee6b070461f1d1202be78082ca84c20%2Fwindow_mode.png?generation=1683474895479322&alt=media" alt="Example of window mode when searchin"></p>
<h2>Solution Links</h2>
<ul>
<li><a href="https://github.com/BooCreator/Lux-AI-Season-2-Strategy-Library" target="_blank">Here</a> you can see the full code of the solution.</li>
<li><a href="https://github.com/BooCreator/Lux-AI-Season-2-Strategy-Library/tree/main/strategy" target="_blank">Here</a> is the implementation of the solution strategies</li>
<li><a href="https://github.com/BooCreator/Lux-AI-Season-2-Strategy-Library/tree/main/bots" target="_blank">Here</a> is the implementation of the latest uploaded bots</li>
<li><a href="https://github.com/BooCreator/Lux-AI-Season-2-Strategy-Library/tree/main/strategy/kits" target="_blank">Here</a> is the implementation of all helpers and classes</li>
</ul>
|
Lux AI Season 2
|
Some notes on a pure logic approach (lots of focus on domestic admin, not enough on fighting)
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lux AI Season 2
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Notes below are not highly structured, just a few bits I find worth sharing in my approach (matches the notebook itself well in that sense: it is adequately commented I hope but far from production-ready code and the structure is difficult to penetrate as it is a nasty mix of 3 stages of design: legacy code from my first aimless submission, highly generalised code when I thought I could run 20+ solar panels and multiple ore/ice sources and then code that drops that generalisation to get at least somewhere).<br>
<strong>- Bidding:</strong> bids very high but not dynamically, I came to the conclusion that a bid of 30 upfront is an immaterial cost relative to the benefits of better placement chances (it represents <900 Power in value, so even at only 2 factories this bid sets me back by <10 turns)<br>
-<strong>Placement:</strong> </p>
<ul>
<li>primary score assesses resource situation at a spawn and only spawns with current max primary score are considered; if I run out of spawns with good ice/ore options on their own, friendly factories with their own ice are considered as ice donors if they are not donors yet (making an ore_adjacent factory with no ice an attractive primary score); hides ore/ice sources previously allocated to my own factories and all ice/ore sources within tier 2 of opponent factories</li>
<li>among those, a secondary score picks the winner: key ingredients for secondary score is potential to host mines (applies to placements with own ice: looks to maximise the number of ore sources within radius 20 for later mine placement); also giving a hefty bonus to placements where the factory puts itself between the resource and the closest opponent to make attacking the resource more costly<br>
-<strong>General stuff:</strong> </li>
<li>works extensively with internal record keeping to store knowledge/decisions across turns (all in "permanent_record" which is an unwieldly big dictionary, poorly structured in some places) - done at 3 levels: global, factory and robot (i.e. every robot has it's own entry to remember stuff like it's mission, destination etc)</li>
<li>movement is done via Networkx pathfinding but the edge costs are manipulated to hard-core avoid some places (e.g. opp factories, the parking spots of my solar panels) and discourage others</li>
<li>friendly collisions are avoided by having a "flight-log": persistent record over all future turns, giving for any future turn the list of already reserved locs that turn; any order must check for consistency with said flight-log and if order is feasible and gets committed, it updates the fligh-log accordingly (flight-log clean-up isnt implemented well alas, e.g. when move orders get interrupted the matching entries don't get removed)</li>
<li>orders that take place on specified tiles (e.g. de-rubbling, de-lichening, staging for attack, parking on the defense grid) reserve their allocated tile for the duration of their order execution, but release the reservation (i.e. open it up for another robot) if they get disturbed and abort the mission</li>
<li>orders given by combat code generate an entry blocking a robot from receiving another order until the combat order is fully executed, to avoid counter-ordering (on the assumption that combat orders are always more important that other orders)<br>
-<strong>Factory management:</strong></li>
<li>factories are governed by pre-set scripts (e.g. determining number of attack robots to build, when to stop ore mining etc) and try to follow the outlined script development through phases; </li>
<li>all production is organised through Congas (absolutely no code here that allows for non-conga-mining, which is a grave design flaw); </li>
<li>Dyanmic factory controller mainly reacts to falling below Water and Power safety stocks (SS) levels (by increasing Water production or shutting down Ore production till Power levels recover)</li>
<li>Water SS increases over time to reach 500 water per factory by turn 700 (to have 200 spare water for final lichen growth - once this is achieved across all factories, all ice production is shut down); Ore production shuts down at 650 (as payback is 250 turns and I want max available power at 850 when the main attack starts)</li>
<li>Factories trade water and metal; any factory can launch a Water emergency call and then other factories may respond to this if they can by dispatching a truck (there is also a Metal emergency call, if a factory has a broken Ore conga and no suitable repair robots left); for mine/farm specialised factories, that trade is done regularly plus some metal flowing the other way to balance power production; beyond emergency water trades, there is also option to donate water to ensure roughly equal distribution of water levels across all factories<br>
-<strong>Robot management:</strong></li>
<li>organised around 8ish different roles that robots can be given; typically given at birth, but dynamic reclassification occurs (e.g. trucks are taken by reclassifying light terraform or defender units, and are handed back to that pool upon completion); solar panels peel off from the factory at start of end game to get Heavy attacker or defender role</li>
<li>3 domestic roles for solar panels/production Congas (that differentiation is pretty pointless now, but was important during original design calling for 20+ robot mega factories): they just move into position and then get production/solar generation orders from the factory controller</li>
<li>Each non-domestic robot type has a controller, that typically triggers when it finds a robot of that mission type with an empty order queue: trucks for metal/water distribution, repair to move solar panels into production congas when they are broken; terraformers (given some prio locs, then paths to reduce final attack costs, and general tier 2 tiles only after turn 500 when power is less valuable; defenders (light and heavy); Heavy lichen attackers</li>
<li>Every controller has a recharge option that triggers when the cost to move to the closest factory gets close to power left in the robot<br>
-<strong>Combat management:</strong></li>
<li>home defense is simply an exercise in power management; the base robots (ie those sitting on the factory) are responsible for maintaining the power SS in each exposed robot; so when they start dancing around due to an invader, the base refills them so that they don't run out of power</li>
<li>main combat code is appropriately names SD (Self defense): triggers when stationary robot has an adjacent threat or moving robot is about to enter a tile that can be reached by a threat this turn (i.e. robot of same or higher size with more power); role-dependent preference for stepping away or stepping onto the threat; lichen attackers have a particular preference for stepping away from the attacked factory, in the hope of drawing out defending Heavy robots; for lichen attackers this gets turned of 30 turns before game end to make sure that are (if necessary by suicide) going to delichen Tier 1 (which wont happen otherwise if enemy Heavies are parked inside the factory)</li>
<li>delichen attackers first stage in tier 4 of the attacked factory; then at a fixed turn (870) 4 of them start to delichen; the rest remain inactive until the number of robot doing this drops below 4 (any robot engaged in SD counts as no longer delichening); this is done to preserve power in the attack force and not get into their own way</li>
<li>allocation of attack robots to factories is done giving preference to achieving superiority in Heavy counts over the defenders and then to balance numbers across factories, moderated by the distance to the target factories (which effectively means I do not always send a Heavy attacker to the closest opposition factory)<br>
-<strong>High value features missing</strong></li>
<li>Some code to mine resources without Congas to allow more placement flexibility and react better to breaking of production Congas early on (and even mid-game, probably preferable over a Conga with 2 exposed Heavies as they are still hilariously easy to break)</li>
<li>Actual defense code: detect incoming heavy, pick closest solar panel, have the base unit charge up that solar panel with all the available power, detach the solar panel and have it meet the intruder in the field before reaching the factory; same for lights in the end game to at least slow down delichening by lights; same for heavy defenders in the end game (currently I fake this by giving some Heavy the Terraform mission in the end game, but it would be much better if they chased intruder)</li>
<li>Resource attack code: I have a significant power advantage throughout the midgame, should use this to create attackers to disrupt ore mining (maybe even ice mining); given the globalised attack code structure, I should in theory be able to focus fire a single factory overwhelming it with 6+ Heavy before turn 500 and maybe taking out a factory early</li>
<li>Lichen attackers should get reallocated periodically: often I find 6+ of them huddling around an obviously beaten factory while the factory 1-over isnt delichened yet</li>
<li>There is clearly a bug in SD: the rules of the game mean that robots should be nearly immortal as long as you move a robot threatened by a neighbour and never move it to a tile where a higher power robot could move in at the same turn; if you have code for that, only way to die is heavy congestion (ie no such tiles exist) or you run out of power (which you in theory can avoid by having a dynamic recharge order trigger when you run the risk of that happening)..and yet, my robots die like flies even before I tell them to </li>
</ul>
|
Lux AI Season 2
|
Yet-another-logic-bot
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lux AI Season 2
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>With the competition still ongoing I've no idea whether I'm going to end up 1st or 5th (though judging by the first few days I suspect it'll be 1st-3rd, which I'm very happy with!), but now is the time for the writeup while it's still fresh in my mind! </p>
<h1>General outline</h1>
<p>I went for a stateful rules based bot with no full forward projection, though with some internal forward projection. I wrote it in Typescript. Early on I was planning on doing a team entry with some other Screeps players, but that fell through.</p>
<p>Most of my work was done with self-play, especially for the first couple of months where I had some tricks that other people hadn't figured out yet which I wanted to keep under wraps. Pretty much all of them other people figured out on their own though! This got a bit tricky as per-step runtimes of my agent climbed, with some self-play games taking >20 minutes. I think next time if we're still at 1000 steps of 3 seconds, I may drop down to C++ as I got to the stage where I'd needed 10+ hours on an 8 core machine to get any sort of reasonable data. Season 1 at 360 steps of 3 seconds was much more managable.</p>
<h1>Placement and bidding</h1>
<p>In general I felt everyone was bidding too low throughout the season, but I didn't want to bid higher, because then others would bid higher. Only my final agents bid "high" at 41, chosen because other agents were using 40 as their limit. Bidding was based on a simulation of best placements, then running things through my scoring system. I do rarely bid -1, as placing second was very rarely judged to be an advantage. I set the max range for a resource to be 4 from any factory tile. I noticed others had this set further. I found I'd too often have my chain stalled out if this was the case, but maybe I should have based it on range to enemy factory after everything had spawned. While the majority of my mining was chains I did have support for non-chain stuff which occasionally kicks in.</p>
<p>Placement was designed to focus on good spots with both ice and ore. Having ice within one tiles was heavily prioritized, and having it outside of two was heavily penalized. Rubble and map edges were also penalized. Aggression, where my factory was closer to a resource than the opponent's only source of that resource, was a big bonus, again with ice more important than metal. </p>
<p>If good ore+ice spots could not be found I tried to place ice-only factories, or, to pair with ice-only factories, ore-only factories. I then had metal and water couriers to move resources between them. I'm not sure I saw anyone else doing metal couriers: I reasoned it was better than spawning myself and moving the robot as often ice only factories would have an excess of power. Not 100% sure this was true.</p>
<h1>Robot logic</h1>
<p>I went for a stateful rules based bot. Each robot was spawned to fulfill a "role", and each step each robot would generate the actions to fulfill that role to its best ability. Some roles were quite static, like mining along a chain, while others were given more freedom. In cases where decisions were based on the "target" of another robot, I'd take the latest information - either from something previously run this tick or something run last tick. Everything was iterated through in the same order to keep things stable. The commands could get complicated enough to fill my action queues fairly well (go here, dig that rubble, go back to factory, pickup power, go here dig that other rubble was plenty!)</p>
<p>Once those actions were generated they were passed through a check to see if those actions would change the queue, and if not, nothing was submitted.</p>
<p>All robots went through the same core "starting" logic where they'd do urgent tasks irrespective of role which went down a common path:</p>
<ul>
<li>Clearing lichen urgently (ie. where there was an opportunity to cut lichen off)</li>
<li>Clearing rubble urgently (to reconnect my lichen),</li>
<li>Giving power urgently (usually to a heavy that was at risk of being killed)</li>
<li>Fighting neighbours</li>
</ul>
<p>Safety logic was also shared - I had a very important and expensive <code>checkSafetyForAction</code> function which would try to figure out if any enemy robot could kill my robot before I made it back to the factory. This was a bit more complicated than simply knowing how much power I needed to return home (which I also had) and I didn't really ever get perfect. If a robot "unsafe" or going to become "unsafe" it would ignore it's previously computed set of actions and either go home for more power or sit still and charge.</p>
<p>At the end of every step I'd have a resolver stage that figured out collisions, repathing and bumping/swapping, as well as validating pickup/transfer commands to avoid waste, and adding new transfer commands if they were better than what the robot wasn't doing. I then had a final "emergency" bump logic for when everything else failed and a robot needed to move. Everything else shouldn't have been failing… but there were corner cases in cramped environments that sometimes fell through the cracks.</p>
<p>Robots could transition between roles. For example rubble clearers who got dragged away from their desired target by too much would turn into combat robots. Less important robots could be moved to a different role if a more important role was stuck waiting for metal. Things like that. I feel this was an underdeveloped part of my bot. Often I'd over-provision a role and not have anything stealing the robot for another role. For example: I might over-build rubble clearers, transition them to combat, then realise I needed more rubble clearers after all and not transition back.</p>
<h1>Factory logic</h1>
<p>Lichen growth was one of the trickiest parts to balance as it was rarely clear what the best strategy was. Others have proposed "only do it at the end" and maybe that's correct, though most of the top agents disagree. I tried to balance efficiency (eg. not watering when at 100, trying to minimizes the losses in the ceil(numTiles/10) function) with need for power and the current water situation. I had a forward projection for late game which helped a lot earlier in the event, though once late game attacks on lichen started appearing it became a bit too conservative and often I found myself holding on to too much water at the end.</p>
<h1>Weaknesses/"future work"</h1>
<p>While I don't plan on doing any future work, if I did, there are things I'd take a step back on re-write.</p>
<ul>
<li>Movement in crowded situations. It often ended up a bit too much "first come first serve" with lots of cancelled queues due to blockages. I feel I could have analysed this better to form better queues.</li>
<li>Countering late game heavy lichen blitzing. Seems I lose a lot of games to this. Have to figure out a way to indentify it and combat the blitzers. I tried this with my 10pm final day submission, but it was too rushed. Many games I lose despite being 4x lichen up at step 900 and basically dropping to zero by step 1000.</li>
<li>Less movement. My robots tend to be a bit twitchy and waste power. More "doing nothing" would benefit it.</li>
<li>Better handling of "mobbed" factories (and mobbing myself). A factory can quite easily be denied ice if it's surrounded by enemy factories. Right now I don't really do that.</li>
<li>In general, better attack/defend priorities. It's not really focussed enough right now. For example, I've seen it stop camping the ice of a factory with very low water where camping it would have killed the factory.</li>
<li>Maybe more solar-panel stuff?</li>
</ul>
|
Lux AI Season 2
|
[10th place] Deimos's RL approach
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lux AI Season 2
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Entropy loss always exists. KL teaching loss is added in phase 3, and the previous best model is selected by hand as the teacher.</p>
<h1>Deimos's RL approach</h1>
<h2>Background</h2>
<p>Our colleagues participated in the Lux Season 1 competition last year and conducted an in-depth study on the competition environment. During the preparation phase of this year's competition, we were invited by Stone to rewrite the Lux environment using JAX framework, which resulted in considerable speedup effect (overall user experience still needs improvement and we plan to optimize further in the future). Therefore, we also wanted to participate in Lux Season two to gain first-hand experience.</p>
<h2>Method</h2>
<p>Our policy for this competition remains the utilization of the PPO algorithm, and the specific implementation follows the off-policy approach provided in RLlib. Since the observation space of this season's competition environment is structured similarly to that of the previous season, we have adopted the neural network architecture outlined in [1] for the backbone of our model and have made our code available as a reference in [2]. However, we have also made some modifications to our model that are unique to this season's competition environment, which we will highlight in the following sections.</p>
<h3>Feature space</h3>
<p>The feature space consisted of three main components: global information, map features, and action queue. Each component was designed to capture critical information that allowed our robot to operate efficiently in the given environment.</p>
<ul>
<li><p>Global Information<br>
The first component of our feature space is global information, which includes the current time phase of the environment (step, cycle, hour) and the total number of robots and resources. We utilized one-hot encoding to represent certain features, resulting in a feature dimension of 32.</p></li>
<li><p>Map Features<br>
The map feature component contained information about the resources (lichen, ice, ore, rubble) present in each block as well as the robot (unit, factory) located in each block. The feature dimension was designed to be 48x48x30.</p></li>
<li><p>Action Queue<br>
The last component of our feature space was the action queue, which represented the current set of actions in robots' queues. This component had a feature dimension of 48x48x20x6.</p></li>
</ul>
<p>To encode our feature space, we then replicated this encoded global information for each grid. We used ResNet to merge the three components to achieve maximum efficiency. </p>
<h3>Action related</h3>
<p>The biggest challenge for RL players was managing the massive action space in the second season. To address this, we restrict the number of actions sent to a robot to one per turn, i.e., we completely ignore the action queue, and turn it into a real-time control problem. Unlike flg's approach, we allow the action to be repeated, thus some power can be saved. Besides, we implement a relatively complicated conditional sampling as follows.</p>
<h4>Sampling Order for action sequences</h4>
<p>We sample different dimensions of action in the following order.</p>
<ul>
<li>Action type (move, transfer, pick up, dig, self-destruct, recharge, do nothing)</li>
<li>Action direction (5 directions)</li>
<li>Resource type for action (ice, ore, water, metal, power)</li>
<li>Quantity of resources for action (float, 0-1)</li>
<li>Infinite repeat or not (boolean)</li>
<li>n (integer)</li>
</ul>
<p>The dimensions sampled before affect the dimensions sampled later, so the whole action spaced is modeled as a conditional probability distribution.</p>
<pre><code> P(type, direction, resource, quantity, repeat, infinite)
= P(type) * P(direction | type) * P(resource | type, direction) * P(quantity | type, direction, resource) * P(repeat | type, direction, resource, quantity) * P(n | type, direction, resource, quantity, repeat)
</code></pre>
<h4>Continuous Value Sampling</h4>
<p>From the action space of the unit type robot described above, we can observe that the quantity of resources operated is a ranged real value, such as $[0,1]$. Generally, for actions involving continuous numerical values, researchers usually model them as a Gaussian distribution, but the gaussian distribution is unbounded, so some truncation is needed. Here, we adopted a more reasonable distribution, the beta distribution, which falls into $[0,1]$ by nature. The advantages of this approach can be found in our reference at [3].</p>
<h2>Model Architecture</h2>
<p>In brief, is an 8-layer-deep 64-neuron-wide Resnet with some additional feature pre-processing layer and action/value head. The backbone is the same as [1], and the specific implementation can be found in [2]. </p>
<h2>Training && Performance</h2>
<h3>Random Initialization</h3>
<p>The distributed reinforcement learning framework consists of two types of processes:</p>
<ul>
<li>Rollout worker : interact with the environment to generate data, and </li>
<li>Trainer : perform policy optimization.</li>
</ul>
<p>As this competition is a perfect information game, we set Rollout worker to play against itself, i.e., self-play. However, we found that the model did not explore new game states during the training process. Therefore, we downloaded a large number of replays from the Kaggle, randomly selected various game state from them, and used these intermediate states as the initial settings for the self-play process. This helped our strategy to explore many game situations that were difficult to evolve through self-play, and the data download can be referenced via the Lux season one sharing blog.</p>
<h3>CURRICULUM LEARNING PHASES</h3>
<p>There are three main phases during the training process.</p>
<ol>
<li>dense reward + rule-based factory spawning</li>
<li>dense reward + neural network factory spawning</li>
<li>sparse reward + neural network factory spawning</li>
</ol>
<h4>Phase1</h4>
<p>The reward is set to dense reward as shown in the table below, and in this phase, we wrote a script for choosing factory spawning location and initial water/metal. In addition, if a player loses the game, it will be penalized by a large negative reward, which cancel out all its past reward. Thus, only the winner get positive reward in this phase.</p>
<table>
<thead>
<tr>
<th>Reward type</th>
<th>value</th>
</tr>
</thead>
<tbody>
<tr>
<td>reward for victory</td>
<td>0.1</td>
</tr>
<tr>
<td>penalty for defeat</td>
<td>-0.1</td>
</tr>
<tr>
<td>light units increment</td>
<td>0.04</td>
</tr>
<tr>
<td>heavy units increment</td>
<td>0.4</td>
</tr>
<tr>
<td>ice increment</td>
<td>0.0005</td>
</tr>
<tr>
<td>ore increment</td>
<td>0.001</td>
</tr>
<tr>
<td>water increment</td>
<td>0.001</td>
</tr>
<tr>
<td>metal increment</td>
<td>0.002</td>
</tr>
<tr>
<td>power increment</td>
<td>0.00005</td>
</tr>
<tr>
<td>growing lichen</td>
<td>0.001</td>
</tr>
<tr>
<td>penalty for losing factory</td>
<td>-0.5</td>
</tr>
<tr>
<td>reward for surviving in this round</td>
<td>0.01</td>
</tr>
</tbody>
</table>
<p>Most of the reward can also be a penalty. For example, if a player builds a light unit, it will get a reward of 0.04, but if it loses the light unit, it will get a penalty of -0.04.</p>
<h4>Phase2</h4>
<p>The dense reward as described above is still used in this phase, but the factory spawning is now decided by the neural network. This phase is quite short. As long as robots know how to collect resources during phase 1, neural networks can learn to spawn factories in a few hours.</p>
<h4>Phase3</h4>
<p>In this phase, we switch to a sparse reward.</p>
<table>
<thead>
<tr>
<th>Reward type</th>
<th>value</th>
</tr>
</thead>
<tbody>
<tr>
<td>reward for lichen increment</td>
<td>0.001</td>
</tr>
<tr>
<td>reward for surviving in this round</td>
<td>0.01</td>
</tr>
</tbody>
</table>
<p>During this phase, the reward for lichen increment is zero-sum. All lichen reward a player gain will also become a penalty for its opponent, so the goal for a player becomes to gain more lichen than its opponent.</p>
<h1>Conclusion</h1>
<p>Our training gets a smooth start, and we can see the ELO score increase steadily. However, it was stuck around 1900 in the last two month. We did lots of experiments to improve the ELO score, but none of them worked. In general, our approach is quite similar to flg's. Both ours and flg's follows last year's champion's approach, but in detail, we have different action space modeling, different rewards, and different curriculum learning phases. Maybe there is a bug; maybe our action space modeling is too complicated; maybe our reward is not good enough. We can't figure out the reason, because RL system is too complex to debug. It consists of too many components, and each component has too many hyper-parameters. Most time, if you did wrong in one component, you just get a bad ELO score silently without any explicit exceptions. Despite all the above, we still want to share our approach with you. </p>
<h2>References</h2>
<pre><code>[1] Chen, H., Tao, S., Chen, J., Shen, W., Li, X., Yu, C., Cheng, S., Zhu, X., & Li, X. (2023). Emergent collective intelligence from massive-agent cooperation and competition. arXiv preprint [arXiv:2301.01609](https://arxiv.org/pdf/2301.01609.pdf).
[2] https://github.com/RoboEden/lux2-deimos
[3] Po-Wei Chou, Daniel Maturana, Sebastian Scherer Proceedings of the 34th International Conference on Machine Learning, [PMLR 70:834-843, 2017](https://proceedings.mlr.press/v70/chou17a.html).
</code></pre>
|
Lux AI Season 2
|
[15th place] A goal-based logic bot & code.
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lux AI Season 2
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>This was my first time competing in a competition of this kind and building a logic bot. I have found it extremely interesting to compete and recommend it to people who were on the fence about joining this year. It is a great experience to code your bot and then visually see it perform against other bots. The game design has been superb, creating some new types of challenges. There have been a few pitfalls for me in this competition, which I would like to share with you. Hopefully, this will help some people avoid them in the future.</p>
<p>In this post, I will first quickly explain the game. Then I will go through my design. After that, I will go through my pitfalls and end by going through what I would have liked to do if I had had more time.</p>
<h2>Python Code</h2>
<p>For anybody interested in the code, it's stored on <a href="https://github.com/BartvonMeijenfeldt/LuxAISeason2Bot" target="_blank">GitHub</a>.</p>
<h1>Game Summary</h1>
<p>The LuxAI 2 challenge is a 2-player zero-sum game where both players compete to terraform Mars by building the most lichen in 1000 time steps. They start with a few factories and enough resources to build a few units. During the game, the units can collect two types of resources—ore for building new units, ice for keeping the factories alive and watering lichen. Lichen, besides counting for the score at the end of the game, also generates power that units need to perform actions. In general, power was a very scarce resource in this game, so efficient power usage was essential.</p>
<p>There are two types of units: a light unit which is more power-efficient, and a heavy unit able to dig more per turn and therefore has higher resource utilization. Units execute actions and require power to perform these actions.</p>
<p>If two units collide, the stronger one survives. If they are the same type and one unit is stationary, that one is lost. If they are both moving, the unit with the most power survives. When your units collide with each other, the same rules apply. Therefore avoiding collisions between your units is extremely important. This wasn't easy because you control your unit not by sending its next action but by updating an action queue which can easily consist of 50 actions. One could update the action queue for every unit at every step, but this is quite costly, as it costs power every time you update the queue.</p>
<h1>Final design</h1>
<p>I switched my design around a few times during the competition, but in the end, I ended up with the following design.</p>
<h2>Factories decide on strategic focus</h2>
<p>Each unit is assigned to the factory that spawns them, and the factory will decide, based on its current resources, the game time step, and the goals that it already scheduled, what currently is the highest priority strategy for its units to focus on. Some examples of these strategies are to increase lichen, collect ore, attack the opponent or defend a lichen tile. Based on these strategies, an attempt is made to schedule the most suitable unit for this task. The unit selection picks the unit that, at a glance, appears to have the highest value per step (explained in more detail in the get_best_case_value_per_step section). If none of the factory's units can be scheduled to aid in this strategy, an attempt will be made to schedule a unit on the next highest priority strategy. After a factory schedules a unit, the factory recalculates the priorities of the strategies again to decide where to schedule the next unit. This loop continues until all units are scheduled, or no unit can be scheduled on any relevant strategy.</p>
<h2>Units carry out strategic focus with goals</h2>
<p>I ended up with 11 different goals for units. These goals either directly contribute to fulfilling a strategy or help the unit survive( e.g. fleeing from opponents). For example, these goals include collecting ice at a specific coordinate (x, y), clearing out rubble at a specific coordinate or destroying a specific opponent's lichen tile. The abstract base class of these goals have the following methods: get_best_case_value_per_step, generate_action_plan and get_value_per_step_of_action_plan.</p>
<h3>get_best_case_value_per_step</h3>
<p>To evaluate goals, I used the following simple formula:<br>
value_per_step = (power_benefit – power_cost) / nr_steps</p>
<p>This method, at a glance, estimates this formula for the best-case scenario of scheduling a unit on a goal without computing an exact action plan. To estimate the power benefit of each goal, I created a formulate which contained some parameters I could tweak. Then to decide on the parameters, I tuned them based on the performance on the leaderboard.</p>
<p>To quickly compute the best-case scenario, we assume that everything is optimal. E.g. to collect ice for a unit, we would calculate the distance it would take to go there without being obstructed by any unit, there to be no rubble on the way, and the unit max number of digging the ice out is based on the state to be day meaning that power is generated each step and then goes back to the factory to return the power.</p>
<p>These best-case values for goals are used to select the most suitable unit for a strategy. E.g. if we want to increase ore to build units, all units belonging to a factory that are not scheduled on a goal yet, are asked to compute their best-case values of mining ore on the ore tiles around them. The unit with the best value is selected, and for this unit, we will carry out the expensive method, generate_action_plan.</p>
<h3>generate_action_plan</h3>
<p>To get from a goal to an action plan, a specific set of actions, you will need some type of planning algorithm. I used <a href="https://en.wikipedia.org/wiki/A*_search_algorithm" target="_blank"> A* </a> as the basis. A* is an algorithm similar to the more famous Dijkstra's algorithm but can better prioritize the most promising node if you can set accurate lower bounds on the remaining cost to reach the endpoint. In a grid world, as in this game, a reasonable lower bound can be obtained based on the distance to the final node. Goals are broken down into some subgoals (e.g. move to a factory and pick up power, collect ice and transfer ice to the factory) to reduce the planning horizon, which improves computational performance significantly. However, the found solution can be slightly worse than the optimal solution.</p>
<p>Another crucial task to solve is ensuring that your units don't collide. This is especially hard in this game, as we are not planning one step at a time per unit, but we update action queues containing multiple actions. For our planning algorithm, this means we must also consider other units' action plans. In the end, I used a reservation table for this. Which works in a first come, first serve manner. The first unit to be scheduled will reserve the time coordinates (x, y and t=time) corresponding to its action plan. Then any future unit planning will not be allowed to be on those coordinates and will generate its action plans accordingly.</p>
<h3>get_value_per_step_of_action_plan</h3>
<p>Given that we now have the exact action plan of the unit, we can calculate the value per step of this plan precisely. It was essential to do this, as in the middle game, often there are more units than worthwhile goals to carry out. If you always schedule your units on goals, you end up using too much power, and then your units will eventually have too little power left for the most important goals. Therefore, goals with negative values are never scheduled.</p>
<h1>Pitfalls</h1>
<h2>All units performing the same strategy</h2>
<p>At the start, every unit thought for themselves what the most worthwhile goal was, and they were not assigned to a factory. Using a <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.linear_sum_assignment.html" target="_blank">sum-assignment problem solver</a>, units were assigned to specific goals. This has one big drawback. Often all units ended up performing the same goal. E.g. if the parameters of ice mining were slightly more favourable than ore mining and there were many ice resources around the factory, the units would only collect ice, neglecting the ore resources completely. Then I would end up with a lot of ice but no ore to build new units. Similarly, if ore mining was slightly more favourable, I might end up with many units but no ice and, therefore, no lichen to generate power for these units. </p>
<p>Therefore, some self-balancing rules were required in the planning algorithm. I ended up scheduling units to perform goals based on their factories' needs. After the factory schedules a unit on a goal, it recomputes its most important strategies using the last scheduled unit's goal. For example, suppose the factory scheduled the last unit to collect ore. In that case, it will soon build new units, so it will now prioritize the strategy of generating power for these future units.</p>
<h2>Optimal goal resolution</h2>
<p>The biggest pitfall I spent a lot of time on at the start was attempting to compute the perfect joint plan at every step. I was using conflict-based planning for this. The idea of this algorithm is that first, every unit comes up independently with its action plan to complete its goal. After this, we validate whether the joint plan is valid, i.e. does it not contain any collisions? If any units' paths collide, we split the problem into two sub-problems, one where the first unit is granted the time coordinate and one where he isn't. Then, in my implementation, I would reconsider the best distribution of goals given this restriction (if a unit is not granted its optimal path, it might be better to have the unit perform a similar goal on an unblocked path). Then the unit that was not granted its optimal path will generate a new action plan. If this is invalid again, we split the problem in two another time. In a branch-and-bound style, we focus on sub-problems whose optimal value is most promising and repeat this process until a node is found with the best-case joint value and without collisions.</p>
<p>At the start, this worked out well and created joint action plans which were always optimal. But as I started to build more efficient economies and my unit size increased, collisions increased, and no collision-free joint plans were found in time. To solve this, I spent significant time optimizing the code to generate action plans under the time limit. But it appeared impossible to get this to work. Therefore, in the end, I switched to using a reservation table, which, although might not grant the perfect solution, is magnitudes faster and allowed me to focus computational resources and, more importantly, my available programming time for this project on more important parts.</p>
<h2>Under-utilizing logging</h2>
<p>I underestimated the complexity of building a bot to control 100+ units. At the start, when a bug popped up, I figured out the problem using the debugger and carried on. But there were two big disadvantages in mainly using the debugger vs logging. One was that matches often took more than 20 minutes, so replicating this state in debug mode was time-consuming. Also, there were some recurring problems which are harder to detect in debug mode. For example, I had some situations where some units were scheduled on a goal, but then another unit got scheduled on the same goal. The original unit would be unscheduled but would later schedule themselves on this goal. Detecting this takes a decent amount of effort using a debugger, especially when other units are scheduled in between as well. But this is very easy to detect by logging every scheduling and unscheduling decision.</p>
<h2>More parameter optimization and better evaluation</h2>
<p>The best way to know if your bot is improving is by comparing it against opponents on the leaderboard. Therefore it is essential to make good use of your five daily submissions. Unfortunately, I focused too much on adding in all the functionality needed for the bot, planning to focus on optimizing the parameters at the end. But in the end, I realized there was a lot more I wanted to test than the number of uploads I had left. Looking back, I should have started using all my uploads from the start, as it takes little effort to tune a few parameters each day.</p>
<p>To make the best use of these uploads, it helps to evaluate them as accurately as possible. Kaggle's rating system jumps around a lot, especially before the final submission date. For leaderboard reasons, this might be optimal, but for accurate performance evaluation in a day of games, there might be better options. I haven't found much information on the Kaggle rating system, but I believe it works similarly to the <a href="https://en.wikipedia.org/wiki/Elo_rating_system" target="_blank">Elo</a> and <a href="https://en.wikipedia.org/wiki/Glicko_rating_system" target="_blank">Glicko</a> rating systems. In these systems, the impact of recent games is more important than that of old games. This makes a lot of sense for the original domains of these methods, sports. But for static bots, you can be more accurate by using a method that assumes a stationary level of the competitor.</p>
<h1>Improvements if I had the time</h1>
<h2>Changing the goal-scheduling method</h2>
<p>During the competition, I set up my scheduling in two different ways, both with their shortcomings. When units schedule purely by themselves, they might end up performing goals irrelevant to the factory. On the other hand, when factories focus only on the most critical strategy, this might lead to poorly accomplishing the most important strategy instead of efficiently accomplishing the second most important strategy. I would have wanted to combine the two methods by multiplying the goal's value by the strategy's importance. The importance of the strategy should then be a number whose average value is approximately 1. </p>
<h2>More focus on attack/defence goals</h2>
<p>Initially, I spent most of my time getting the planning algorithms to work correctly, quickly enough and without collisions. Later, I struggled with balancing my economy. There was also a lot of small functionality to build in, e.g. differentiating between a unit's private action plan and the action queue it sends to the environment and precisely calculating the power of this action plan, including the moments it will update the action queue.</p>
<p>In the end, I ran out of time to properly implement the defence goals and also some attacking goals. I did implement clearing out the opponent's lichen decently, but defending ice tiles close to my base or defending my lichen was rushed and did not work properly, nor was it prioritized appropriately by the factories. Neither did I have the time to implement camping important opponent resources or capturing opponent's units low on energy and far away from their factory, where they are safe. Lacking these capabilities hampered the performance of my bot severely.</p>
<h1>Conclusion</h1>
<p>In conclusion, it has been a great experience. I want to thank Stone Tao for creating such a rich competition environment. I have learned a lot by competing here. I hope this write-up helps some people avoid my pitfalls for the next challenge. And lastly, I can't wait to see what LuxAI Challenge 3 will bring!</p>
|
Lux AI Season 2
|
[76th place] Another fork of "Building a Basic Rule Based Agent in Python"
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lux AI Season 2
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h1>[76th place] Another fork of "Building a Basic Rule Based Agent in Python"</h1>
<h2>Intro</h2>
<p>First of all, big thanks to the organizers for hosting such a great competition! It was really interesting and fun all the time during the competition timeline!<br>
Big thanks to the community for the inspiration and interesting discussions - It was really cool to be a part of it.<br>
Special thanks to <a href="https://www.kaggle.com/scakcotf" target="_blank">@scakcotf</a> for posting their public kernel - it really helps me to start my season 2 journey, not even sure I came up with something without this baseline!</p>
<h2>Approach</h2>
<p>The solution is a rule-based agent improved from the <a href="https://www.kaggle.com/code/scakcotf/building-a-basic-rule-based-agent-in-python" target="_blank">scakcotf baseline</a> consisting of mostly predefined factory behavior, and somewhat dynamic robots reaction for the environment.</p>
<h3>Early stage</h3>
<p>Taken from the baseline with almost no changes.</p>
<p>Bid 5 then place all the factories by simple heuristic to score each possible spawn location based on:</p>
<ul>
<li>rubble density</li>
<li>distance to the closest ice</li>
<li>distance to the closest ore</li>
<li>distance to the closest opponent factory</li>
<li>distance to the closest player factory</li>
</ul>
<h3>Main stage: Factories</h3>
<p>Factories first build robots and assign their tasks based on the predefined sequence then mostly stay inactive during the game. They also detect opponent appearances nearby and assign a robot to defend the area.<br>
Starting from turn 800 factory grows lichen, if it has enough water to do it all the following turns (determined by a simple heuristic).</p>
<p>The final agent does not heavily rely upon economics and does not dig ore or generate power. Only a few robots are built - one heavy and 4-5 light, which allows them to not experience a severe lack of power, but survive till the end if no intervention occurs, and prepare enough space for lichen growth.</p>
<h3>Main stage: Robots</h3>
<ul>
<li><p>Each robot belongs to a particular factory, which is its place to return gathered resources and take power. </p></li>
<li><p>Robots have one of the tasks given by the factory and obey the logic it determines. </p></li>
<li><p>Every robot reacts to opponent closeness: try to destroy the enemy robot if can, and escape to the safe zone otherwise</p></li>
<li><p>Paths for robots are built using graph shortest path algorithm as described in <a href="https://www.kaggle.com/code/jtbontinck/shortest-path-on-mars-using-networkx" target="_blank">this notebook by jtbontinck</a>.</p></li>
<li><p>Collision avoidance was handled in “real-time”, every robot check if it can move further, and if the cell was already occupied - change its direction.</p></li>
<li><p>Actions were computed each turn, and action sequences were used for power usage optimization. The robot creates a sequence of all the following actions determined by its task, then compares the new sequence with the existing one: if the first action is the same, the queue was not overwritten.</p></li>
</ul>
<h4>Tasks: Ice</h4>
<p>Task handled by the first heavy robots. Simply digs the closest ice, and return to the factory to transfer it if the cargo is full and takes power. Additionally, urgent transfer was added: if the factory is out of water, and the robot has ice in the cargo - it returns back immediately.</p>
<h4>Tasks: Rubble</h4>
<p>Handled by light robots - digs closest rubble or enemy lichen, returns to factory if discharged.<br>
A few restrictions were added:</p>
<ul>
<li>ignore rubble on resource tiles</li>
<li>ignore tiles that prevent opponent lichen from spreading</li>
<li>consider rubble tiles only in a specific radius around the factory, or adjacent to lichen.</li>
<li>if there is no rubble to dig - wait near the radius border to prevent crowding</li>
</ul>
<p>The last two restrictions, which were originally added to prevent robots from digging too far from the factory, accidentally result in some interesting behavior - when their base cleaning is done, robots start to help other factories with cleaning, and massively attack enemy lichen. Actually, these features help to do the last score gain and stay in the bronze.</p>
<h4>Tasks: Ore</h4>
<p>Same as ice: find the closest resource - dig - back to the factory to unload and recharge. Was not used in the final agent.</p>
<h4>Tasks: Kill</h4>
<p>The logic for an attacking robot - find go to the closest opponent robot, and try to fight it with common simple fights logic. Was not used in the final agent.</p>
<h4>Tasks: Defend</h4>
<p>The same code as Kill, but treated by the factory differently. When the opponent robot appears close to the factory - one of the factory heavies changes its task to defend and tries to strike the enemy. If the enemy was destroyed or had left the factory area - all defenders were revoked back to normal tasks.</p>
<h2>Summary</h2>
<p>A few things I have learned during the competition:</p>
<ul>
<li>Rule-based approach is extremely fun</li>
<li>Bugs. Bugs everywhere. All the time during the competition I have the higher gain not by implementing features, but by making them actually work!</li>
<li>Code organization really matters. Suboptimal code organization - suboptimal agent logic. Keep it in mind, and don't be like me 😄</li>
</ul>
<p>Thanks for reading, and hope to see you in season 3!</p>
<blockquote>
<p>P.S. Code can be found here - <a href="https://github.com/andrii0yerko/lux-ai-s2-2023" target="_blank">https://github.com/andrii0yerko/lux-ai-s2-2023</a></p>
</blockquote>
|
Lux AI Season 2 - NeurIPS Stage 2
|
PPO using Jux - Lux AI Season 2 - NeurIPS Stage 2 Competition Solution
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lux AI Season 2 - NeurIPS Stage 2
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks! Your <a href="https://www.kaggle.com/competitions/lux-ai-season-2/discussion/406702" target="_blank">Lux AI Season 2 solution write-up</a> and <a href="https://www.kaggle.com/competitions/lux-ai-season-2/discussion/411725" target="_blank">Deimos's write-up</a> were both extremely helpful for me.</p>
<p>Implementing and verifying the GridNet observation, action mask, and action handling logic with Jax was definitely a project. Unfortunately, for the competition, I only had a few days of training with the final version of the observation and action mask. Training on the larger map sizes has been challenging, especially when trying to improve upon a model trained on a smaller map size. Your idea about adding an additional loss term that's the KL-divergence from a prior checkpoint is interesting. I'll have to try that out.</p>
<p>To answer your questions:</p>
<h2>Did your agent build any light units?</h2>
<p>Not in a meaningful way. The competition submission agents mostly built lights near the end if they couldn't build heavies:<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1298%2F06ff88ff884a050d4d9282904b51debc%2Frobots_generation.png?generation=1702334883676506&alt=media" alt="robots_generation.png"></p>
<p>Follow-up training with the <a href="https://github.com/sgoodfriend/rl-algo-impls/blob/640324b8e9ca9437fdcc021cb3a8659ec8cf28df/rl_algo_impls/lux/docs/lux_s2_neurips_writeup.md#next-steps" target="_blank">Next Step ideas</a> has generated agents that do build lights (and significantly more heavies). On 32×32 maps (still training on smaller than competition-sized maps), my agents will build about 10 heavies and 60 lights. Starting resources would only make 3-4 heavies. <a href="https://api.wandb.ai/links/sgoodfriend/8ozskssn" target="_blank">Lux S2 NeurIPS Follow-up Training Report</a></p>
<p>Below is a replay of a 32×32-trained agent playing on a competition-sized map:</p>
<h2>Action queues were done via repeating the current action?</h2>
<p>Yes. Actions are enqueued with num_executions set to 1000. Recharge actually clears the action queue. Your solution of forward simulating the game to build an action queue would definitely improve this agent, but that's an entirely other project…</p>
<p>Kaggle competition: <a href="https://www.kaggle.com/competitions/lux-ai-season-2-neurips-stage-2" target="_blank">Lux AI Season 2 - NeurIPS Stage 2</a></p>
<p>Kaggle code submission: <a href="https://www.kaggle.com/sgoodfriend/lux2-neurips2-ppo-using-jux" target="_blank">https://www.kaggle.com/sgoodfriend/lux2-neurips2-ppo-using-jux</a></p>
<p>Training repo: <a href="https://github.com/sgoodfriend/rl-algo-impls" target="_blank">https://github.com/sgoodfriend/rl-algo-impls</a>. Best submission is from <a href="https://github.com/sgoodfriend/rl-algo-impls/commit/28e662dc34fb32a22a14ec2018e13a3b30aa6699" target="_blank">28e662d</a>.</p>
<p>JUX fork: <a href="https://github.com/sgoodfriend/jux" target="_blank">https://github.com/sgoodfriend/jux</a>. Biggest changes are to support environments not being in lockstep, stats collection, and allowing for adjacent factories (for 16x16 map training).</p>
<p>Weights & Biases report: <a href="https://wandb.ai/sgoodfriend/rl-algo-impls-lux-nips1/reports/Lux-S2-NeurIPS-Training-Report--Vmlldzo2MTMyODc3?accessToken=a8xwpu4xi7zavhwmyavxt5lbiejk6wjn1o2eh3v8c3lc416bo11oatirp2pxlzet" target="_blank">Lux S2 NeurIPS Training Report</a></p>
<h2>Environment</h2>
<p>Jux allows training with vectorized environments using Jax. I used 1024 environments for training on 16x16 and 32x32 maps and 512 environments for training on 64x64 maps. I’m using a fork of <a href="https://github.com/sgoodfriend/jux" target="_blank">Jux</a> for training. The fork has the following changes and extensions:</p>
<ul>
<li><a href="https://github.com/sgoodfriend/jux/commit/5f40da58e5fd05537484abcd02d2c9af48bb6fc4" target="_blank">Fix incorrectly computing valid_spawns_mask.</a> This was broken on 16x16 maps. I'm not certain if it was wrong on competition-size maps.</li>
<li>EnvConfig option to support adjacent factory spawns (default off). I use this for 16x16 map training because the default requirement of 6 spaces away could push factories too far away from resources on such small maps.</li>
<li>Reward -1000 if player lost game for no factories (mimics Lux)</li>
<li>step_unified combines step_factory_placement and step_late_game</li>
<li>Environments don’t need to run in lockstep and can have different numbers of factories to place (externally replace individual envs with new ones when they finish)</li>
<li>Stats collection (generation [resources, bots, kills], resources [lichen, bots, factories], actions)</li>
</ul>
<p>I convert the Jux observation to a GridNet observation with the following observation features for every position:<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1298%2F3f878f9ba51a34d536107f98e3d40001%2FScreenshot%202023-12-06%20at%2015.21.57.png?generation=1701904948509595&alt=media" alt="observation_space.png"></p>
<p>I take care of computing amounts of resources in my action handling logic. The model only handles position for factory placement while I assign the initial water per factory (150) and enough metal for 1 or 2 heavy units (100 or 200) or 150 if not possible. For example, for 1 to 4 factories to place:<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1298%2F460d5be764d8e1b750f131673e199c60%2FScreenshot%202023-12-06%20at%2015.22.30.png?generation=1701904993242219&alt=media" alt="metal_for_factories_to_place.png"></p>
<p>I only allow factories to be placed on tiles that would be adjacent to ice OR ore. I allow factories to be placed adjacent to ore but not ice to help the model learn to mine ore and build robots.</p>
<p>I split direction and resources between the action subtypes, resulting in the following action space per position:</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1298%2F6d62f2cd4d73d74f74d63e35014268ff%2FScreenshot%202023-12-06%20at%2015.24.01.png?generation=1701905061027060&alt=media" alt="action_space.png"></p>
<p>I heavily used invalid action masking to both eliminate no-op actions (e.g. actions on non-own unit or factory positions, moves or transfers off map or onto opponent factory, or invalid actions because insufficient power or resources) and ill-advised actions:</p>
<ul>
<li>Don’t water lichen if it would result in water being less than the number of game steps remaining.</li>
<li>Don’t transfer resources off factory tiles.<ul>
<li>Exception: Allow transferring power to a unit from a factory tile if the destination unit has been digging.</li></ul></li>
<li>Cannot pickup resources other than power<ul>
<li>Exception: Light robots can pickup water if the factory has sufficient water.</li></ul></li>
<li>Only allow digging on resources, opponent lichen, and rubble that is adjacent to a factory’s lichen grow area (prevents digging on distant rubble).</li>
<li>Only allow moving in a rectangle containing all resources, diggable areas (see above), own units, and opponent lichen.</li>
<li>Only lights can self-destruct and only if they are on opponent lichen that isn’t eliminable by a single dig action.</li>
</ul>
<p>The action handling logic will also cancel conflicting actions (instead of attempting to resolve them):</p>
<ul>
<li>Cancel moves if they are to a stationary own unit, unit to be spawned, or into the destination of another moving own unit. This is done iteratively until no more collisions occur.</li>
<li>Cancel transfers if they aren’t going to a valid target (no unit or factory or unit or factory is at capacity)</li>
<li>Cancel pickups if multiple units are picking up from the same factory and they’d cause the factory to go below 150 water or 0 power.</li>
</ul>
<h2>Neural Architecture</h2>
<p>I started with a similar neural architecture to <a href="https://www.kaggle.com/competitions/lux-ai-season-2/discussion/406702" target="_blank">FLG’s DoubleCone</a>, but added an additional 4x-downsampling layer within the original 4x-downsampling layer to get the receptive field to 64x64:</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1298%2Fd9adf36a478568489a4415f6ddc20e94%2FScreenshot%202023-12-06%20at%2015.24.38.png?generation=1701905097172444&alt=media" alt="squnet.png"></p>
<p>The policy output consists of 24 logits for unit actions, 4 logits for factory actions, and 1 logit for factory placement. Each unit’s action type and subactions are assumed independent and identically distributed, as are the factory actions. The factory placement logit undergoes a softmax transformation across all valid factory spawn positions (all factory spawn positions are masked out if it’s not the agent’s turn to place factories).</p>
<h2>PPO Training</h2>
<p>Similar to <a href="https://www.kaggle.com/competitions/lux-ai-season-2/discussion/406702" target="_blank">FLG’s Lux AI Season 2 Approach</a> and <a href="https://github.com/sgoodfriend/rl-algo-impls/blob/07083d6e5170ae9d2a16668e2aeadf04225f637c/rl_algo_impls/microrts/technical-description.md" target="_blank">my 2023 microRTS competition solution</a>, I progressively trained the model on larger maps, starting with 16x16, then 32x32, and finally 64x64. The best performing agent had the following training runs:</p>
<table>
<thead>
<tr>
<th>Name</th>
<th>Map Size</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="https://wandb.ai/sgoodfriend/rl-algo-impls-lux-nips1/runs/jk8u688d" target="_blank">ppo-LuxAI_S2-v0-j1024env16-80m-lr30-opp-resources-S1-2023-11-16T23:18:33.978764</a></td>
<td>16x16</td>
</tr>
<tr>
<td><a href="https://wandb.ai/sgoodfriend/rl-algo-impls-lux-nips1/runs/ewbq4e71" target="_blank">ppo-LuxAI_S2-v0-j1024env32-80m-lr20-2building-S1-2023-11-18T09:16:46.921499</a></td>
<td>32x32</td>
</tr>
<tr>
<td><a href="https://wandb.ai/sgoodfriend/rl-algo-impls-lux-nips1/runs/idaxlrl0" target="_blank">ppo-LuxAI_S2-v0-j512env64-80m-lr5-ft32-2building-S1-2023-11-19T09:30:01.096368</a></td>
<td>64x64</td>
</tr>
</tbody>
</table>
<p>Each larger map training run was initialized with the weights from the best performing checkpoint of the previous map size. The 16x16 map training run’s weights were initialized randomly.</p>
<p>I used my <a href="https://github.com/sgoodfriend/rl-algo-impls/blob/07083d6e5170ae9d2a16668e2aeadf04225f637c/rl_algo_impls/ppo/ppo.py" target="_blank">own implementation of PPO</a> (inspired by <a href="https://github.com/vwxyzjn/ppo-implementation-details/blob/fbef824effc284137943ff9c058125435ec68cd3/ppo_multidiscrete_mask.py" target="_blank">Costa Huang's implementation</a>) with the following hyperparameters:</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1298%2F5e27c6ca82f5622963a15a45abd5f9d8%2FScreenshot%202023-12-06%20at%2015.25.15.png?generation=1701905136626107&alt=media" alt="ppo_hyperparams.png"></p>
<p>Each training run was for 80 million steps with the following schedule for learning rate and entropy coefficient (cosine interpolation during transition phases):</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1298%2F473071dbcba3ef72fc8882ad6f554b0d%2FScreenshot%202023-12-06%20at%2015.25.45.png?generation=1701905167868722&alt=media" alt="training_schedule.png"></p>
<p>Training was done on Lambda Cloud GPU instances each with 1 Nvidia A10. I also used Nvidia A100 instances for the larger maps (not these specific training runs) where I could double the mini-batch size. I used PyTorch’s autocast to bfloat16 to reduce memory usage and gradient accumulation to take optimizer steps on the full batch.</p>
<p>While training was scheduled to run 80 million steps, I would stop training early if it looked like progress was stuck. This let me schedule different training runs with limited resources.</p>
<h3>Reward structure</h3>
<p>RL solutions from the prior Lux Season 2 competition had to start training with shaped rewards. Similar to <a href="https://www.kaggle.com/competitions/lux-ai-season-2/discussion/406791" target="_blank">my prior solution</a>, I used generation and resource statistics to generate the reward. However, instead of determining the scaling factors myself, I scaled each statistic by dividing each statistic by its exponential moving standard deviation (window size 5 million steps). The environment would return all of these scaled statistics and a WinLoss reward (+1 win, -1 loss, 0 otherwise), and the rollout computes an advantage for each statistic. The PPO implementation has element-wise scaling factors for each advantage and reward for computing policy and value losses:</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1298%2F3c651a4b1df678206a17ab30c990e397%2FScreenshot%202023-12-06%20at%2015.26.15.png?generation=1701905196003519&alt=media" alt="reward.png"></p>
<p>The advantage of the above was that I could keep the same model and simply change the weights in the value and reward coefficients to adjust the strategy. For example, the training runs for 32x32 and 64x64 maps rewarded building robots more by increasing the reward weights for ore, metal, and robot generation.</p>
<h2>Training Results</h2>
<h3>Reaches End of Game</h3>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1298%2F77e3e145ef3c9ba11df7c25b67abdb6a%2Freach_game_end.png?generation=1701825369443112&alt=media" alt="reach_game_end.png"></p>
<p>The chart above shows the rate of games that reach the step limit. The 16x16 agent (light green) averages about 600 steps/game by the end of training. Even though I require maps to have at least 2 ice and ore each, later agents I’ve trained rarely reach over 900 steps/game, implying the small map with competitive resources is a difficult environment to reliably reach the step limit. The 32x32 (magenta) and 64x64 agents (blue) get to the step limit regularly.</p>
<h3>Metal Generation</h3>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1298%2Fb02290583ed05522c03042211847f189%2Fmetal_generation.png?generation=1701825389976619&alt=media" alt="metal_generation.png"></p>
<p>The chart above shows average metal generation per game. The dashed lines represents evaluations that on average beat the prior 4 best evaluation checkpoints (cumulative win-rate of at least 57% in 128 games [64 games for 64x64]). Notice that the last dashed line for 64x64 is before 20 million steps. 32x32 does continue to make models that beat prior checkpoints (dashed line continues to 60 million steps), but metal generation falls below 100 (the cost of a heavy robot). All of this implies training stopped being useful before the end.</p>
<h3>KL Divergence and Loss</h3>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1298%2Fc64ab76fd68a7a92d2cc3ab7345c0237%2Flosses.png?generation=1701825409120403&alt=media" alt="losses.png"></p>
<p>The charts above shows the KL divergence and training loss. 3 things jump out at me:</p>
<ol>
<li>KL divergence for 32x32 is too high (over 0.02), especially after 30 million steps. This is around when metal generation drops below 100.</li>
<li>Losses are periodically spiky for 64x64 (and to a lesser extent 32x32). This is likely caused by training games ending at the same time every 1000 steps.</li>
<li>The variability of KL divergence means a constant learning rate is not ideal. Training reaches milestones that changes game dynamics. For example, the 16x16 spike at 25 million steps coincides with games beginning to reach the step limit a sizable portion of the time. A constant learning rate means a training agent can easily be training too slowly or too quickly in the same training run depending on how much game dynamics are changing.</li>
</ol>
<h2>Next steps</h2>
<p>I spent a lot of time creating a GridNet observation space from Jux using Jax. I believe there are a few things I could do to improve the model:</p>
<ol>
<li>Fix the periodic spikes in losses by doing a rolling reset of environments at the beginning of training.</li>
<li>Track L2 gradient norm to gauge training stability. Loss, value loss, policy loss, KL divergence, and entropy loss are all important, but I noticed that I could end up in situations where everything would be stable until a sudden spike. Rising gradient norm is one possible indicator that training is becoming unstable even if other metrics show little change.</li>
<li>Use a learning rate schedule that takes into account the changing game dynamics. I’m currently working on raising and lowering learning rate depending on the KL divergence. This is tricky because KL divergence isn’t the only indicator of instability. Currently, if the L2 gradient norm is above a cutoff, learning rate isn’t increased. This has been very finicky so this will either be supplemented with or abandoned for the next item.</li>
<li>Normalization layers. <a href="https://www.kaggle.com/competitions/lux-ai-season-2/discussion/406702" target="_blank">FLG’s solution</a> called out that normalization layers didn’t appear necessary given the use of Squeeze-and-Excitation layers, but did mention LayerNorm could be useful if there wasn’t Squeeze-and-Excitation layers. Given my convergence issues, I’m trying out adding LayerNorm after fully connected layers and a spatial dimension-independent ChannelLayerNorm2d after convolutional layers. So far this has <a href="https://wandb.ai/sgoodfriend/rl-algo-impls-lux-nips1/runs/2t5tcjes" target="_blank">helped with stability at the cost of training memory and performance</a>.</li>
</ol>
<h2>Appendix</h2>
<p>Environment hyperparameters:</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1298%2F227bc5e2f75df25b8cb4ca3de6bc66f4%2FScreenshot%202023-12-06%20at%2015.26.55.png?generation=1701905235576550&alt=media" alt="env_hyperparams.png"></p>
|
Lyft 3D Object Detection for Autonomous Vehicles
|
19th place solution with code
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lyft 3D Object Detection for Autonomous Vehicles
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks <a href="/auxlchen">@auxlchen</a> </p>
<p>Hey guys,</p>
<p>First of all, I'd like to thank the organizers for this awesome challenge. This was not a typical computer vision competition that's for sure and I spent a good amount of time just to understand the problem and the data. I went through multiple papers related to 3d object detection. I chose to go with <a href="https://github.com/traveller59/second.pytorch">SECOND</a>:</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F761152%2Fadcfa4df972dfe71bde7404745460bb1%2Fpic-selected-191130-2044-46.png?generation=1575126996055584&alt=media" alt=""></p>
<p>I tweaked the SECOND's original source code to get it working for lyft dataset. Added the evaluation metric of the competition for val set evaluation. Modified the default config files according to lyft object dimensions (<code>anchor_ranges</code>, <code>sizes</code> etc). Splitted train/val based on scenes (80:20), <a href="https://github.com/pyaf/second.pytorch/blob/master/second/configs/nuscenes/all.pp.lowa.config">configs/nuscenes/all.pp.lowa.config</a> with VoxelNet and PillarFeatureNet worked best for me. </p>
<p>check out my source code: <a href="https://github.com/pyaf/second.pytorch">https://github.com/pyaf/second.pytorch</a> </p>
<p>Checkout prepare.ipynb in the notebooks folder</p>
|
Lyft 3D Object Detection for Autonomous Vehicles
|
1st place solution (0.220 public LB)
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lyft 3D Object Detection for Autonomous Vehicles
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Hi, the post may be a little late. Thanks to organizers and congratulations to all!</p>
<h1>Background</h1>
<p>For the record, I want to state that I am really new to Kaggle and actually really new to machine learning. I only started to work on machine learning 9 month ago. My background is in 3D Computer Graphics so I looked into the problems more in the view of 3D than in machine learning. Pardon me if I made any silly mistake with regard to machine learning.</p>
<p>Before this competition, I won 2nd place in CVPR 2019 competition WAD-Beyond Single-Frame Perception hosted by Baidu on a similar topic: 3D detection with Lidar points (<a href="http://wad.ai/2019/challenge.html">http://wad.ai/2019/challenge.html</a>). The tricks we used is actually based on that competition. So we just adopt and modified the tricks and have no idea about the performance without the tricks. </p>
<h1>Models</h1>
<p>Our method is based on Voxelnet (<a href="https://github.com/traveller59/second.pytorch">traveller59</a>) But our tricks can be applied to any other network. I gave a try with PointRCNN but got no luck. </p>
<p>Basic Setting:
- No external data
- Data Augmentation: flip x and y, random rotation, random scaling and random translation
- No Ground Truth Augmentation
- Detection Range [-100,-100,-5,100,100,3]
- No direction classifier
- No specific post processing but score thresholding (0.1) and NMS</p>
<p>Two types of voxelnet are implemented in second: FHD and PointPillars. We use both. Based on the idea that ensembling models with more difference results in better results, we use different settings to train a set of models. E.g. we use voxel size 0.1, 0.125, 0.2, 0.25 for PointPillar, 0.1 and 0.125 for FHD. Different Voxel Feature Extractors are also used for different models(e.g. PillarFeatureNet, PillarFeatureNetRadius,PillarFeatureNetRadiusHeight). RPN is modified so that the final resolution is 200 X 200 or 250 X 250. </p>
<h1>Key Tricks</h1>
<p>The key to our method is Test time augmentation (TTA) and model ensemble with a specific 3D box fusion method.</p>
<h2><strong>Test Time Augmentation</strong></h2>
<p>We transform the point cloud into several copies. Each copy is then feed into the network and get the predicted boxes. Then the predicted boxes are transformed back. For example, we can rotate the point cloud 20 degrees. After we got the predicted boxes (after NMS), we rotate the predicted boxes -20 degrees (both the center position and yaw angle are changed). We do this for many copies and fuse the results. During the competition, we only use 4 copies: original, flip x, flip y, flip x and y. We tried more copies with rotation, scaling and translation. It gives slightly better results but needs more inference time.</p>
<h2><strong>Model ensemble</strong></h2>
<p>We use TTA to get the predicted boxes for each model and fuse the results.</p>
<p>Best Single Model (No TTA): >0.175 (I only got the score for a model with TTA score 0.193. But I got a better model with TTA score 0.197)
Best Single Model (TTA): 0.197</p>
<p>Ensembling 7 best models: 0.220</p>
<h2><strong>3D box fusion</strong></h2>
<p>After we got several copies of predicted boxes (from TTA or model ensemble), we need to fuse them. We choose boxes with same label and IOU > 0.6 to fuse into one. After the competition,we tried Weighted Boxes Fusion: ensembling boxes for object detection models. It actually gives better results (0.222 Public LB) but is slower. To fuse boxes, the center and size are directly weighted averaged. The key is the yaw angle. If you predict the direction and can trust it. You may use sin and cos interpolation.</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F3701925%2F7c611366e6f5e39e70bbbe3d0b46d12e%2Fyaw.png?generation=1577071532448853&alt=media" alt=""></p>
<p>However, in our implementation, we did not use direction classifier (it won’t affect the score and it can not be 100% accurate). We need to deal with one ambiguity: yaw angle is the same to yaw angle + 180 degrees. Say for one box, one prediction might give yaw angle 175 degrees or -5 degrees. <br>
It does not matter since it is of the same IOU to ground truth. However, when we do box fusion, it matters. Say for the same box, another prediction gives yaw angle 5 degrees. If the first prediction is -5 degree. The average is 0 degree. It is okay. However, if the first prediction is 175 degree, the averaged boxes will be with yaw angle 90 degrees.</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F3701925%2F1b3f051743db56d52c52e61e943091c8%2Fyaw2.png?generation=1577071794662291&alt=media" alt=""></p>
<p>To deal with this problem, we use an intuitive method: average 2 * yaw instead of yaw.
The idea is that sin and cos interpolation of yaw angle can remove 360 degrees ambiguity. So sin and cos interpolation of 2 * yaw angle can remove 180 degrees ambiguity. I have no theoretical proof yet but intuitively feel it is correct. Actually the idea came into my head when I was telling bedtime story to my daughter. She asked me to tell the story over and over again so I just repeated it😂 !</p>
<p>I uploaded our code and pretrained models. You may give a try. Have fun!</p>
<p>p.s.
For sparse convolution, since spconv used in second might be patented, we replace it with <a href="https://github.com/facebookresearch/SparseConvNet">this one</a>. It is much slower. </p>
|
Lyft 3D Object Detection for Autonomous Vehicles
|
22th place solution
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lyft 3D Object Detection for Autonomous Vehicles
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Hi Everyone,</p>
<p>Ending final validation, I share my solution.
I converted points clouds into RGB images and applied simple SSD (Single Shot Multibox Detector).
The Brightness corresponds to the density of clouds, and the Hue corresponds to the weighted center of z-position.</p>
<p>Code: <a href="https://github.com/toshi-k/kaggle-3d-object-detection-for-autonomous-vehicles">https://github.com/toshi-k/kaggle-3d-object-detection-for-autonomous-vehicles</a></p>
<p><img src="https://raw.githubusercontent.com/toshi-k/kaggle-3d-object-detection-for-autonomous-vehicles/master/img/concept.png" alt="conceptual diagram"></p>
<p>Thank you for your comment ! I just counted number of points in each grid for quantization. Althongh It might not be efficient, it is easy to tune hyperparameters because of its simplicity. I had simmilar ideas and tried PointPillars. However I could not tune it enough. I gave up to use it finally.</p>
|
Lyft 3D Object Detection for Autonomous Vehicles
|
26th Place Solution Summary [0.078 Private LB]
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lyft 3D Object Detection for Autonomous Vehicles
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h2>Congrats + Thanks</h2>
<p>Congrats to all the winners!
Thanks to the competition hosts for a very interesting and challenging competition.
Big thanks to <a href="/rishabhiitbhu">@rishabhiitbhu</a> for all his sharing in the forums and kernels throughout the competition and everyone else who contributed their insights. </p>
<h2>Model</h2>
<p>The model was based on the PointPillars [1] implementation from second.pytorch [2]. This repo contains SECOND [3], VoxelNet [4], and PointPillars implementations and supports Kitti [5] and NuScenes [6] data formats. Most of my time was spent updating the code to work with the Lyft dataset and removing the Spconv [7] dependency used by SECOND architecture which kept causing errors while trying to compile it. Many of the changes to remove the Spconv dependency were taken from Nutomoy’s fork [8] of second.pytorch but this fork does not support the NuScenes format. </p>
<h2>Configuration</h2>
<p>| Point Cloud Range | Voxel Size | Max Num Points Per Voxel |
|--|--|--|
| [-100, -100, -10, 100, 100, 10] | [0.25, 0.25, 20] | 60</p>
<h2>Validation</h2>
<p>First 80% of data was used for training, last 20% was used for validation. Data was split by scene. </p>
<h2>Training, Evaluation & Test Set Predictions</h2>
<p>On Saturday 9th before the competition end I was able to make my first submission using Point Pillars model. This first attempt got the following results:</p>
<p>| GPU | Epochs | Train Time | Val mAP | Public LB mAP | Private LB mAP |
|--|--|--|--|--|--|
| GTX1080 | 20 | ~18 | 0.049 | 0.066 | 0.065 |</p>
<p>On analyzing predictions from both eval set and test set I noticed there were no predictions outside of +-50 meters along X and Y. The reason for this was the point cloud range was set to [-50, -50, -10, 50, 50, 10], many of the object anchor ranges were set to the same range or less, there was also some post processing that filter out any detections outside of 50 meters from the center of the point cloud. These were defaults used for working with NuScenes and not well suited for the Lyft dataset. </p>
<p>After extending the point cloud range to [-100, -100, -10, 100, 100, 10] , extending the object anchor ranges, increasing the post processing detection filtering radius to 100 meters, and retraining I got the following results:</p>
<p>| GPU | Epochs | Train Time | Val mAP | Public LB mAP | Private LB mAP |
|--|--|--|--|--|--|
| GTX1080 | 19 | ~36 | 0.072 | 0.079 | 0.078 |</p>
<h2>References</h2>
<ol>
<li>PointPillars: Fast Encoders for Object Detection from Point Clouds <a href="https://arxiv.org/pdf/1812.05784.pdf">[paper]</a></li>
<li>second.pytorch <a href="https://github.com/traveller59/second.pytorch">[code]</a></li>
<li>SECOND: Sparsely Embedded Convolutional Detection <a href="https://pdfs.semanticscholar.org/5125/a16039cabc6320c908a4764f32596e018ad3.pdf">[paper]</a></li>
<li>VoxelNet: End-to-End Learning for Point Cloud Based 3D Object Detection <a href="https://arxiv.org/pdf/1711.06396.pdf">[paper]</a></li>
<li>Kitti dataset <a href="http://www.cvlibs.net/datasets/kitti/">[data]</a></li>
<li>NuScenes dataset <a href="https://www.nuscenes.org/">[data]</a></li>
<li>Spconv <a href="https://github.com/traveller59/spconv">[code]</a></li>
<li>Nutonomy’s fork of second.pytorch <a href="https://github.com/nutonomy/second.pytorch">[code]</a></li>
</ol>
<p>Welcome and thank you. Batch size of 1 on a 1080 not 1080ti.</p>
<p>Thanks! Still you finished with a silver medal, well done! </p>
<p>Thanks <a href="/veeralakrishna">@veeralakrishna</a>!</p>
|
Lyft 3D Object Detection for Autonomous Vehicles
|
2nd Place Solution Summary (Private: 0.202 / Public: 0.205)
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lyft 3D Object Detection for Autonomous Vehicles
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Before I describe my solution (which I will only summarize verbally), I'd like to thank the organizers and hosts for this interesting, well-organized competition which came with a rich, multi-data dataset that provided multiple solution avenues. And of course, I'd also like to thank the competitors for contributing to this competition and congratulations to all the winners and medal holders too.</p>
<p>Also, apologies for not having written this sooner since I got caught up with multiple commitments after the competition - but better late than never. Particularly, my solution takes a slightly different approach wherein I actually did end up using 2D images effectively (compared to the other approaches which use only LIDAR), so it may be of interest. </p>
<h1>Methods</h1>
<p>These are my primary methods:</p>
<p><strong>Method 1.</strong> As with most of high scoring solutions which have been shared one method I used is based on Voxelnet with PointPillars (<a href="https://github.com/traveller59/second.pytorch">https://github.com/traveller59/second.pytorch</a>). I started with this since it seemed to have the most fastest path to getting a first cut solution - NuScenes format, multi-class, similar classes, etc.. In particular I re-used the multi-head version of the config (all.mhead.pp.config), and simply remapped existing NuScenes classes to Lyft classes (with the exception of some new classes which I just did a closest match, e.g. other_vehicle to trailer). Here I found that the following parameters made the most difference</p>
<ul>
<li><code>point_cloud_range</code> - [-100, -100, -5, 100, 100, 3]</li>
<li><code>voxel_size</code> - in the final implementation I used an ensemble of models ranging from 0.1x0.1 to 0.25x0.25, with the best performing single model at 0.2x0.2. </li>
<li><code>feature_map</code> - this has to be changed to match <code>voxel_size</code> above</li>
<li><code>max_number_of_voxels</code> - I found that this was best set to as large as possible, e.g. > 200k (depending on the amount of GPU memory available).</li>
</ul>
<p>Other than flip augmentations I did not find any additional advantage in additional augmentations, nor did I spend any time varying architecture parameters. I left the single model NMS parameters at the default and did not tune the thresholds, even though the downstream ensemble used rotated soft-NMS.</p>
<p>In terms of external data, I did start my first model by training on the NuScenes dataset from scratch, which helped to (1) validate that the repository results were acceptable on NuScenes scoring (on average yes, but per class scores varied somewhat from what was reported) (2) accelerate subsequent training cycles as a pretrained model for Lyft dataset. Post-competition analysis showed that using the NuScenes dataset as an initial pretrained model might not have been necessary, but it was still helpful for me to validate the integrity of the repository.</p>
<p>My best model had a private/public of 0.170/0.173 using a voxel size of 0.2x0.2. Including test time augmentation for this model. With test time augmentation (described below) this contributed to a private/public of 0.185/0.188. </p>
<p>For the final ensemble I used a combination of 8 models of varying voxel sizes (and a few of them either used full data rather than train/val and one of them at some additional augs e.g. scaling). This LIDAR only ensemble gave a private/public of 0.188/0.191, which is not that much better from the best model TTA.</p>
<p><strong>Method 2.</strong> Additionally, I used a 2D->3D approach that leveraged Frustum ConvNet (<a href="https://github.com/zhixinwang/frustum-convnet">https://github.com/zhixinwang/frustum-convnet</a>) by using 2D boxes/proposals from conventional object detectors. Since this repository worked on KITTI format, this required a few corrections on the KITTI converter:</p>
<ol>
<li>The rotation had to be pi instead of pi/2 (this was corrected by the Kaggle community)</li>
<li>Ego pose differences between LIDAR and cameras had to be taken into account (see PR: <a href="https://github.com/lyft/nuscenes-devkit/pull/75">https://github.com/lyft/nuscenes-devkit/pull/75</a>)</li>
</ol>
<p>For the object detectors I used Detectron 2 and Tensorflow Object Detection API and trained the labels after converting from KITTI to COCO format. Pretrained models used from these object detectors include Faster-RCNN with X101-FPN for Detectron 2 and Faster-RCNN with Inception ResNet V2 (Atrous) for TF object detection API. </p>
<p>I also wrote a de-converter from KITTI back to the Lyft submission format, and ignore overlapping boxes across camera views since they would be rectified by the ensemble process (which is rotated soft-NMS) described later.</p>
<p>For the Frustum-ConvNet training process, I maintained 3 classes as per the original repository (instead of expanding this to all classes in a single training cycle, to minimize risk of modifications). I then mapped bicycle and motorcycle classes to 'Cyclist', pedestrian and animal classes to 'Pedestrian', and all other vehicle classes to 'Car', but modified their average sizes whenever the class was used. This required training each class mostly independently.</p>
<p>Surprisingly, this approach by itself gave around private/public of 0.169/0.171 (ensemble of the 2 models from the frameworks x 2 checkpoints), which was pretty respectable - more importantly, combining this with approach (using SECOND) gave a final private/public of 0.202/0.205, which was would not have been achievable just using LIDAR alone since my LIDAR ensemble had already saturated. </p>
<p>Further investigation showed that the best model for Frustum-ConvNet when compared to the SECOND approach has an improvement on pedestrian and bicycle classes, as shown below. Additionally, my guess is that this approach was able to detect some missed false negatives from the LIDAR approach for most of the classes which even though the overall score was lower.</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F495818%2F6bb7a3583aee98d1efe199da3c8fb2e6%2F3d_vs_2d.png?generation=1577161276113708&alt=media" alt=""></p>
<h1>Ensembles</h1>
<ol>
<li><p>I used test time augmentation for the SECOND/LIDAR approach, which effectively is just orig, x flip, y flip, and x-y flip - preprocessing the point cloud by these flips, and then postprocessing the detected object boxes by the inverse. I did not apply TTA for the Frustum-ConvNet approach.</p></li>
<li><p>I employed the same rotated soft-NMS for all ensembles, which include combining TTA predictions + merging all LIDAR models and all Frustum-ConvNet models. In other words this acted as somewhat of a "late fusion" approach to both 3D and 2D->3D (via Frustum-ConvNet) models. A little bit of validation checking showed that using Gaussian function at a sigma of 0.85 gave the best validation score, so I stuck to this throughout the competition. I did not have success with 3D (i.e. including height intersection) but only IOU considering the rotated bounding boxes of the objects (it scored worse), and only considered soft-NMS within the same class.</p></li>
</ol>
<h1>What Didn't Work</h1>
<p>I would be very interested if anyone enabled the following to work properly. It is also food for thought:</p>
<ol>
<li><p>Using high resolution maps to improve LIDAR/SECOND training - I had the idea of augmenting the point clouds with non road vs road points, but wasn't confident of this approach. I also tried weighing predicted objects directly using the map information to down-weigh non-road objects for certain classes, but I only got extremely marginal improvement.</p></li>
<li><p>Using samples which were adjacent in time - I tried weighing predictions across pre and post adjacent frame samples for both non-road and road objects, and boost the predictions of objects which were seen across multiple adjacent frames. This did not help. Perhaps a tracking approach would have improved scores here.</p></li>
<li><p>Animals - the 2D (Frustum-ConvNet) approach actually detected some animals (dogs) correctly, but the IOU evaluation was too sensitive for this to work well, so my score was 0 for both local and LB.</p></li>
<li><p>PointRCNN - a last minute attempt to use this did not work well and I only got about slightly better than half the score for the car class (if I remember ~0.15 instead of 0.3+ for cars).</p></li>
</ol>
|
Lyft 3D Object Detection for Autonomous Vehicles
|
3rd place solution [0.182 Private LB]
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lyft 3D Object Detection for Autonomous Vehicles
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks to organizers and Kaggle for this competition!</p>
<p>Congratulations to all winners!</p>
<p>Here is my solution:</p>
<h3>Dataset & Pre-processing</h3>
<ul>
<li>No external data and only point-cloud of this competition</li>
<li>Animals and emergency vehicle classes were not used.</li>
<li>The objects which have less than 5 points were ignored.</li>
<li>The detection area was 100m x 75m for vehicle's classes (car, other_vehicle, truck and bus) and 100m x 50 for small object's classes (pedestrian, bicycle and motorcycle).</li>
<li>Dataset was splitted bt StratifiedKFold using the number of objects for each class in a scenes.</li>
</ul>
<h3>Model</h3>
<p>My network was the combination of VoxelNet [1] and PointPillars [2], and the implementation was based on <a href="https://github.com/traveller59/second.pytorch">traveller59's second.pytorch</a>. The network utilized only FC and Conv2d, no Sparse Convolution or Deformable Convolution.</p>
<p>Base model's pipeline:</p>
<ol>
<li>Point-cloud was splitted into voxels [0.25m x 0.25m x 0.75m]</li>
<li>The same network of PointPillars' Pillar Feature Net was applied to each voxel and output channel size = 16 worked best for me.</li>
<li>Voxel-representation features (C x D x H x W) were reshaped into pseudo-image features (C * D x H x W).</li>
<li>Almost the same network of RPN in VoxelNet was used for vehicle's classes and this was based on <a href="https://github.com/traveller59/second.pytorch/blob/master/second/configs/nuscenes/all.pp.mhead.config">this configuration file</a>. The first DeConv2d was replaced to Conv2d and other parameters were adjusted. <br>
For other small object's classes, three Conv2d were applied to the cropped feature map from the reshaped feature map. The cropped featuere map corresponding to the detection area.</li>
<li>The prediction outputs were localization, classification and direction.</li>
</ol>
<p>Optional models:</p>
<ol>
<li>Pre-activation ResNet was used in RPN and this idea was from [3]</li>
<li>RPN for small object's classes was changed. Conv2d x 1 (1st output) and Conv2d x 3 (2nd output) were applied to the cropped feature map then these outputs were concatenated. This was based on the original RPN in VoxelNet.</li>
</ol>
<h3>Post-processing</h3>
<ul>
<li>NMS was used to suppress the overlaps for each model.</li>
<li>Three models were ensembled using Soft NMS. </li>
<li>No score threshold.</li>
</ul>
<h3>Data Augmentation</h3>
<ul>
<li>global translation (x, y, z)</li>
<li>global scaling</li>
<li>rotation around z-axis</li>
<li>mixup-augmentation <br>
Ground-truths were cropped and pasted to other samples (More explanation is in [4]). This augmentation raised the scores a lot for all classes. </li>
</ul>
<h3>No Improvement for me</h3>
<ul>
<li>I extended Weighted-boxes-fusion (<a href="https://www.kaggle.com/c/google-ai-open-images-object-detection-track/discussion/64633#latest-590283">ZFTurbo's solution on the Open Image competition last year</a> [5]) to apply 3D Bonding Boxes to ensemble different models, but the score was lower than Soft NMS. It was better than NMS.</li>
<li>I tried to use a semantic map image (original, filtered) to filter the predictions, but both positive and false predictions were dropped.</li>
<li>Point-cloud-coloring using raw images or feature maps extracted from 2D detection model did not work as additional feature for Point-cloud in my architectures.</li>
</ul>
<h3>Reference</h3>
<ol>
<li><p>VoxelNet: End-to-End Learning for Point Cloud Based 3D Object Detection [<a href="https://arxiv.org/abs/1711.06396">arvix</a>]</p></li>
<li><p>PointPillars: Fast Encoders for Object Detection from Point Clouds [<a href="https://arxiv.org/abs/1812.05784">arvix</a>]</p></li>
<li><p>End-to-End Multi-View Fusion for 3D Object Detection in LiDAR Point Clouds [<a href="https://arxiv.org/abs/1910.06528">arvix</a>]</p></li>
<li><p>Fast Point R-CNN [<a href="https://arxiv.org/abs/1908.02990">arvix</a>]</p></li>
<li><p>Weighted Boxes Fusion: ensembling boxes for object detection models [<a href="https://arxiv.org/abs/1910.13302">arxiv</a>] [<a href="https://github.com/ZFTurbo/Weighted-Boxes-Fusion">github</a>]</p></li>
</ol>
<p>For 3 ~ 4 days with single GTX 1080Ti with batch_size = 2 or 3</p>
<p>Thanks!</p>
<p>point_cloud_range = [-100, -75, -2, 100, 75, 5.5] and I used <code>flat_vehicle_coordinates=True</code> option in <code>get_sample_data</code>.</p>
<p>Thanks!</p>
<p>Thanks!</p>
<p>In the evaluation page, </p>
<p>> In nearly all cases confidence will have no impact on scoring. </p>
<p>"In nearly all cases" is very ambiguous and misleading. It doesn't say that the metric ignores the confidence values. At least, average precision has some impact on the evaluation metric.</p>
<p>If this competition uses <a href="https://github.com/lyft/nuscenes-devkit/blob/master/lyft_dataset_sdk/eval/detection/mAP_evaluation.py">the same metric implementation on official devkit</a>, the metric changes.
In my case, <code>0.837</code> drops to <code>0.783</code> by changing confidence from <code>c</code> to <code>1 - c</code></p>
|
Lyft 3D Object Detection for Autonomous Vehicles
|
Three Rank Jump 41->38 in two days on private set
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lyft 3D Object Detection for Autonomous Vehicles
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>That's sad. Being in top 5 was a great achievement for them.</p>
<p>How did this happen? Kaggle removed multiple accounts?</p>
<p>This time Det3d was removed</p>
|
Lyft Motion Prediction for Autonomous Vehicles
|
10th place solution (vectornet)
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lyft Motion Prediction for Autonomous Vehicles
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>not use any image at all</p>
<p>Thanks to Kaggle and Lyft for hosting the competition.<br>
<strong>Rule-base</strong> is only my team name, but not a solution.😀</p>
<p>In this competition, I tested two papers from waymo & google research:<br>
vector net: <a href="https://arxiv.org/abs/2005.04259" target="_blank">https://arxiv.org/abs/2005.04259</a> (final solution)<br>
tnt: <a href="https://arxiv.org/abs/2008.08294" target="_blank">https://arxiv.org/abs/2008.08294</a> (hard to train, = =!)</p>
<p>vector net:<br>
batch=1024, 1 * 1080 GPU + 8 core CPU, trained for 2 days<br>
<=800 vectors</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F5513638%2Fdc1279adf7cddb1b4ad05a32e108d175%2F149.png?generation=1606437813920943&alt=media" alt=""></p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F5513638%2Fcb42ce425d35ec735107a2f2178e0985%2F12.png?generation=1606437866782123&alt=media" alt=""></p>
<p>tnt:<br>
batch=128, 1 * 1080 GPU + 8 core CPU, trained for 0.5 day<br>
<=800 vectors</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F5513638%2Fde8650eb8c219883afa0c64f65c51911%2Ftnt1.png?generation=1606438391638966&alt=media" alt=""></p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F5513638%2F97dd2340242bbc2ff9a1a8492b882d2e%2Ftnt2.png?generation=1606438403511527&alt=media" alt=""></p>
<p>it's my vis tool based on the matplotlib</p>
<p>I'm not sure. I met gradient exploding problem & gradient vanishing problem at the same time.<br>
some layers' gradient explodes easily but others' vanish 😂</p>
<p>about 3min per 1000 batch, batch_size = 1024</p>
|
Lyft Motion Prediction for Autonomous Vehicles
|
14th place solution. Custom Mask and LSTM encoder/decoder
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lyft Motion Prediction for Autonomous Vehicles
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Great thanks to Lyft and kaggle team for hosting this competition. Congrats to all the winners. And a special thanks to all my teammates for teaming up!! The time I spent discussing together was very insightful and most enjoyable.</p>
<h1>Create Mask</h1>
<p>Our solution’s point is that we made the custom mask.<br>
Agent data one frame away from the same scene is very similar. So, in order to learn efficiently, we created a custom mask so that the data is loaded every N frames. For example, by sampling data every 5 frames, the training data is reduced by a factor of 5, allowing for faster learning.<br>
To make it more efficient, we balanced the data according to the target distance. About 65% of the data had a target distance of less than 6 meters, and they were easy tasks. So in order to efficiently train the difficult data, we downsampled the data below 6 m. This halved the data. In the end, the number of data was roughly 80,000 iterations x 64 batch size.</p>
<h1>Model architecture</h1>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1057275%2F98319e9931caf1a99cbfdfdbf0c78237%2Ffinal_model.jpg?generation=1606994527055759&alt=media" alt=""></p>
<p>In addition to CNN, we used LSTM encoder and LSTM decoder.</p>
<ul>
<li>Image size: 300x300</li>
<li>Optimizer: Adam</li>
<li>Scheduler: Onecyclelr</li>
<li>Num history: 10</li>
<li>Target: positions + cosine/sine of yaw</li>
</ul>
<p>First, we trained the model with the target distance balanced mask. Additional learning with the non-balanced mask. We used log10-scaled loss when additional training, because train/validate loss goes up and down with a large margin repeatedly. For two days of model training by using this method, we got a public score under 13, and a private score about 12.</p>
<h1>Didn’t work</h1>
<p>history_positions more than 10 (Public score around 15, slow convergence)<br>
metalabeling<br>
Seq2seq like LSTM decoder</p>
<hr>
<h1>Discussion</h1>
<h2>Stacking</h2>
<p>As discussed in <a href="https://www.kaggle.com/c/lyft-motion-prediction-autonomous-vehicles/discussion/199531#1091632" target="_blank">this thread</a>, we found that stacking boosted the score, but had no time left integrating the best model to stacking…</p>
<h2>Satellite image</h2>
<p>Until halfway through, I had mistakenly used satellite_debug as the 3 channel map information instead of semantic_map. Interestingly, this model got a public score of 13.3.<br>
I didn’t pursue it further because I realized the mistake, but it seems that satellite maps can score somewhat well in this task. Try it if you like it!!!</p>
<h2>3D-CNN(R2+1D)</h2>
<p>Rasterized image data in the form of RGB×T×H×W, then fed them into R2+1D.<br>
Validation score was equivalent to resnet18, but the process of rasterizing and the 3D-CNN model were so heavy that the training required twice ~ triple as much time.</p>
<h2>Only sequence model</h2>
<p>We trained Seq2seq model not only with the target agent’s history position, but also with the surrounding vehicle’s history position. Despite no map information, this model got a validation score of 24. We integrated this trained seq2seq model into the trained resnet18 model, and fine-tuned the concat model. Sadly, improvement of the score was marginal.</p>
|
Lyft Motion Prediction for Autonomous Vehicles
|
1st Place Solution & L5Kit Speedup
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lyft Motion Prediction for Autonomous Vehicles
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>As we were asked to share our ensemble model, please see the snippet below:</p>
<pre><code>import torch
from torch import nn
from typing import Dict
import timm
from timm.models.layers.conv2d_same import Conv2dSame
from utils.loss import pytorch_neg_multi_log_likelihood_batch
from utils.poolings import GeM
class LMM(nn.Module):
def __init__(self, model_architecture, H=30, gem=False):
super().__init__()
self.H = H
num_history_channels = (self.H + 1) * 2
rgb_channels = 6
num_in_channels = rgb_channels + num_history_channels
self.future_len = 50
num_targets = 2 * self.future_len
self.num_modes = 3
self.num_preds = num_targets * self.num_modes
self.backbone = timm.create_model(model_architecture, pretrained=False)
if gem:
self.backbone.global_pool = GeM()
self.backbone.conv_stem = Conv2dSame(
num_in_channels,
self.backbone.conv_stem.out_channels,
kernel_size=self.backbone.conv_stem.kernel_size,
stride=self.backbone.conv_stem.stride,
padding=self.backbone.conv_stem.padding,
bias=False,
)
self.backbone_out_features = self.backbone.classifier.in_features
self.backbone.classifier = nn.Sequential(
nn.Identity(),
nn.Linear(
in_features=self.backbone.classifier.in_features,
out_features=self.backbone_out_features,
),
)
self.lin_head = nn.Sequential(
nn.ReLU(),
nn.Linear(
in_features=self.backbone_out_features,
out_features=self.num_preds + self.num_modes,
),
)
for param in self.parameters():
param.requires_grad = False
def forward(self, image_box, image_sat, image_sem, history, history_availabilities):
x = torch.cat(
(
image_box[:, : self.H + 1].float(),
image_box[:, 31 : 31 + self.H + 1].float(),
image_sat,
image_sem,
),
1,
)
x = self.backbone(x)
x = self.lin_head(x)
return x
class LyftMultiModel(nn.Module):
def __init__(self, cfg: Dict, PARAMS, num_modes=3):
super().__init__()
self.future_len = cfg["model_params"]["future_num_frames"]
num_targets = 2 * self.future_len
self.num_preds = num_targets * num_modes
self.num_modes = num_modes
self.PARAMS = PARAMS
self.model1 = LMM("tf_efficientnet_b6_ns")
sd = torch.load("output/preds/config_ch_aws_2_checkpoint.pth")["model"]
self.model1.load_state_dict(sd, strict=True)
self.model1.lin_head = nn.Identity()
self.model3 = LMM("tf_efficientnet_b6_ns")
sd = torch.load("output/preds/config_ch_aws_1_checkpoint.pth")["model"]
self.model3.load_state_dict(sd, strict=True)
backbone_out_features = self.model3.backbone_out_features
self.model3.lin_head = nn.Identity()
self.model4 = LMM("tf_efficientnet_b3_ns", gem=True)
sd = torch.load("output/preds/philipp_config_17_ep5_checkpoint_lr5e6.pth")["model"]
self.model4.load_state_dict(sd, strict=True)
backbone_out_features_2 = self.model4.backbone_out_features
self.model4.lin_head = nn.Identity()
self.model5 = LMM("tf_efficientnet_b5_ns", H=8)
sd = torch.load("output/preds/config_ch_ddp_16_checkpoint.pth")["model"]
self.model5.load_state_dict(sd)
backbone_out_features3 = self.model5.backbone_out_features
self.model5.lin_head = nn.Identity()
self.lin_head = nn.Sequential(
nn.ReLU(),
nn.Linear(
in_features=backbone_out_features * 2
+ backbone_out_features_2
+ backbone_out_features3,
out_features=self.num_preds + num_modes,
),
)
def forward(
self,
image_box,
image_sat,
image_sem,
image_box2,
image_sat2,
image_sem2,
history,
history_availabilities,
):
self.model1 = self.model1.eval()
self.model3 = self.model3.eval()
self.model4 = self.model4.eval()
self.model5 = self.model5.eval()
x1 = self.model1(image_box, image_sat, image_sem, history, history_availabilities)
x3 = self.model3(image_box, image_sat, image_sem, history, history_availabilities)
x4 = self.model4(image_box2, image_sat2, image_sem2, history, history_availabilities)
x5 = self.model5(image_box2, image_sat2, image_sem2, history, history_availabilities)
x = self.lin_head(torch.cat([x1, x3, x4, x5], dim=-1))
bs, _ = x.shape
pred, confidences = torch.split(x, self.num_preds, dim=1)
pred = pred.view(bs, self.num_modes, self.future_len, 2)
assert confidences.shape == (bs, self.num_modes)
confidences = torch.softmax(confidences, dim=1)
return pred, confidences
class LyftMultiRegressor(nn.Module):
"""Single mode prediction"""
def __init__(self, predictor, PARAMS):
super().__init__()
self.predictor = predictor
self.PARAMS = PARAMS
def forward(
self,
image_box,
image_sat,
image_sem,
image_box2,
image_sat2,
image_sem2,
targets,
target_availabilities,
history,
history_availabilities,
velocity,
):
pred, confidences = self.predictor(
image_box,
image_sat,
image_sem,
image_box2,
image_sat2,
image_sem2,
history,
history_availabilities,
)
if self.PARAMS.predict_diffs:
pred = torch.cumsum(pred, dim=2)
loss_nll = pytorch_neg_multi_log_likelihood_batch(
targets, pred, confidences, target_availabilities
)
return loss_nll, pred, confidences
</code></pre>
<p>I am afraid we didn't do all ablation studies due to time constraints, so I can't tell the exact influence of the satellite view. It wasn't much, but with that many channels, we decided another three wouldn't hurt and may help in cases where the semantic view either fails to be drawn (happens sometimes) or in park like areas where cyclists do not drive on paved roads. </p>
<p>Indeed, key to our solution was being able to do many experiments. We found that using even more data than whats provided with the standard settings (harder samples in this case, the train loss was significantly higher) helped to squeeze out a bit more accuracy w.r.t. the competition metric. </p>
<p>Using more data was definitely one of the major improvements that we got. Even more improvement for a single model was gained by the pre-training on different raster-sizes. </p>
<p>Thank you for the praise.<br>
I uploaded 4 submissions that are very close to the checkpoints we have used in the final ensemble. The difference should be marginal. You can find them <a href="https://www.kaggle.com/ilu000/lyft-submission-csvs" target="_blank">here</a><br>
Note: first 20 rows in some submissions files are set to zero, so ignore their public LB score.</p>
<p>no, we have the satellite image for each pixel. It's just 3 extra channels, but for simplicity we have shown an image with the semantic view over the satellite image in this Writeup. </p>
<p>we have ego channels, agent channels, semantic channels, satellite channels</p>
<h1>1st Place Solution & L5Kit Speedup</h1>
<h2>Introduction</h2>
<p>First of all, I would like to thank Lyft for this great challenge and of course for their huge dataset. I must say I was a bit overwhelmed by the sheer amount of agents in the training set, but it was a fun experience to be able to train without ever using training data twice. Well, we did, when we used pre-trained models, but more on that later.</p>
<p>I also want to thank my Teammates <a href="https://www.kaggle.com/philippsinger" target="_blank">@philippsinger</a>, <a href="https://www.kaggle.com/christofhenkel" target="_blank">@christofhenkel</a> and <a href="https://www.kaggle.com/nvnnghia" target="_blank">@nvnnghia</a> for the great collaborative teamwork during the competition. We worked well together with a pipeline consisting of two repositories (version controlled custom l5kit and a training repo) and used logging in neptune.ai to keep track of the experiments. </p>
<h2>TL;DR</h2>
<p>Our solution is an ensemble of 4 efficientnet models trained with different rasterization parameters indivdually on train_full.zarr and stacked on validation.zarr. Key to training that many models on this huge dataset were several key improvements to the original l5kit repository to remove CPU bottleneck and enable efficient multi-GPU training using pytorch. </p>
<h2>Improvements/Changes to the L5Kit</h2>
<p>One of the major challenges in this competition was the slow rasterizer. We profiled the l5kit a lot and pinpointed the bottlenecks to speed it up by a factor of 4+. After that, our experiments were mostly GPU limited and multi-GPU experiments allowed us for "fast" iterations. Running through train_full (191_177_863+ samples) was possible within 2 days with medium sized models. </p>
<h3>Speedups</h3>
<p>Speed before changes with semantic view only (i5-3570K single thread, so ignore the actual time):</p>
<pre><code>Raster-time per sample: 0.124 s
Hits Time Per Hit % Time Line Contents
==================================================
9 11147507.0 1238611.9 93.6 rasterizer.rasterize(history_frames, history_agents, history_tl_faces, selected_agent)
</code></pre>
<p>All the speedups were achieved with plain python, no C++. The main speedups came from:</p>
<ol>
<li>Batched transformation of boxes with modifications from <a href="https://github.com/lyft/l5kit/pull/167" target="_blank">https://github.com/lyft/l5kit/pull/167</a>. <br>
It has been said that the transformation is the bottleneck in the rasterizer as it is called a lot. We used the vectorized transformation whereever possible.</li>
<li>In <code>box_rasterizer.py</code>, using python lists of small numpy arrays instead of one two large numpy arrays (<code>agent_images, ego_images</code>).<br>
Python lists are surprisingly fast! <code>np.concatenate</code> on large numpy arrays is slow. Pre-allocation and writing to a single large array is even slower.<br>
The lists can be cast to a numpy array by <code>out_im = np.asarray(agents_images + ego_images, dtype=np.uint8)</code><br>
This way, boxes will stay in <code>uint8</code></li>
<li>Moving concatenate to the GPU<br>
As <code>np.concatenate</code> is slow on large arrays, we do that on the GPU.<br>
Replace <code>"image": image,</code> with <code>"image_box": image_box</code>, <code>"image_sat": image_sat</code>, <code>"image_sem": image_sem</code></li>
<li>Speedups from <a href="https://github.com/lyft/l5kit/pull/140" target="_blank">https://github.com/lyft/l5kit/pull/140</a><br>
With the changes above, they now made a larger impact than the 7-8% stated in the PR.</li>
</ol>
<p>Speed after changes with semantic and satellite view (i5-3570K single thread, so ignore the actual time):</p>
<pre><code>Raster-time per sample: 0.032 s
Hits Time Per Hit % Time Line Contents
==================================================
9 2847054.0 316339.3 84.2 rasterizer.rasterize(history_frames, history_agents, history_tl_faces, selected_agent)
</code></pre>
<h3>Additions/Changes</h3>
<ul>
<li>New rasterizer which combines satellite and semantic view (<code>py_sem_sat</code>).</li>
<li>Flag: AgentID used as a value for drawing (instead of just boolean <code>no agent = 0</code>, <code>agent = 1</code>)</li>
<li>Flag: AgentLabelProba used as a value for drawing (instead of just boolean <code>no agent = 0</code>, <code>agent = 1</code>)</li>
<li>Flag: Velocity used as a value for drawing (instead of just boolean <code>no agent = 0</code>, <code>agent = 1</code>)</li>
<li>Option to draw all objects on the semantic layer, combinable with the label probas from above.</li>
<li>Filter options for agents: <code>th_extent_ratio, th_area, th_distance_av</code> to give a larger training dataset (or harder as you want to phrase it)</li>
<li>Multiple parallel rasterizers for ensembling models that use different raster sizes</li>
<li>Satellite view fix for non square shapes (had some weird transformation in it before)</li>
</ul>
<p><img src="https://i.imgur.com/G3g9lEJ.png" alt="rasterized_image"></p>
<p>We will make our L5kit code changes public in the next few days and after cleanup. Most likely with PRs to the original repo.</p>
<h2>Journey & Experiments</h2>
<p>With all the speed improvements from our custom L5kit we were able to eliminate the previous CPU bottleneck and run experiments on an efficient multi-GPU setup. We mostly trained on 8xV100 nodes using pytorchs awesome distributed data parallel (DDP), which enables to effectivly scale a training script to multiple GPUs. This efficient training setup was key to run quite a few experiments. (See list of stuff that did not work below) In all our experiments, we used the chopped validation set for local validation as discussed <a href="https://www.kaggle.com/c/lyft-motion-prediction-autonomous-vehicles/discussion/188695" target="_blank">here</a>. This yielded us very good prediction of the LB score (in the sub 13 range, the score was usually ~0.2 higher than local validation with a standard deviation of around 0.3). </p>
<p>Originating from the provided baseline and the multi-mode prediction from <a href="https://www.kaggle.com/corochann/lyft-training-with-multi-mode-confidence" target="_blank">here</a>, we experimented with raster size, pooling layers, head-modifications, usage of different backbones, learning rate scheduler, subsampling and oversampling to name a few. It was a major challenge in this competition, that experiments had to be run for at least 50 % of a full epoch of train_full.zarr or when comparing different sample sizes or learning rate scheduler even until the end to be really comparable. Subsampling the train set or stepwise decrease of the LR quickly yielded a low training and validation loss, but in the end, the performance was worse.</p>
<p>Quite quickly, we decided to always use all data, and settled to a setup using shuffled train_full.zarr (with a fixed seed to be able to resume training) with a linear decay learning rate scheduler. To keep the training sample fixed, we also settled to an AgentDataset with <code>min_frame_history=1</code> and <code>min_frame_future=10.0</code> to best resemble the test dataset. Opposed to the many discussions about a much lower training loss, we never experienced that. Without any augmentation, the training loss is of course slightly lower, especially in the end of the epoch, but usually within 80% of the validation score. We found that larger backbones help to reach lower loss levels, but starting at the size of an EfficientNetB7, the nets seem to be overconfident with their predictions and the LB score was sometimes shaky. </p>
<p>The first half of test is public, second half is private test. We couldn't identify any major differences in the two sets. With that knowledge it was possible to hide the true score (setting some public rows to zeros), we wonder how many teams did that and were afraid of surprises in the private LB due to this. </p>
<h2>Best Single Model</h2>
<p><img src="https://i.imgur.com/YC1WGD1.png" alt="model"></p>
<p>Our best single model is actually one that not fully finished on the last day. It's just an EfficientNetB3 with a Linear Layer Head and dropout attached trained on an extended train_full.zarr Dataset (<code>min_frame_history=1, min_frame_future=5.0, th_distance_av=80, th_extent_ratio=1.6, th_area=0.45</code>)</p>
<ul>
<li>history_num_frames: 30.0</li>
<li>raster_size: [448, 224]</li>
<li>pixel_size: [0.1875, 0.1875]</li>
<li>rasterizer: py_sem_sat</li>
<li>batch_size: 64</li>
<li>dropout: 0.3</li>
</ul>
<p>The model was pre-trained for 4 epochs on different lower resolution images (starting with 112, 64 and pixel size 0.75, 0.75) , so you can argue this is also an ensemble of some kind. The 5th epoch was trained with the parameters above and a very customized learning rate schedule that starts with a consine anneal and then transitions to a stepwise lr scheduler as seen in the graph below. The last evaluation score is 9.697.</p>
<p><img src="https://i.imgur.com/4Q2PkvX.png" alt="best_single"></p>
<p>The model achieves a public LB score of 9.776 and a private LB score of 9.070. With that, it would also have ranked 1st place this competition on it's own.</p>
<p>Pretraining is VERY important! We discovered it by a mistake where we loaded an EfficientNet without pretrained weights from imagenet. It performed significantly worse by ~1.00.</p>
<h2>Ensemble</h2>
<p>Ensembling proved to be challenging in this competition, as traditional methods are not working well with the metric in use. We tried a lot of manual blending and form of post-processing without success. We then started building stacking models taking the raw predictions of the models as input, but this was also surprisingly not working well. At about the same time as <a href="https://www.kaggle.com/hengck23" target="_blank">@hengck23</a> posted it <a href="https://www.kaggle.com/c/lyft-motion-prediction-autonomous-vehicles/discussion/193908#1077899" target="_blank">here</a>, we had the idea of using the features/embeddings from each model as an input to a ensemble head. This worked much better and we could improve upon our single models specifically as we could introduce some diversity into the blend (different image size, pixel sizes, etc.) We also went with the dropout + single linear layer approach here, and all modification we tried with the head performed worse.</p>
<p><img src="https://i.imgur.com/2I3M2rD.png" alt="ensemble_arch"></p>
<p>To prevent overfitting, the ensembling was done on the chopped validation set (without using the chopped off actual validation part), in some experiments extended to validation + test set without noticeable change in the metric but with about twice the runtime. </p>
<p>Ensembles of two similar models (even just two different checkpoints) already gave a boost of about 0.2 in the metric. Naturally, with more diverse models the ensemble performed even better and we were able to achieve our best public LB score of 9.319 and private LB score of 8.579 with an ensemble of 4 models (B3, B5, B6, B6) on two different raster sizes. </p>
<h2>Bootstrapped Validation</h2>
<p>We evaluated model and ensemble performance with bootstrap method on the chopped dataset. For more diverse ensembles we also got the lowest standard deviation from the bootstrap method. For our final submission it was 0.22754. The best single models had a standard deviation of ~0.27. We also identified our B7 and B8 models to have a slightly larger standard deviation in the bootstrap method of ~0.36-0.39 which may also explain their partial performance degredations on the public LB. Despite their good validation score, for that reason we excluded them in our final ensembles and final submissions. </p>
<p><img src="https://i.imgur.com/l4vEAaz.png" alt="bootstrap"></p>
<p>We plotted CV vs public LB for our submissions and found a spread of +-0.3 for most of our single models (green corridor) with just the B7 and B8 models outside of that corridor (not shown in the picture). Our ensembles are in an even smaller corridor with a spread of +-0.1 (orange corridor), proving their superior robustness and generalization capabilities over single models. </p>
<p><img src="https://i.imgur.com/S6fYsBI.png" alt="cv_lb"></p>
<p>Given this robust CV & LB correlation, we were very confident that improvements in validation also lead to improvements on the leaderboard, so we did not have to sub it. So the sudden jump on public leaderboard only happened after we decided to sub our better models and was not some sudden magic we discovered.</p>
<h2>What Didn't Work</h2>
<ul>
<li>Flag: AgentID used as a value for drawing (instead of just boolean <code>no agent = 0</code>, <code>agent = 1</code>)</li>
<li>Flag: AgentLabelProba used as a value for drawing (instead of just boolean <code>no agent = 0</code>, <code>agent = 1</code>)</li>
<li>Flag: AgentLabelProba used as a value for drawing (instead of just boolean <code>no agent = 0</code>, <code>agent = 1</code>)</li>
<li>Option to draw all objects on the semantic layer, combinable with the label probas from above.</li>
<li>Kalman filtering the output</li>
<li>Any non NN prediction method</li>
<li>Prediction of only the difference to a constant velocity model</li>
<li>Using additional informations, such as velocity, history positions, label probas or anything else we could find in the head of the models. </li>
<li>Heavier heads</li>
<li>3D CNNs</li>
<li>RNN based approaches on history frames for backbone input or outbut </li>
<li>Using additional features from shallower layers of the backbone</li>
<li>Ensembling with kmeans, or other analytic clustering method that we tried. Some success at scores down to around 14, but no improvements below that. </li>
<li>Subsampling the training set. Huge speedups, but accuracy was always slightly lower</li>
<li>TTA with modified yaw angles</li>
<li>Unfreezing the backbone after ensembling and continue training with a second epoch</li>
</ul>
<h2>What We Didn't Try</h2>
<ul>
<li>Augmentation</li>
<li>Multi backbone, multi rasterizer training</li>
</ul>
<p>The distribution is from a bootstrap validation method where we randomly subsample (with multi-draw) 35k rows of the validation set. It's the histogramm over the scores of all subsamples, and not the scores of a single validation set. <br>
We did that, to measure the stability of the predictions (chance of shakeup).<br>
The largest single sample loss is ~2k as far as i remember. We all saw how skewed the score distribution is ;)</p>
<p>Yes, 66 channels in that case</p>
<p>Awesome! Great to see an analytic method to be on par or even superior to our method. <br>
Could you try to weight the B3 model a bit higher (it has the best score out of those). And I am very interested in your ensembling code or the specific execution. </p>
|
Lyft Motion Prediction for Autonomous Vehicles
|
21st solution: freeze and stage-wise training
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lyft Motion Prediction for Autonomous Vehicles
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>in summary (lb shown in red is public LB):<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F113660%2F936f4a397b66a26c15b2fe47ac47087c%2FSelection_063.png?generation=1606461205385767&alt=media" alt=""></p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F113660%2Fd426997c9a23e7b0777ede06cbb62de2%2FSelection_061.png?generation=1606460932975188&alt=media" alt=""></p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F113660%2Fef5337723983b036b1b613c6d4b87da5%2FSelection_062.png?generation=1606460950160462&alt=media" alt=""></p>
<p>since ensemble is difficult, I adopt stacking.</p>
|
Lyft Motion Prediction for Autonomous Vehicles
|
22nd place journey : a completely different motion prediction approach
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lyft Motion Prediction for Autonomous Vehicles
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks <a href="https://www.kaggle.com/seriousran" target="_blank">@seriousran</a> </p>
<p>Thanks <a href="https://www.kaggle.com/ulrich07" target="_blank">@ulrich07</a> </p>
<p>Thanks <a href="https://www.kaggle.com/doanquanvietnamca" target="_blank">@doanquanvietnamca</a> , I learn't a lot from you as well :) </p>
<p>First of all, many thanks to the Kaggle team and Lyft team for hosting this competition, and congrats to all winners! Thanks to my teammates too, especially <a href="https://www.kaggle.com/doanquanvietnamca" target="_blank">@doanquanvietnamca</a> for his hard work and commitment during all those 3 laborious months.</p>
<h1>Preditcting agent motion with PointNet architecture …</h1>
<p>Our ideas are mainly based on the pointnet architechture. We totally forgot about L5kit package and deal with the raw data which was transformed into a 4D tensors of shape (num_mini_scenes, max_agents_on_frame, num_backward_frames, num_features). Those tensors are concatenated over n_batches scenes and feed to the pointnet architecture. We was able to reach a score of 21.xx by using a single pointnet model but things become harder and we got stuck.</p>
<h1>Breakthrough ideas</h1>
<p>To push our model performance a little bit, we manage to stack many pointnet models. This was doable since pointnet is very lightweight. Each model will look at a limited time step back to the agent history and output some embeddings of the scenes, the embeddging are then projected into a lower dimension space and concatenated. A simple full connected head is responsible for outputing the final 300+3 predictions.<br>
Our best model is composed of 4 stacked models which resp. look at 10, 5, 3, and 1 frame back into the agent history. We use a simple zero padding for agents with no enough frames. With that giant pointnet model (~40 M params), we was able to reach a score of 13.353 on the public LB and 12.912 on the private.</p>
<h1>Custom loss and training</h1>
<p>We implement a custom version of the competition loss in which agent's loss is ignored when it leaves the scene. This custom loss allows us to try things like sample weight, penalization … We use <strong>pytorch-lightening</strong> to ease things. We maingly train on Colab, which is just owesome given the huge size of the competiion dataset. The optimizer is the classical Adam with a step learning rate scheduler, nothing fancy over there.</p>
<h1>Things that doesn't work</h1>
<ul>
<li>Sample weight</li>
<li>Bagging: we try a lot of ideas, and they all fail :(</li>
<li>RNN : we try a LSTM over time-stacked models without any success</li>
<li>Longer history : augementing the history step leads to worse results (likely because of the many zeros coming from our zero padding stratedy)</li>
</ul>
<h1>Advantages of our model</h1>
<ul>
<li>Very fast model, whole inference last 14 min's with single model and less than 30 minutes with tens of stacked models</li>
<li>Training on whole train_full takes just 30' with a light pointnet model and 1h30' with 4 stacked models on a Colab Tesla-V100 single GPU</li>
</ul>
<h1>Cons of our model</h1>
<ul>
<li>Our pointnet implementation is completely road lanes blinded, even if we manage to incorporate light faces info in some extents</li>
</ul>
<h1>Things we may like to try</h1>
<ul>
<li>Moving from pointnet to other point-cloud models or voxel based models (pointCNN, point-Voxel, ShapeNet, …)</li>
<li>Stacking & transfer learning: use our best models as embedders and train a simple model on top of them</li>
<li>Combining our model with other image raster models (this one could make the pointnet road lanes aware)</li>
<li>3D convolutions</li>
</ul>
<p>PS: Our inference code by <a href="https://www.kaggle.com/doanquanvietnamca" target="_blank">@doanquanvietnamca</a> is available <a href="https://www.kaggle.com/doanquanvietnamca/22st-solution-kkiller" target="_blank">here</a> .</p>
<p>Thanks <a href="https://www.kaggle.com/duykhanh99" target="_blank">@duykhanh99</a> </p>
<p>Nice extrapolation of our ideas over there :) </p>
|
Lyft Motion Prediction for Autonomous Vehicles
|
23rd solution (single model based on Resnet18)
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lyft Motion Prediction for Autonomous Vehicles
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>This was a nice dataset to play with. It is like HPC simulations, one have to relax and let things run for long. To my surprise, one can go very far using simple concepts and published work. My solution is simply an implementation of the two papers from Uber<br>
1- Uncertainty-aware Short-term Motion Prediction of Traffic Actors for Autonomous Driving, <a href="https://arxiv.org/abs/1808.05819" target="_blank">https://arxiv.org/abs/1808.05819</a><br>
2- Multimodal Trajectory Predictions for Autonomous Driving using Deep Convolutional Networks, <a href="https://arxiv.org/abs/1809.10732" target="_blank">https://arxiv.org/abs/1809.10732</a></p>
<p>Now to some details which I think contributed to my best performing model:</p>
<p>1- Sample the data to break the serial correlation in time. I only trained on frames with 60+10+1 gaps. I wanted to avoid data leakages so I kept a gap of history length (10) + future prediction (50) + (1) extra. Also, if a frame is too crowded (i.e. too many agents), I sampled a sub-set of the agents (20 in my code below).</p>
<pre><code>def get_dataset_masks(
zarr_path,
zarr_dt,
th_agent_prob: float,
min_frame_history: int,
min_frame_future: int,
scene_mask=None,
chop_data=False,
chop_idx_list=[100, 200],
chop_agents=False):
"""
Modified from create_chopped_dataset
Returns:
mask: numpy array of bool to pass to AgentDatasetExtended
"""
if scene_mask is None:
scene_mask = np.ones(len(zarr_dt.scenes), dtype=np.bool)
else:
assert len(zarr_dt.scenes) == len(scene_mask), "mask should be equal length"
agents_mask_path = Path(zarr_path) / f"agents_mask/{th_agent_prob}"
if not agents_mask_path.exists(): # don't check in root but check for the path
assert 0
agents_mask_original = np.asarray(convenience.load(str(agents_mask_path)))
agents_mask = np.zeros(len(zarr_dt.agents), dtype=np.bool)
# for scene in zarr_dt.scenes.get_mask_selection(scene_mask):
for scene_idx in range(len(zarr_dt.scenes)):
if scene_mask[scene_idx] == 0:
continue
scene = zarr_dt.scenes[scene_idx]
if chop_data:
for num_frame_to_copy in chop_idx_list:
kept_frame = zarr_dt.frames[scene["frame_index_interval"][0] + num_frame_to_copy - 1]
agents_slice = get_agents_slice_from_frames(kept_frame)
# In create_chopped_dataset: no mask for min_frame_history
mask = agents_mask_original[agents_slice][:, 1] >= min_frame_future
num_agents_per_frame = mask.sum()
max_agents_per_frame = 20
if chop_agents and num_agents_per_frame > max_agents_per_frame: # or 10
removed_indices = np.random.choice(
np.where(mask)[0],
num_agents_per_frame - max_agents_per_frame,
replace=False)
mask[removed_indices] = False
agents_mask[agents_slice] = mask.copy()
else:
first_frame = zarr_dt.frames[scene["frame_index_interval"][0]]
last_frame = zarr_dt.frames[scene["frame_index_interval"][1] - 1]
agents_slice = get_agents_slice_from_frames(first_frame, last_frame)
past_mask = agents_mask_original[agents_slice][:, 0] >= min_frame_history
future_mask = agents_mask_original[agents_slice][:, 1] >= min_frame_future
mask = past_mask * future_mask
agents_mask[agents_slice] = mask.copy()
return agents_mask
</code></pre>
<p>2- I had a clean implementation of the Multiple-Trajectory Prediction (MTP) loss. I trained on the MoN loss and validated on the nll loss</p>
<pre><code>def uber_like_loss_new(gt, pred, confidences, avails):
batch_size, num_modes, future_len, num_coords = pred.shape
# ensure that your model outputs logits
gt = gt[:, None, :, :] # add modes
avails = avails[:, None, :, None] # add modes and cords
l2_error = torch.sum(((gt - pred) * avails) ** 2, dim=-1) # reduce coords and use availability
l2_error = torch.sum(l2_error, dim=-1) # reduce future_len
best_mode_target = torch.argmin(l2_error, dim=1).detach()
classification_loss = torch.nn.functional.cross_entropy(confidences, best_mode_target, reduction='none')
alpha = 1.0
MoN_error = classification_loss + alpha * l2_error[torch.arange(batch_size), best_mode_target]
MoN_error = MoN_error.reshape(-1, 1)
error = torch.nn.functional.log_softmax(confidences, dim=1) - 0.5 * l2_error # reduce future_len
max_value, _ = torch.max(error, dim=-1, keepdim=True) # error are negative at this point, so max() gives the minimum one
nll_error = -torch.log(torch.sum(torch.exp(error - max_value), dim=-1, keepdim=True)) - max_value
return MoN_error, nll_error
</code></pre>
<p>3- I extracted some meta data from the AgentDataset. Here is a minimal implementation </p>
<pre><code>class AgentDatasetExtended(AgentDataset):
def __init__(
self,
cfg,
zarr_dataset,
rasterizer,
perturbation,
agents_mask,
min_frame_history,
min_frame_future,
transform,
l5kit_version,
):
assert perturbation is None, "AgentDataset does not support perturbation (yet)"
super(AgentDatasetExtended, self).__init__(
cfg, zarr_dataset, rasterizer, perturbation, agents_mask, min_frame_history, min_frame_future)
self.min_frame_future = min_frame_future
self.min_frame_history = min_frame_history
self.transform = transform
self.l5kit_version = l5kit_version
def __getitem__(self, index: int) -> dict:
"""
Differs from parent returning the indices of the frame, agent and scene
"""
if index < 0:
if -index > len(self):
raise ValueError("absolute value of index should not exceed dataset length")
index = len(self) + index
index = self.agents_indices[index]
track_id = self.dataset.agents[index]["track_id"]
frame_index = bisect.bisect_right(self.cumulative_sizes_agents, index)
scene_index = bisect.bisect_right(self.cumulative_sizes, frame_index)
if scene_index == 0:
state_index = frame_index
else:
state_index = frame_index - self.cumulative_sizes[scene_index - 1]
data_dic = self.get_frame(scene_index, state_index, track_id=track_id)
# track_id = self.dataset.agents[index]["track_id"]
# centroid = self.dataset.agents[index]["centroid"]
# yaw = self.dataset.agents[index]["yaw"]
velocity = self.dataset.agents[index]["velocity"]
label_probabilities = self.dataset.agents[index]["label_probabilities"]
# data_dic['track_id2'] = np.int64(track_id)
# data_dic['centroid2'] = centroid
# data_dic['yaw2'] = yaw
data_dic['velocity'] = velocity
data_dic['label_probabilities'] = label_probabilities
data_dic['ego_translation'] = self.dataset.frames[frame_index]["ego_translation"]
data_dic['ego_rotation'] = self.dataset.frames[frame_index]["ego_rotation"] # matrix
data_dic['timestamp'] = self.dataset.frames[frame_index]["timestamp"]
data_dic['hour'] = datetime.fromtimestamp(data_dic['timestamp'] / 1e9).hour
data_dic['weekday'] = datetime.fromtimestamp(data_dic['timestamp'] / 1e9).weekday()
if self.transform:
data_dic = self.transform(data_dic)
return data_dic
</code></pre>
<p>4- I had a second head of 47 inputs (probably too much), which is fed all sort of metadata (label_probabilities, yaw, extent, acceleration, ego_translation, ego_centroid_diff, hour, weekday) and then passed through two fully connected layers before merging with the pooling layers of the backbone. This concatenated vector is then passed to dense layer, relu and then the output layer.</p>
<p>5- I applied a <code>cumsum</code> function to NN output to force the NN to produce something like the differences, then I applied the image_to_world_matrix transformation before calling the loss function of the real coordinate. I wanted the output of my NN model to be in the image space (conceptually). </p>
<p>There are many small additional details. I used lookahead optimizer wrapped around ADAM with starting learning rate of 1e-4 that and then decreased the LR by 0.99 every 100000 steps over batches of 32 samples (which takes about an hour on my machine RTX-Titan-X). Learning rate is reduced after 20 iterations of the 320k samples. Best solution is reached after 110 of these 320k samples (best model Private LB 13.580, Public LB 14.265). I then averaged 7 models based on checkpointing (Private LB 13.154, Public LB 13.722). My image size is 336x336 with a resolution of 0.25x0.25, trained on full data with the following frames <code>chop_idx_list_train = [11, 11 + 61, 11 + 2 * 61, 11 + 3 * 61]</code></p>
<p>Probably, few simple modification could produce a bit better score.<br>
(a) A bigger patch of 64 samples might perform better (diversity of the samples). <br>
(b) Change the backbone to ResNet50 or MobileNet-V2</p>
<p>I didn't test that and as reported in the paper, the differences interms of the evaluation metrics are not that big. However, I recently came across the diversity loss (see <a href="https://arxiv.org/abs/2011.15084" target="_blank">https://arxiv.org/abs/2011.15084</a>) by adding a L2 penalty on similar predictions to the NLL loss.</p>
|
Lyft Motion Prediction for Autonomous Vehicles
|
25nd place Summary
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lyft Motion Prediction for Autonomous Vehicles
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>I only compared the loss function when doing the cross validation (using little parts of the dataset). I remembered the improvement was around "-1" for the evaluation metric. However, I am not sure that there would be so much improvement when using all of my training data</p>
<blockquote>
<blockquote>
<p>How much did turning data into tfrecord speed up training for you?<br>
Around 2~3 days. Actually I used a lot of machines to do this.</p>
</blockquote>
</blockquote>
<p>To enhance the weak modes, I had also tried a loss function which formulate the confidence estimation as a classification problem. The confidence of the mode with the least MSE would be "1" while the others are "0", and I calculated the cross entropy of the confidences as part of the loss function. However it did not work either.</p>
<h2>Tools I used</h2>
<ul>
<li>Tensorflow/Keras</li>
<li>Colab (with TPU, free version)</li>
<li>Google Cloud Storage<br>
I rendered the data offline, packed the data into .tfrec format, and uploaded them to Google Cloud Storage (~2TB), To ensure that the size would not be exploded, I compress the image into PNG format</li>
</ul>
<h2>Dataset</h2>
<ul>
<li>Used training (not full version*) and validation data</li>
<li>Used default setting (from sample code) for rendering except min_future_frame ( = 10)</li>
</ul>
<h2>Network backbone</h2>
<ul>
<li>Xception<br>
I had tried a lot of backbone provided from Keras and different version of Resnet (101, 50, 34, 18), and found Xception's quality was the best (through validation)</li>
<li>Batch size = 256</li>
</ul>
<h2>Other tricks</h2>
<ul>
<li>Validation<br>
Validation data and part of training data were used, and I separated both training and validation data into five parts by y-position of agent's center points. I made sure that the same (or similar) maps would not appear in both training and validation data simultaneously</li>
<li>Multimode<br>
I predicted 4 modes and picked the top-3 (determined by confidences) modes. Besides, I had tried more modes (> 4) but found only 4 modes had larger confidence values while the other modes' never be picked. The unbalanced issue seems common in multimode trick</li>
<li>Label smoothing <br>
I "multiply" a small gaussion noise (mean = 1, std = 0.00333) to each ground truth.</li>
<li>Custom loss function<br>
I used the evaluation metric for multimode (provided from official) as loss function. To gave more penalty to the corner cases, the loss was multiply by a weight, which was proportional to the "Angle" of each agent<br>
Angle = acos(x/sqrt(x**2 + y ** 2)), (x, y) is the coordinate of the final position of each agent </li>
<li>Discard History<br>
I used 10 history frames for training, but I found that around 5% testing data had history frames less than 10. So, I discard the history of target history frame randomly</li>
</ul>
<p>*Due to the limitation of memory in colab, I could not use preprocess full training data. So sad.</p>
|
Lyft Motion Prediction for Autonomous Vehicles
|
3rd Place Solution: Baseline + Set Transformer
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lyft Motion Prediction for Autonomous Vehicles
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Update: YouTube video about our solution <a href="https://youtu.be/3Yz8_x38qbc" target="_blank">https://youtu.be/3Yz8_x38qbc</a></p>
<h1>TL;DR</h1>
<ul>
<li>Baseline CNN regression</li>
<li>Six 3-mode models based on: Xception41, Xception65, Xception71, EfficientNetB5</li>
<li>One 16-mode Xception41 model</li>
<li><a href="https://arxiv.org/abs/1810.00825" target="_blank">Set Transformer</a> as a second level clusterizer model for ensembling</li>
</ul>
<p>Our code is available on <a href="https://github.com/asanakoy/kaggle-lyft-motion-prediction-av" target="_blank">GitHub</a></p>
<h1>Detailed solution</h1>
<h2>1. Data preprocessing</h2>
<p>The first level models used the same raster format as generated by l5kit, with next settings:</p>
<p>raster_size=[224, 224]<br>
pixel_size=[0.5, 0.5]<br>
ego_center=[0.25, 0.5]</p>
<p>With history frames rendered at frame offsets 0, 1, 2, 4, 8.</p>
<p>We found the significant time with l5kit rasterizer is spent to prepare coordinates for opencv rendering due to the large number of operations on small numpy arrays, so we combined multiple stages like transform points and CV2 shift to single, numba optimized functions.</p>
<p>This allowed us to improve performance approximately 1.6x.</p>
<p>Another improvement was to uncompress zarr files, it’s especially useful with random access.</p>
<p>Next improvement was to save the cached raster and all relevant information for each training sample to numpy compressed npz file. Especially with the full dataset, we saved each N-th frame for training, since the following frames are usually very similar.</p>
<p>All optimization combined allowed to <strong>improve the CPU load during training around 6x</strong> and train multiple models simultaneously. The cached training samples for the full dataset used around 1.3TB of space. Fast nvme SSD drive is useful.</p>
<h2>2. First level CNN models</h2>
<p>We have tried many approaches but could not beat the baseline solution of using the imagenet pretrained CNN, avg pooling or trainable weighted pooling and fully connected layer to directly predict positions and confidences of trajectories.</p>
<p>What made a bigger difference was the training parameters. We used SGD with a relatively high learning rate of 0.01, gradient clipping of 2 and batch size around 64-128.</p>
<p>We used the modified CosineAnnealingWarmRestarts scheduler, starting from period of 16 epoch (200000 samples each), increasing period by 1.41421 times each cycle.</p>
<p>We used the following models:</p>
<ul>
<li>Xception41, avg pool, batch size 64</li>
<li>Xception41, avg pool, batch size 128 - similar performance to batch size of 64</li>
<li>Xception41, learnable weighted pooling</li>
<li>Xception41, predicts 16 modes instead of 3</li>
<li>Xception65</li>
<li>Xception71 - seems to be the best performing model, but was trained less comparing to Xception41 due to the shortage of time</li>
<li>EfficientNet B5</li>
</ul>
<p>Initially the EfficientNet based model performed worse compared to Xception41, but with the batch size increased from 64 to 128, the performance improved significantly, with results on par with Xception.</p>
<p>Models have been trained on the full training dataset for about 5-7 days on a single GPU (2080ti, 3090 for larger models) each.</p>
<p>Training for longer would likely improve the score, for example Xception41 model reached following validation loss during the last 3 cycles: 11.31, 10.86, 10.37<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F2000545%2Fdc9904887584210bbfa46ee33f7a9dd2%2FScreen%20Shot%202020-12-20%20at%200.20.53.png?generation=1608412893460095&alt=media" alt=""></p>
<h2>3. Ensembling (second level model)</h2>
<p>Since we cannot simply average different models predictions, we used an approach where we find 3 trajectories that best approximate input trajectories. This can be achieved by utilizing the competition loss directly, but with input trajectories as ground truth and weighted by input confidences. This can be seen as a particular case of GMM.<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F2000545%2Fd3c6cac01be9fef035946f893e3a0f05%2FScreen%20Shot%202020-12-20%20at%200.25.01.png?generation=1608413124490687&alt=media" alt=""><br>
where n index relates to input trajectories and k index relates to 3 final output trajectories.</p>
<p>At first we optimized this loss with a BFGS solver and this already worked pretty well, however, it was very sensitive to the initialization and tended to get stuck in local optima.</p>
<p>We tried to use stacking on a hold-out dataset, i.e., train a 2nd level model that takes trajectories from 1st level models as input and predicts 3 completely new trajectories. We compared a bunch of different architectures from MLP to LSTM and luckily came across Set Transformer, which worked almost as well as the BFGS optimizer. Then we noticed that in the paper, they also utilize the model for the GMM task, so we tried to optimize the loss mentioned above with the model instead of stacking, i.e., train it from scratch on the whole val (or test) dataset. It consistently performed by around 0.2 better than the optimizer. We explain such a performance boost by the model's ability to leverage global statistics of the entire provided amount of training data, in contrast to the optimizer, which works sample-wise.</p>
<p>Our Set Transformer architecture is pretty simple. As an encoder, we have a 2-layer Transformer without positional encoding. In the decoding stage, we have three so-called "seed vectors" that are trainable parameters. Those vectors attend to the encoded representations of the trajectories.<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F2000545%2F0c90849861c770da146a1c1b6ec0f32c%2FScreen%20Shot%202020-12-20%20at%200.27.11.png?generation=1608413244195430&alt=media" alt=""></p>
<p>All of the input trajectories are predictions from 3-mode models. However, we also had a 16-mode model that boosted the optimizer quite a bit, but didn't help the transformer. So what we did was to add the 16-mode model predictions to the loss, but remove from the input.</p>
<h1>Other interesting findings and what didn't work for us</h1>
<h2>1. Experiments with the Set Transformer</h2>
<p>When experimenting with the Set Transformer on a hold-out train set, we found these interesting results.</p>
<table>
<thead>
<tr>
<th>Method</th>
<th>Val nll loss</th>
<th>Inference time on the entire val</th>
</tr>
</thead>
<tbody>
<tr>
<td>Optimizer</td>
<td>12.06</td>
<td>~ 30 min</td>
</tr>
<tr>
<td>Transformer: supervised on train set</td>
<td>12.06</td>
<td><strong>< 1 sec</strong></td>
</tr>
<tr>
<td>Transformer: unsupervised on train set</td>
<td>12.00</td>
<td><strong>< 1 sec</strong></td>
</tr>
<tr>
<td>Transformer: unsupervised→supervised fine-tune on train set</td>
<td><strong>11.98</strong></td>
<td><strong>< 1 sec</strong></td>
</tr>
<tr>
<td>Transformer: unsupervised on val set</td>
<td><strong>11.82</strong></td>
<td>~ 30-50 min</td>
</tr>
</tbody>
</table>
<p>Supervised here denotes stacking (original NLL loss with GT trajectory as a target ), and unsupervised indicates the above-mentioned ensemble loss. </p>
<p>In the table, we can see that unsupervised training from scratch on the validation data has the best performance. However, we can also utilize a train set to train a model that generalizes well to the validation set, outperforming the optimizer. Such an approach is speedy (as only a forward is needed to predict for a new observation) and may be more suitable for production purposes.</p>
<h2>2. Data preprocessing not used for submitted models</h2>
<p>We also added extra rasterizer outputs, related to traffic lights: in addition with the current rendering, we added additional 1/4th resolution planes with information about the current and previous traffic lights. We added the separate planes for known on and off traffic lights for forward, left and right directions for the current and previous moments in time. The intuition behind - to provide the model an extra information and separate unknown traffic light from the known off traffic light, has traffic light changed right now or some time ago and easier way to distinguish different signal directions. Lower resolution is sufficient to associate the signal with lanes but can be mixed to deeper model layers, where it does not have to be compressed so much with other inputs. When trained with the extra traffic light inputs, the training and validation loss dropped faster initially but converged to the same level after a few cycles. This approach may still be useful for models used outside of the small training area.</p>
<h2>3. What we tried, with performance either on par or worse comparing to the simple baseline</h2>
<ul>
<li>Used kalman filter to estimate less noisy initial position, velocity, acceleration and angular rate / turn radius: Slightly faster but less stable training, the same final result.</li>
<li>Used transformers to model interaction between agents and map, no improvement</li>
<li>Predict the occupation map. May actually be useful for planning, but not very useful for the competition metrics. </li>
<li>Use the predicted occupancy map of other agents as an input</li>
<li>Predict all agents recurrently, using transformers or CNN</li>
<li>Added positions embeddings for points on the map</li>
<li>Different heads to predict trajectory, RNN, predict acceleration/turn, separate trajectory parameters from velocity on trajectory etc.</li>
<li>Different number of FC (0-3) layers before the final output FC layer</li>
</ul>
<h1>Conlusion</h1>
<ul>
<li>CNN regression baseline is very hard to beat</li>
<li>Training for longer with right parameters on the full dataset was the key</li>
<li>l5kit can be optimized by a lot</li>
<li>Great competition overall: lots of high quality data, nice optimizable metric, very<br>
supportive host</li>
<li>Though we thought it would have been better to split train/val/test by geographical<br>
location and to increase the train area.</li>
</ul>
<p>Thanks for reading and happy kaggling!</p>
<p>Hi, thanks for the comment.<br>
You can download our test predictions in npz format from <a href="https://drive.google.com/drive/folders/1hM0aPGugVeAY8qUAUIWVBVcqb3KGk2rQ?usp=sharing" target="_blank">here</a>. Just ignore the sample submission csv. Our scores with these models are: public - 10.209, private - 9.404.</p>
<p>As for the loss plot, it's Tensorboard.</p>
<p>Not sure if we've written down the scores somewhere… You can check the LB score by yourself though :) Also note the 16-mode model. It may not fit your approach (haven't read that so not sure).</p>
|
Lyft Motion Prediction for Autonomous Vehicles
|
4th place solution: Ensemble with GMM
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lyft Motion Prediction for Autonomous Vehicles
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks <a href="https://www.kaggle.com/YoungseokJoung" target="_blank">@YoungseokJoung</a> !</p>
<p>We have published our code:<br>
<a href="https://github.com/pfnet-research/kaggle-lyft-motion-prediction-4th-place-solution" target="_blank">https://github.com/pfnet-research/kaggle-lyft-motion-prediction-4th-place-solution</a></p>
<p>Thanks! <a href="https://www.kaggle.com/prokaggler" target="_blank">@prokaggler</a> </p>
<h1>What we tried and not worked</h1>
<p>Sorry for the late post, these are some of the items that we tried but not worked.</p>
<h2>Change hyper parameters</h2>
<p>We tried several hyper parameters, especially for rasterizers. But none of them contributed to improve the model's accuracy.</p>
<ul>
<li><p>image size</p>
<ul>
<li>We tried 224x224 & 128x128. The image size=128 training is faster especially because Rasterization becomes faster, and its training accuracy is almost the same until the middle of the training. However, its validation loss is a bit (only about 0.5~1.0) worse than image size = 224.</li></ul></li>
<li><p>pixel_size</p>
<ul>
<li>There are many frames that the car is almost stopping now but starts in the near future. We thought that when the car starts moving, its change in the pixel is very small and CNN cannot detect it when the pixel_size is bit (resolution is rough). We tried to change <code>pixel_size</code> from default 0.5 into 0.25 or 0.15 but the accuracy becomes worse.</li></ul></li>
<li><p>num_history</p>
<ul>
<li>1. Only short history predictor: Several agents have very few past history. So I thought when we train the model with only 0 past frames (i.e., input only current frame), this specific purpose model performs better for predicting the future with only 0 past frames. In the training phase, <strong>we can train this model using the agents with many past frames, by just input only a current frame.</strong> However, this model’s accuracy is worse than the default 10 history input model.</li>
<li>2. Long history predictor: Oppositely, having more past information helps to improve the score? To check that hypothesis, we tried to input longer past history frames by setting <code>history_num_frames=7, 10</code> with <code>history_step_size=2</code> instead of default <code>history_num_frames=10</code> with <code>history_step_size=1</code>. This model’s accuracy was lower than the original model even if we only chose the validation input to have more than 20 history frames.</li></ul></li>
</ul>
<h2>Big, deep models</h2>
<p>We tried <code>resnet101</code> & <code>res152</code> too, but they did not work well.</p>
<h2>Custom Rasterizer</h2>
<p>We tried implementing our own rasterizer to add more rich information to CNN input, but all of them did not work well to improve the accuracy somehow…</p>
<ul>
<li><code>ChannelSemanticRasterizer</code><ul>
<li><code>SemanticRasterizer</code> draws the semantic in RGB space, using 3 channels. We thought this is not always optimal for CNN input and tried to input 6 channels with 1. road, 2. default lane, 3. green signal lane, 4. yellow signal lane, 5. red signal lane, 6. crosswalk.</li></ul></li>
<li><code>TLSemanticRasterizer</code>:<ul>
<li>When we executed EDA, we thought knowing <strong>the red signal length is important</strong>. Because some frames start with the red signal as current, and start in the future when the signal changed to green.<br>
We input a signal length by changing the color value so that CNN can understand how long this signal color already continued (since Host car detected the signal).</li></ul></li>
<li><code>AgentTypeBoxRasterizer</code>:<ul>
<li>There are 4 agent types: CAR, CYCLIST, PEDESTRIAN and UNKNOWN in the original dataset. But UNKNOWN is not drawn in the original <code>BoxRasterizer</code>. Also agent type information is also dropped when drawing boxes.<br>
We tried to draw each agent type in different channels including UNKNOWN, to input more precise information. </li></ul></li>
</ul>
<p><strong>Speed up rasterizer</strong><br>
Use numpy batch operation as much as possible, and replacing implementations with numba jit computations. Even though it becomes faster in single process, its computation speed-up does not contribute so much for multi-process data preparation during training.</p>
<h2>Train with Agent type</h2>
<p>Other than trying the <code>AgentTypeBoxRasterizer</code>, we tried inputting agent type one-hot vector explicitly, but it did not contribute to improve accuracy too.</p>
<h2>Multi-agent prediction model</h2>
<p>The baseline kernel predicts future movement of only target agent. Instead I considered to build a model which predicts all the agent's future movement within the input image.<br>
The first I thought this idea speed-ups the training since it can predict multiple agent at once. However sometimes the host car detects agent with very far place, like 400 pixels far away. So we noticed it is difficult to align the image size to fixed size. And we suspended its further trial.</p>
<h2>Yaw correction</h2>
<p>The below figure shows the biggest error in the validation dataset. The error is extremely high when the <code>yaw</code> in the dataset was actually opposite and the model predicted the opposite way to go.<br>
We worked hard to check if the test dataset contains this kind of case. Indeed there seems to be some frames whose <code>yaw</code> might be opposite, however most of the time the agent is stopping in this case in the test dataset. Even though we fixed the yaw, the LB score was almost unchanged.</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F518134%2Fe51c936752b5cd7bd0689f6ef9faebe9%2Fvalidation_worst_error.png?generation=1606717208803896&alt=media" alt=""><br>
The biggest error in the validation dataset with error=43988.1 !!</p>
<h2>Leak check</h2>
<p>When we checked the dataset carefully, we noticed that the timestamp & the map position actually overlaps within the train/validation/test dataset.<br>
We checked if the test dataset information was leaked from another dataset. But it seems that the timestamp is not aligned in scenes (maybe physically other host car is used to collect data, and timestamp record is not calibrated).</p>
<p>We used local machine :)</p>
<p><a href="https://www.kaggle.com/hengck23" target="_blank">@hengck23</a> <br>
Thanks for your comment.<br>
We used this code, usage is same with sklearn's GMM.</p>
<pre><code>import numba as nb
import numpy as np
from sklearn.mixture import GaussianMixture
# from sklearn.mixture._gaussian_mixture import _estimate_gaussian_parameters
@nb.jit(nb.types.Tuple(
(nb.float64[:], nb.float64[:, :])
)(nb.float64[:, :], nb.float64[:, :]), nopython=True, nogil=True)
def _estimate_gaussian_parameters(X, resp):
nk = resp.sum(axis=0) + 10 * np.finfo(resp.dtype).eps
means = np.dot(np.ascontiguousarray(resp.T), X) / np.ascontiguousarray(np.expand_dims(nk, 1))
return nk, means
class GaussianMixtureIdentity(GaussianMixture):
def _initialize(self, X, resp):
n_samples, _ = X.shape
self.covariances_ = np.zeros(self.n_components)+1.0
self.precisions_cholesky_ = np.zeros(self.n_components)+1.0
weights, means = _estimate_gaussian_parameters(X, resp)
weights /= n_samples
self.weights_ = (weights if self.weights_init is None
else self.weights_init)
self.means_ = means if self.means_init is None else self.means_init
def _m_step(self, X, log_resp):
n_samples, _ = X.shape
self.covariances_ = np.zeros(self.n_components)+1.0
self.precisions_cholesky_ = np.zeros(self.n_components)+1.0
self.weights_, self.means_ = _estimate_gaussian_parameters(X, np.exp(log_resp))
self.weights_ /= n_samples
</code></pre>
<p>Thank you <a href="https://www.kaggle.com/christofhenkel" target="_blank">@christofhenkel</a> for comment. I'm looking forward to see your team's solution.</p>
<p>I saw that your team used stacking. I also wonder if your team applied GMM ensembling, the score has increased further or not!</p>
<p>Yes, the dataset becomes <code>191,177,863</code> -> <code>198,474,478</code>.</p>
<p>I guess <code>min_frame_history=0</code> increases the number, while <code>min_frame_history=10</code> reduces the number.</p>
<p>Thanks for reply <a href="https://www.kaggle.com/louis925" target="_blank">@louis925</a>, yeah I think so too. For considering application, this "what did not work" is more important to consider further why.</p>
<p>Actually "Yaw correction" happened many times, and I guess to correct it we need better accuracy for the previous object detection NN part where I guess this module will decide the yaw direction.<br>
While the pedestrian & cyclist they are more easier to decide direction from real image and indeed there is less mistake for yaw, but car is just "box" shape, determining its direction from image sometimes has mistake.</p>
<p>Thanks, congrats <a href="https://www.kaggle.com/sheriytm" target="_blank">@sheriytm</a> too!</p>
<p>😃</p>
<p>You can find various trial implementations of our rasterizer too: (numba jit tuned version of rasterizer etc)</p>
<ul>
<li><a href="https://github.com/pfnet-research/kaggle-lyft-motion-prediction-4th-place-solution/tree/master/src/lib/rasterization" target="_blank">https://github.com/pfnet-research/kaggle-lyft-motion-prediction-4th-place-solution/tree/master/src/lib/rasterization</a></li>
</ul>
<p>Thanks, please check/try our ensemble code :)</p>
<ul>
<li><a href="https://github.com/pfnet-research/kaggle-lyft-motion-prediction-4th-place-solution/tree/master/src/ensemble" target="_blank">https://github.com/pfnet-research/kaggle-lyft-motion-prediction-4th-place-solution/tree/master/src/ensemble</a></li>
</ul>
<p>Thank you to the organizers and congratulations to all the participants. <br>
Also I would like to thank my team members <a href="https://www.kaggle.com/zaburo" target="_blank">@zaburo</a>, <a href="https://www.kaggle.com/qhapaq49" target="_blank">@qhapaq49</a>, <a href="https://www.kaggle.com/charmq" target="_blank">@charmq</a> for our hard work, I could enjoy the competition!<br>
The LB was really stable in this competition due to the big amount of data, we could work on improving the model without caring about big shake-up.</p>
<p>We have started with my baseline kernel <a href="https://www.kaggle.com/corochann/lyft-training-with-multi-mode-confidence" target="_blank">Lyft: Training with multi-mode confidence</a>.<br>
Below items are substantial changes we made:</p>
<p>[Update 2020/12/9] <strong>We have published our code:</strong></p>
<ul>
<li><a href="https://github.com/pfnet-research/kaggle-lyft-motion-prediction-4th-place-solution" target="_blank">https://github.com/pfnet-research/kaggle-lyft-motion-prediction-4th-place-solution</a></li>
</ul>
<h1>Short Summary</h1>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F518134%2Fa27c649533aca3f12e23255ed2295440%2Flyft_4th_place_solution.png?generation=1606414075335190&alt=media" alt=""></p>
<p>Published baseline training pipeline was indeed already very strong. <br>
Just modifying</p>
<ol>
<li>train_full.zarr</li>
<li>l5kit==1.1.0</li>
<li>Set min_history=0, min_future=10 in AgentDataset</li>
<li>Cosine annealing for LR decrease until 0</li>
</ol>
<p>with training 1 epoch was already enough to win the prize.</p>
<h1>1. Use train_full.zarr data</h1>
<p>Bigger data is almost always better for deep learning model training. We used <a href="https://www.kaggle.com/philculliton/lyft-full-training-set" target="_blank">Lyft Full Training Set</a>.</p>
<p>However its size is really large, containing 191M data for AgentDataset.</p>
<p>Practically we need this modifications in order to train this big dataset in real time:</p>
<h2>Distributed training</h2>
<p>We implemented distributed training using <code>torch.distributed</code>.<br>
It usually takes about 5 days to finish 1 epoch when we use 8GPUs.</p>
<h2>Caching some arrays into zarr beforehand to reduce on-memory usage in AgentDataset</h2>
<p>The problem arises when we run distributed training and <code>DataLoader</code> with setting <code>num_workers</code> for multi-process data loading.</p>
<p>In the distributed training, 8 processes run in parallel and each process invokes <code>num_workers</code> subprocess. Therefore 8 * num_workers subprocess is launched and <code>AgentDataset</code> data is copied in each subprocess.<br>
Then Out Of Memory error occurs because <code>AgentDataset</code> internally holds <code>cumulative_sizes</code> attribute whose size is very big (<a href="https://github.com/lyft/l5kit/blob/1ea2f8cecfe7ad974419bf5c8519ab3a21300119/l5kit/l5kit/dataset/agent.py#L62" target="_blank">code</a>).</p>
<p>Instead, we pre-calculated <code>track_id, scene_index, state_index</code> and saved as the zarr format. So that we can load each data from disk, and reduce on-memory usage.</p>
<p>The Public Score was around <strong>25.742</strong> <a href="https://www.kaggle.com/corochann/lyft-prediction-with-multi-mode-confidence" target="_blank">kernel</a> at this stage.</p>
<h1>2. Use l5kit==1.1.0</h1>
<p>As mentioned in the discussion <a href="https://www.kaggle.com/c/lyft-motion-prediction-autonomous-vehicles/discussion/186492" target="_blank">We did it all wrong</a>, image is rotated while the target value is not rotated in the previous version of l5kit==1.0.6 during the beginning of the competition.<br>
We updated l5kit version to 1.1.0 once it is released, which fixes this behavior.</p>
<p>The Public LB score was jumped to <strong>15.874</strong> with this update.</p>
<h1>3. Set min_history=0, min_future=10</h1>
<p>As written in the “Validation Strategy” section, validation&test data is made by <code>create_chopped_dataset</code> method. We noticed that this validation/test data consists of the data with A. always contains more than 10 future frames, and B sometimes it does not contain any history frame.</p>
<p>To align the training <code>AgentDataset</code> to this test dataset behavior, we can set <strong><code>min_frame_history=0</code> and <code>min_frame_future=10</code></strong>.<br>
I think <strong>this modification is the most important part to notice in this competition</strong>.<br>
You need a courage to intentionally ignore l5kit library warning ;)(<a href="https://github.com/lyft/l5kit/blob/1ea2f8cecfe7ad974419bf5c8519ab3a21300119/l5kit/l5kit/dataset/agent.py#L15-L17" target="_blank">code</a>).</p>
<p>It’s very effective, the score jumped to <strong>13.059</strong>.</p>
<h1>4. Training: with cosine annealing</h1>
<p>Model: We trained & used following models for final ensemble</p>
<ul>
<li>Resnet18</li>
<li>Resnet50</li>
<li>SEResNeXt50</li>
<li>ecaresnet18</li>
</ul>
<p>However resnet18 baseline was strong, and enough to win the prize.</p>
<p>Image size: tried (128, 128) and (224, 224). image size of 128 training proceeds faster, but image size 224 final score was slightly better.</p>
<p>Optimizer: Adam with Cosine annealing<br>
Cosine annealing was better than Exponential decay. I think decreasing the learning rate until very close to 0 is important for final tuning.</p>
<p>Batch size: 12 * 8 process = 96</p>
<p>We just trained only 1 epoch to train full data. We did not downsample any of the data.</p>
<p>Public LB score for single resnet18 model is <strong>11.341</strong>.</p>
<h1>Augmentation</h1>
<h2>Image augmentation</h2>
<p>Many of the augmentation used in natural images is not appropriate for this competition task, (for example flip augmentation flips the target value as well and not realistic since right-lane, left-lane will change). We tried</p>
<ul>
<li>Cutout</li>
<li>Blur</li>
<li>Downscale<br>
using <a href="https://github.com/albumentations-team/albumentations" target="_blank">albumentations</a> library.</li>
</ul>
<h2>Rasterizer-level augmentation</h2>
<p>What is different from normal image prediction is that the image is drawn by rasterizer. We can also consider applying augmentation during rasterization.</p>
<p>I tried following augmentation by modifying <code>BoxRasterizer</code> (<a href="https://github.com/lyft/l5kit/blob/1ea2f8cecfe7ad974419bf5c8519ab3a21300119/l5kit/l5kit/rasterization/box_rasterizer.py" target="_blank">code</a>).</p>
<ul>
<li>Drop agent randomly<ul>
<li>I assumed that the target agent’s movement does not change so much when the other agent far from the target agent exists or not. So we randomly skip drawing some of the agent boxes.</li></ul></li>
<li>Scale extent size randomly<ul>
<li>Even when the other agent size changes a bit, I assume that the target agent’s behavior does not change. So we scaled extent size from factor 0.9~1.1</li></ul></li>
</ul>
<p>I thought rasterizer-level augmentation was an interesting idea for this competition task. However we could not see big score improvement actually. Maybe the training dataset size is already big enough and its effect is not so big.</p>
<p>By <strong>only adding cutout augmentation</strong>, we achieved to get public LB score of <strong>10.846</strong>, already enough to win the prize. </p>
<h1>Validation Strategy</h1>
<p>As discussed in <a href="https://www.kaggle.com/c/lyft-motion-prediction-autonomous-vehicles/discussion/188695" target="_blank">Validation vs LB score</a>, we can run very stable validation using a chopped dataset.<br>
However, it removes ground truth data, format is different from training AgentDataset and difficult to validate during training phase.</p>
<p>What we want is <code>agents_mask_orig_bool</code> (<a href="https://github.com/lyft/l5kit/blob/1ea2f8cecfe7ad974419bf5c8519ab3a21300119/l5kit/l5kit/evaluation/chop_dataset.py#L68" target="_blank">code</a>).<br>
We saved this <code>agents_mask_orig_bool</code> and set it to the <code>agent_mask</code> argument of <code>AgentDataset</code>.<br>
Then we could run validation during training.</p>
<p>We sub-sampled 10000 dataset for fast validation during training, but it differs a lot from the score using a total 190327 validation dataset.<br>
At the end phase of the competition, we validated the trained model using a full validation dataset.</p>
<h1>Ensemble: sample trajectory and GMM fitting</h1>
<p>To improve the score further, how to ensemble is the key question in this task.<br>
No golden method is suggested in <a href="https://www.kaggle.com/c/lyft-motion-prediction-autonomous-vehicles/discussion/180931" target="_blank">the discussion</a> and we came up with an idea to adopt the <strong>Gaussian Mixture Model</strong>.</p>
<p>We can sample trajectory and fit the sampled points by GMM with the 3 components.<br>
We started from the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.mixture.GaussianMixture.html" target="_blank">sklearn implementation</a>.<br>
Setting <code>n_components=3</code> and <code>covariance_type=”spherical”</code> achieved the good score.<br>
However sigma is fixed to 1 in this competition <a href="https://www.kaggle.com/c/lyft-motion-prediction-autonomous-vehicles/overview/evaluation" target="_blank">metric</a>, so we also tried implementing own GMM model with fixing covariance to be 1.</p>
<p>Ensemble by GMM was really effective, we finally achieved <strong>public LB score 10.272/private LB score 9.475</strong></p>
<p>Thus, the ensemble pushed the public LB score from 10.846 to 10.272. But it does not change the final rank this time ;)</p>
<p>By the way, I saw other participants used k-means clustering for ensembling coords. <br>
I think the behavior is quite similar with using GMM, since it calls k-means clustering in the initialization of EM algorithm.</p>
<h1>What we tried and not worked</h1>
<p>We noticed Baseline model & l5kit default rasterizer was already very strong in this competition.<br>
We really tried a lot, but many of the attempts failed to improve the scores. I’ll write in the reply section (since it’s already very long).</p>
<p>Thank you and congrats to you too! <a href="https://www.kaggle.com/zaharch" target="_blank">@zaharch</a> </p>
<p>We used 8 V100 GPUs for single model training with about 32 cpu cores.<br>
I think disk IO and rasterization process was the bottleneck compared to the normal image training.</p>
<p>Thank you! Glad to know that :) <a href="https://www.kaggle.com/piantic" target="_blank">@piantic</a> </p>
|
Lyft Motion Prediction for Autonomous Vehicles
|
6th place: Micro-inputs, Lots of Data + Distance Order to Ensemble!
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lyft Motion Prediction for Autonomous Vehicles
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks! Same to you!</p>
<p>No, I never trained train_full for a complete epoch, I think I'd be here until Christmas if I did! <a href="https://www.kaggle.com/rytisva88" target="_blank">@rytisva88</a> had been training on a random shuffle of train_full before switching to the chopped version, so he will have a better gauge on what the impact was. <a href="https://www.kaggle.com/sheriytm" target="_blank">@sheriytm</a> also went from using train.zarr to a chop of train_full.zarr so will have an idea of how much that was worth.</p>
<p>We ended up reusing chopped datasets (i.e. showing the same sample multiple times). It would have been better if we didn't, but we were running out of time and were resource constrained. </p>
<p>If I were starting over I would have done it differently: rather than creating complete chops I would just store off the indices in train_full.zarr that those chops refer to, thereby allowing us to create sequences of diverse samples without having to show samples multiple times or run out of resources. <a href="https://www.kaggle.com/rytisva88" target="_blank">@rytisva88</a> managed resources better and he was able to use 20 chopped datasets (but could have gone higher). I was stuck using 16.</p>
<p>Yes, I kept the rasterization throughout as I was so often playing around with different configs that it didn't make sense to freeze it. Also, I wasn't sure whether I'd have the disk space… </p>
<p>The top score was an ensemble of the two best models (slightly lower score was an ensemble of four). For that one, 11.15 + 10.52 -> 10.32</p>
<p>I did try kmeans early on, but it wasn't working for me, perhaps because of how I implemented it: if there were three models, say, I was clustering 9 modes into three clusters. Then taking the max conf mode for each cluster or averaging within each cluster (I tried both). But obviously had something wrong somewhere…</p>
<p>3x1080ti. 128GB RAM, 10 cores. Could have done with more!!</p>
<p>First up: great competition! The data was about as stable as I’ve ever encountered on Kaggle – kudos to the organisers. Congratulations to all of the winners - and to everyone who worked hard and completed the competition. </p>
<p>It was a pleasure to work with <a href="https://www.kaggle.com/rytisva88" target="_blank">@rytisva88</a> and <a href="https://www.kaggle.com/sheriytm" target="_blank">@sheriytm</a> on this – thank you both! </p>
<p>I’m sure that my teammates will post separately, so I’ll stick with some observations from my own workflow here. Very interested to hear how everyone else approached the problem, as there was a lot of scope for different approaches! </p>
<p>I ended up with two small input sizes in the interest of speed: 128 + 5 channels, 196 + 5 channels. </p>
<ul>
<li>The 128+5 model got to 11.9 after 68.8M samples. </li>
<li>The 196+5 model reached 11.15 after 71.4M samples. </li>
</ul>
<p>Reading others’ comments and solutions it seems that some of the items that I thought were key to doing well were not, in fact! I’m sure cherry picking ideas that worked from different teams could lead to something very interesting.</p>
<p><strong>Data, data, data:</strong></p>
<p>There seemed to be one major key to success in this competition: how much data you could access, and how you sampled it. </p>
<p>Early on it became clear that grouping scenes while training gave a significant uplift: when a single agent from each scene was selected before moving to the next iteration, scores improved.</p>
<p>Taking this idea and following it through to train_full.zarr gave the next breakthrough: training on a chopped version of train_full.zarr yielded further improvements. </p>
<p>The next jump in performance came from training on multiple chops of train_full.zarr. (You can adapt the l5kit code to create lightweight chops comprising just a small number of historic frames. This allowed for big savings on RAM/disk space.)</p>
<p>We debated why there were such performance gains from training using chopped versions of train_full.zarr rather than randomly accessing indices. From early experiments it seemed like ensuring scene diversity was important: in the same way that we might enforce class balance while training, enforcing scene diversity (and perhaps more fundamentally, driver diversity?) seemed to matter. </p>
<p><strong>Raster size v data coverage tradeoff:</strong></p>
<p>Covering as much data as possible mattered, and training for as long as possible mattered. A single chop of train_full.zarr (approx 825K samples) could be shown to the model 12 times before it stopped learning. Obviously if you could show the model different samples you would do a lot better! But this seemed to be the hard limit.</p>
<p>Keeping the model as small as possible meant it could iterate through these samples much more quickly. The inputs for the models that I ended up using were raster size 128 and 196, history_num_frames = 5, condensed into five input channels: </p>
<p>sum(agent_history), agent_current, sum(ego_history), ego_current, sum(semantic_map)</p>
<p>I was originally using Resnet18, but then switched to Resnest50 on <a href="https://www.kaggle.com/rytisva88" target="_blank">@rytisva88</a>'s recommendation and it gave an improvement of about -1 in nll. (Incidentally, <a href="https://www.kaggle.com/rytisva88" target="_blank">@rytisva88</a> had the best performing single model in our group).</p>
<p>Summing the semantic map meant that red and green traffic signals were treated the same. This seemed to work fine, surprisingly. Perhaps because only yellow gave additional information not already contained in the traffic movement.</p>
<p><strong>Acceleration:</strong></p>
<p>Eyeballing the predicted trajectories, it became clear that the models were ultimately making a bet on acceleration: typically, modes 0, 1, 2 represented trajectories arising from different agent speeds. </p>
<p>Once it became clear that this was key it was possible to look at sampling the data such that we balanced these cases. </p>
<p>A scene containing lots of agents was indicative of traffic. Gridlocked traffic obviously does not move much and leads to a lot of duplication in inputs. The models implemented a sampling scheme whereby scenes with a large number of agents were undersampled. The sampling proportion was: min(1, 7/agent_count). Thus, scenes containing 14 agents had 50% of those agents selected for each training iteration, etc.</p>
<p><strong>Ensembling:</strong></p>
<p>This was initially a tricky one: averaging models based on confidence values didn’t work. However, when the importance of acceleration was taken into account, the route to ensembling made sense: order the model modes by distance covered, then average the results. When this was implemented all models could be ensembled very quickly, with positive results. We also looked at incorporating curvature here, but it didn’t make any difference: distance was the key.</p>
<p>The final ensemble optimized weights on the validation set. The weighting scheme incorporated distance and confidence values. </p>
<p><strong>Code:</strong></p>
<p>Code for contribution to our team solution can be found <a href="https://github.com/ciararogerson/Kaggle_Lyft" target="_blank">here</a></p>
<p><strong>Ideas that didn’t work: many! Here are a few…</strong></p>
<p><em>Traffic lights:</em></p>
<p>I couldn’t get additional traffic light information to add anything: many different angles were tried! The most promising was probably traffic light persistence: we included an additional channel in the model where instead of traffic light lane lines, we drew lines containing the number of frames since the traffic light had turned to its current colour (up to a maximum of 100). Ultimately this didn’t add anything.</p>
<p><em>Day/hour:</em></p>
<p>Adding channels for day/hour values proved better than concatenating them directly before the dense layers of the model, but it still didn’t help much.</p>
<p><em>Interpolation:</em></p>
<p>Having the penultimate model layer output 25 sets of (x, y) points, followed by an interpolation between these points to make the final 50 point trajectory did not work.</p>
<p><em>Weighted loss function:</em></p>
<p>Given the importance of capturing acceleration, we tried a version of the loss function that weighted the last 10 points of the trajectory equal to the first 40. This didn’t help.</p>
|
Lyft Motion Prediction for Autonomous Vehicles
|
7th place solution - Peter & Beluga
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lyft Motion Prediction for Autonomous Vehicles
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h4>Acknowledgements</h4>
<p>Thanks for the organizers for this tough but certainly interesting challenge.<br>
Special thanks for Vladimir Iglovikov and Luca Bergamini for their active forum contribution during the competition.</p>
<p>Hats off to my team mate <a href="https://www.kaggle.com/pestipeti" target="_blank">@pestipeti</a> by the time I joined him he already had optimized the hell out of l5kit and had a solid training framework.<br>
Then he managed to boost the training speed even further by <a href="https://www.kaggle.com/c/lyft-motion-prediction-autonomous-vehicles/discussion/199583" target="_blank">rasterizing the images on GPU</a>.<br>
With all those improvements we were able to run dozens of experiments with different config parameters and slightly modified encodings during the last months.</p>
<h4>Back to the future</h4>
<p>We noticed that the training dataset and chopped validation set had slightly different feature distributions. After some digging we found that the chopped datasets (valid, test) always had availability for at least 10 future frames. It was quite the opposite than the default <code>AgentDataset</code> settings so we used that for training too. </p>
<pre><code>AgentDataset(
cfg, dataset_zarr, gpu_rasterizer, agents_mask=dataset_mask,
min_frame_history=1, min_frame_future=10
)
</code></pre>
<p>It helped both in terms of validation consistency and final score.</p>
<h4>Poor Man's Ensembling</h4>
<p>We did not hope that blending or any simple heuristic would help to combine different models. (I read clever tricks though and I hear that stacking works too…)</p>
<p>The speed of the agent matters a lot and we saw that in our experiments. Intuitively for slower objects we used smaller raster size but more history.<br>
Our final and best submission used three models based on speed (Total distance in the last 1 sec) </p>
<ul>
<li>[0-2] Slow model 320x220 with 3 sec history (compressed by 1.5 s) trained for 7+ days on slower examples</li>
<li>[2-5] Medium model 320x220 with 3 sec history (compressed by 1.5 s) trained for 5+ days [1.5-12]</li>
<li>[5+] Fast model 480x320 with 1 sec history on separate channels trained for 9+ days on [2+]</li>
</ul>
<h4>Things that did not work</h4>
<ul>
<li>We tried to use additional meta data (speed, acceleration, position, hour of the day, day of the week etc.) but it did not really help.</li>
<li>We did not use satellite images at all. We noticed that they could have additional info (especially for pedestrians or cyclists) but it would be too slow.</li>
<li>Different backbone. We tried a few other networks but mostly used Effnet-B2.</li>
</ul>
|
Lyft Motion Prediction for Autonomous Vehicles
|
9th place solution
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lyft Motion Prediction for Autonomous Vehicles
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Very good description, thanks. And interesting insights. Regarding better results with "my" loss in comparison to the original true trajectories, it may be because the original loss is harder to learn. For the original loss one still needs to learn how to separate into 3 modes smartly. With "my" loss it is already separated into good candidates, the search field is much smaller.</p>
<p>Actually, I think I will not share the code this time. It requires cleaning up, and I don't see too much value in it anyway. </p>
<p>Thanks for that description, very interesting. Is it possible that you share your implementation of the Set Transformer? I want to compare them too. And also, what did you mean by "than to minimize the loss to known GT trajectories".</p>
<p>Not really, just decide on a per-experiment basis what is appropriate.</p>
<p>Nothing special, I have careful logging into csv files, with versioning of each run. Just an incremental integer, I got to version 81 at the end. For each version I write what it is about, what scores it reaches and what is my conclusion. Then move on to the next version. And I always try to make one change at a time.</p>
<p>Thanks, fergusoci, and congratulations with your great result too. To be honest, posting the directionless trajectories topic was a safe bet. The organizers had already known the issue and worked on a fix. And it was too big of an issue to stay secret for long. Maybe maximum another week and someone else would have reported it. And additionally, I was sure that the top teams would definitely do it correctly, so mot much of an advantage to keep it secret. </p>
<p>First, it was a well organized competition. The engagement from <a href="https://www.kaggle.com/lucabergamini" target="_blank">@lucabergamini</a> and <a href="https://www.kaggle.com/iglovikov" target="_blank">@iglovikov</a> on the forum is exemplarily, and one can see how <a href="https://www.kaggle.com/iglovikov" target="_blank">@iglovikov</a> corrects in this competition problems that he himself has probably experienced when he was a participant, well done. Second, I think Lyft investing and organizing Kaggle competitions is not something to be taken for granted. They give the data and lots of their time, but also expose their proprietary l5kit library to the competitors. I hope it pays off to a degree with the ideas that kagglers generate, but in any case thanks to Lyft for doing this, please continue. </p>
<p>My solution at the end is surprisingly simple, because no fancy ideas have worked well. Yet, there are several things that helped me, I describe everything below. For me, it is once again a lesson to stick to the solid basics. I remember when I started 3 months ago I was excited to try GANs, as it <a href="http://papers.neurips.cc/paper/8308-social-bigat-multimodal-trajectory-forecasting-using-bicycle-gan-and-graph-attention-networks.pdf" target="_blank">seemed to be the state of the art</a>. I couldn't finish further away from it.</p>
<h1>Data</h1>
<h3>Samples selection</h3>
<p>The dataset parameters are <code>min_history_steps = 0</code> and <code>min_future_steps = 10</code>, which is standard and what was probably used to chop the test data. And I added another layer of filtering, - based on the state index. Stated index is a frame's count inside its scene, ranging from 0 to 250. In test, state index is always 99. If one decides to train on a chopped dataset he basically constraints himself to state index 99. But this cuts too much data, so I built a mask similar to the existing mask and require <code>min_state_history = 30</code> and <code>min_state_future = 50</code>. I believe this change improved my scores. Without it I would get samples with state index starting from 0, which is not good.</p>
<h3>zarr files</h3>
<p>From the beginning I used full train zarr, and two weeks before the end I added the chopped validation and the test zarrs. That last part may sound surprising at first. Basically we have 100 frames in the test and validation, and with my states index filtering I look only at frames 30 to 50 to train on. It is a legitimate data for the training, and my motivation was to expose the models to any specifics of the test dataset, like a raining day. After all the filtering I had that much data for the training:</p>
<ul>
<li>140M full train</li>
<li>1.4M test, frames 30-50</li>
<li>1.9M validation, frames 30-50</li>
</ul>
<h3>Rasterization</h3>
<ul>
<li>12 frames <code>[0,1,2,3,4,5,8,10,13,16,20,30]</code> into the past</li>
<li>3 channels semantic map</li>
<li>another 3 channels of semantic map for history frame 30, gives traffic light 3s from the past</li>
<li>future frame, when applicable (which is about <code>87%</code> of time). <a href="https://www.kaggle.com/c/lyft-motion-prediction-autonomous-vehicles/discussion/199498" target="_blank">Discussed here</a>.</li>
<li>AV vehicle is marked with a black dot (see the above link for an example)</li>
<li>raster size <code>[256,192]</code>, all the rest of the parameters are defaults</li>
</ul>
<p>All of the above modification have helped to improve the score. </p>
<h3>Sampling</h3>
<p>We had a lot of training data so I had a luxury to make sure that I did not attend the same sample more than once during the whole training. Basically I generated the order before the training and picked indices from it sequentially. </p>
<h1>Model</h1>
<p>The ensemble of 3 models, from <a href="https://rwightman.github.io/pytorch-image-models/results/" target="_blank">timm package</a></p>
<table>
<thead>
<tr>
<th>Model</th>
<th>train</th>
<th>validation</th>
<th>LB public</th>
</tr>
</thead>
<tbody>
<tr>
<td>mixnet_m, 3 traj</td>
<td>12.10</td>
<td>12.62</td>
<td>12.976</td>
</tr>
<tr>
<td>mixnet_l, 3 traj</td>
<td>11.48</td>
<td>12.02</td>
<td>12.285</td>
</tr>
<tr>
<td>mixnet_l, 6 traj</td>
<td>6.88</td>
<td>7.10</td>
<td></td>
</tr>
<tr>
<td>ensembled, 3 traj</td>
<td></td>
<td>11.61</td>
<td>11.788</td>
</tr>
</tbody>
</table>
<p>The approach to the model is straightforward 3 or 6 trajectories prediction, I initially got the idea from <a href="https://www.kaggle.com/corochann/lyft-training-with-multi-mode-confidence" target="_blank">this kernel</a>, and it stuck. </p>
<h3>Training</h3>
<ul>
<li>the best model <code>mixnet_l</code> was trained for <code>215 (epochs) x 64 (batch size) x 2500 (iterations)=34.4M</code> samples</li>
<li>Adam optimizer</li>
<li>learning rate <code>4e-4</code> decaying to <code>1e-7</code>. Most of the training on <code>1e-4</code> - <code>2e-4</code></li>
<li>Auxiliary losses - also predicting 50 future velocities and yaws. It helped to converge faster, but not sure if it improved the accuracy. </li>
</ul>
<h1>Ensembling</h1>
<p>I am proud of the ensembling procedure that I developed, however I have not tested it against the alternatives, and the benefit is only <code>0.5</code>. It seems like some people report good results with stacking, very interesting what is better. </p>
<p>In my approach I gave weights <code>[0.8,0.3,0.5]</code> to my 3 models, which multiplied their own confidences. As a result I had 12 (3+3+6) trajectories with some probabilities assigned to them. How to ensemble those? I want to optimize the negative log likelihood metric and get three trajectories with confidences as output. If I assume that each of the 12 trajectories is a ground truth with its probability, then I have a well-defined optimization problem at hand. Still, it is a difficult non-convex optimization problem. By writing down the expression, requesting that the gradient equals to zero (local minimum requirement), I got to a fixed point formulation. Fixed point is an expression of form <code>x = f(x)</code>. From this by making several iterations I can get to an optimum. </p>
<p>There are a couple of questions. First, does it always converge? In practice, it does always converge in 2-20 iterations. In theory it needs to be proven, I think it can be proven. Second, does it converge to a global minimum and not a local one? Given the problem structure I believe it is a global optimum, but maybe it is a global optimum only almost always. Third, does my original assumption about 12 ground truth trajectories with probabilities create a problem? It seems to me that it is a theoretically sounds approach, but it is a long discussion in itself.</p>
<p>The advantages of the approach is that I run it in batches on GPU, very fast. The results are stable, and it accepts any number of input trajectories. Specifically, I trained the 6 trajectory model to cover a wider range of possibilities, knowing that I can ensemble them effectively. </p>
<h1>Things that did not work, all in one big pile</h1>
<ul>
<li>weight decay, AdamP, AdamW, one-cycle learning rate policy</li>
<li>freezing batch normalization layers at the last epochs of training</li>
<li>changing agents box colors continuously based on their velocity. Bright - fast, dim - slow.</li>
<li>GAN: train a model to differentiate between real and generated trajectories, with gradient reverse layer to propagate the gradient</li>
<li>PCA: selecting 25 PCA components for 100 dimensional vector of the possible futures and learning to predict their coefficients</li>
<li>predicting probability maps (like a segmentation task) and clustering those into 3 trajectories</li>
<li>adding velocity, acceleration, yaws to the last layer of the network</li>
<li>predicting trajectory as a difference above constant speed trajectory</li>
<li>rasterizing output of a model and feeding it to a second level CNN model which outputs small corrections</li>
<li>bigger raster sizes</li>
<li>predicting heading and velocity instead of <code>x</code> and <code>y</code></li>
<li>adding 1-2 fully connected layers on top of the model</li>
<li>learning a "specialized" model, - one output trajectory for fast modes, one for turns etc.</li>
<li>augmentations: random cutout of semantic map, removing random agents</li>
<li>resnet18, resnet50, mobilenetv3_large_100, densenet121</li>
<li>adding constant speed and constant acceleration models to the ensembling with low weights</li>
<li>smoothing final trajectories with B-splines gave indecently small improvement</li>
</ul>
<p>Wow, I tried a lot of stuff. </p>
<h1>Finally</h1>
<p>Congratulations to the winners! It was a great competition, truly unique, challenging and rewarding.</p>
<p>And with that I am happy to become Kaggle competitions grandmaster, number 197. Thank you Kaggle and kagglers for that journey!</p>
<p>Congrats on getting your silver medal</p>
|
Lyft Motion Prediction for Autonomous Vehicles
|
Things I have tried and my final solution
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lyft Motion Prediction for Autonomous Vehicles
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>iter training_loss (avg) eval_loss<br>
10000 23.5 27.526<br>
20000 20.01 23.999<br>
30000 16.69 20.397<br>
40000 17.12 18.814<br>
50000 15.25 17.781<br>
60000 13.1 15.989<br>
70000 13.93 15.538<br>
80000 14.29 15.311<br>
90000 12.74 15.17<br>
100000 12.38 14.593<br>
110000 12.54 14.021<br>
120000 11.53 13.705<br>
130000 12.41 13.868<br>
140000 11.81 13.485<br>
150000 10.79 13.321<br>
160000 10.92 12.983<br>
170000 10.81 12.987<br>
180000 10.98 13.04<br>
190000 11.83 12.893<br>
200000 10.94 12.806<br>
210000 10.7 12.63<br>
220000 10.48 12.666<br>
230000 10.6 12.527<br>
240000 No data, the machine shut down for no reason 😂 <br>
250000 10.43 12.555<br>
260000 10.46 12.409<br>
270000 10.69 12.426<br>
280000 10.35 12.376<br>
290000 10.55 12.347<br>
300000 9.92 12.342<br>
310000 11.07 12.314<br>
320000 10.55 12.3<br>
330000 9.94 12.317<br>
here I started the second round just before the competition deadline, restarted from lr of 0.00001 (drop by half every 20000 steps)<br>
340000 10.67 12.465<br>
350000 11.33 12.385<br>
360000 10.1 12.352<br>
370000 10.12 12.295<br>
380000 10.83 12.269<br>
390000 10.29 12.232<br>
during the final steps I checkpointed every 3000 steps<br>
393000 9.98 12.2<br>
396000 10.38 12.21<br>
399000 10.5 12.189<br>
402000 10.66 12.156<br>
405000 10.25 12.241<br>
408000 10.72 12.168</p>
<p>Thanks for your kind words <a href="https://www.kaggle.com/indswetrust" target="_blank">@indswetrust</a> 😂. The only reason I could hold out that long was just because I was observing steadly decreasing loss every day, so there is no reason to stop.</p>
<p>Congratulations to all the winners and thank the host for this very interesting competition. I have to admit that I did not expect a medal at all at the beginning. At some point I almost gave up, as the training was painfully slow, and I just could not get a reasonable score. This result gives me great motivation to keep trying in the future.</p>
<p>Forgive me if my terminology does not make sense. Any feedback would be greatly appreciated. </p>
<p>To my understanding, this is not a problem of finding three most likely future routes, which is equivalent to finding the one most likely route, as the second most likely route will always be the most likely route shifted by one nanometre. Instead, this is a problem of finding three routes that could best represent the probability distribution. Ideally, we want to include the less likely, but nonetheless typical routes. The most damage to our score probably will be caused by those less likely but very different routes. Therefore, we want diversity in our predictions, and simple ensemble might not work. </p>
<p>My work is based on the model shared by <a href="https://www.kaggle.com/corochann" target="_blank">@corochann</a> <a href="https://www.kaggle.com/corochann/lyft-training-with-multi-mode-confidence" target="_blank">here</a>. While this simple approach to achieve multi-mode prediction is surprisingly effective, there is one thing that does not make sense to me, and I have been fighting with this problem most of the time: </p>
<p>At every training step, the coordinates of all three predictions are all pulled towards the ground truth. The confidence of the prediction that is most close to the ground truth is increased, while the confidences for the other two predictions are decreased. Therefore, for the other two predictions that are relatively further from the ground truth, we are decreasing their confidence values (meaning now we think they are less likely) but pushing their coordinates to the ground truth (meaning making them more likely). Although at the early training stage this should not be such a big problem and the model is able to converge, I just cannot believe it can converge to an optimal point. <br>
Other models such as classification models or NLP models would not have this problem as the target possibilities are fixed and finite. Here we are basically assigning confidence values to moving targets. </p>
<p>I thought about several solutions: </p>
<ul>
<li>I constructed a “diversity” factor in the loss function. It is basically the average distance between three predictions. By adding this to the loss I was hoping I could gently push three predictions away from each other, reduce the effect of three predictions being pulled together. However, my experiments were of no success. The model either totally ignored this factor or used this factor as the only way to gain lower loss. I did not try many times because every experiment took too long. </li>
<li>Make the coordinate space discrete and finite and assign a confidence value to every possible point in this space at each step. Then generate randomly many possible future routes. Finally do a k-means clustering to cluster the routes into three groups and take the centre of each group as the final prediction. I did not even finish the implementation of this idea as the computer power needed would be out of my reach. </li>
<li>Very large batch size. It was until very late into the competition I suddenly realized that maybe increasing the batch size could mitigate (certainly not resolve) this problem. By letting the model see as many future possibilities as possible at each step, the model might learn to maintain the diversity of its three predictio<a href="url" target="_blank"></a>ns. It indeed worked, although to be honest I am not sure it was only because of the problem I mentioned above. </li>
</ul>
<p>So, my final solution might seem surprisingly simple to most people. I just used the good old Resnet18, a very small image setting of 150x150 with only 5 history frames, which enabled me to fit in a batch of 512 samples into my 8G VRAM. The optimizer is again good old Adam, with a learning rate starting from 0.0001 and reduce by half every 50000 steps. I trained on the full dataset, not because I think I need so much data, but to mitigate the problem of overlapping samples as discussed <a href="https://www.kaggle.com/c/lyft-motion-prediction-autonomous-vehicles/discussion/185762" target="_blank">here</a>. </p>
<p>I trained 400k steps, which intermittently took me more than 15 days!!! After this, my computer and I were so exhausted, so we did not try other models or optimizers. </p>
<p>(I tried accumulating gradients to increase the effect batch size but again the training was too slow, and the early result was not fantastic, possibly because of the incompatibility with Batch Normalization.) </p>
<p>I guess, if we could make the batch size even bigger, and image size a little larger, train longer, or maybe use a more sophisticated model, there is potential to further improve the score significantly. </p>
<p>By the way, I have never really solved the problem of deviation between my training loss and validation loss. After removing some problematic parts of my model and setting the min future and history frames in alignment with the validation dataset, the problem was only partly solved. My training loss has reached below 10 but validation loss was never below 12.10. This is not too bad, but I know some of you get much better alignment. How did you guys get the scores aligned? </p>
<p>That was my theory, and it did help, but to be honest I am not sure if that is the only explanation.</p>
|
Lyft Motion Prediction for Autonomous Vehicles
|
[Summary] 42nd place - What I did briefly, Single Model
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lyft Motion Prediction for Autonomous Vehicles
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>please, see 'linear schedule with warmup' haha <a href="https://www.kaggle.com/kramadhari" target="_blank">@kramadhari</a> </p>
<p>I used 256 batch size for train. :)<br>
<a href="https://www.kaggle.com/louis925" target="_blank">@louis925</a> </p>
<p>I just trained 100,000 steps. Maybe I trained model more. lb score is much higher I think</p>
<h1>Intro</h1>
<p>I joined this competition late. It was difficult to try many things.<br>
So, I tried a few things.<br>
(Maybe my solution is too simple. :) )</p>
<h1>First Step</h1>
<p>My first goal was to be in the top 100.<br>
I used Resnet18 and train_full.zarr that have 224 raster_size.</p>
<p>I got <strong>20.56</strong> lb score after about <code>80,000</code> steps.</p>
<h1>Second Step - Switch to Resnet34</h1>
<p>I got <strong>19.23</strong> after <code>25,000</code> steps. The performance has been greatly improved.<br>
So, I trained more steps and finally got 15.080.</p>
<p>Ensemble using public kernel's way didn't work for me.<br>
And ensemble using a simple average way with same model helped public and private lb.<br>
(But I didn't have many models. So, I used basic one and weights averaged model i.e. polyak.)</p>
<ul>
<li>I got public lb score of <strong>14.91</strong> </li>
</ul>
<h1>Third Step - Switch to Resnet50</h1>
<p>2 days ago I switched my baseline model to resnet50.<br>
When I trained resnet50, I found the interesting part between valid score and public lb.</p>
<p>After <code>50,000</code> steps, public lb was <strong>19.132</strong> that it is bad compared to resnet34. But valid score is a pretty good.</p>
<ul>
<li><strong>12.504</strong></li>
</ul>
<p>I checked resnet34 and got a little bad valid score.</p>
<ul>
<li><strong>16.66</strong></li>
</ul>
<p>And also I observed mean loss when I trained resnet50.<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F3492127%2F33dd4f76a9b3e7f7a1d29a9f859e80fb%2F1.png?generation=1606395471230692&alt=media" alt=""><br>
[<code>Left</code>: When <code>57,000</code> steps - 19.194 loss, <code>Right</code>: <code>60,000</code> steps - 19.089 loss]</p>
<p>In that points, lb scores are:<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F3492127%2Fe307542c1bcee60540d08583a092e717%2F2.png?generation=1606396024722504&alt=media" alt=""></p>
<p>I just trained resnet50 after <code>100,000</code> steps and got public lb score <strong>16.076</strong>.<br>
(I have no time for training. haha)</p>
<h1>Final</h1>
<p>I selected resnet34 and resnet50.<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F3492127%2Fcf29ed6aadd3b67951817754a9691fbe%2F3.png?generation=1606396517653027&alt=media" alt=""></p>
<p>As you can see, resnet50 got better private lb despite public lb score.<br>
(I wasn't sure, so I didn't choose the ensemble model.)</p>
<h1>Etc.</h1>
<p>I did some other experiments such as raster size - 300 and finetuning model using high raster size, but It is not good for me. Single model is best. haha<br>
I tried <a href="https://www.kaggle.com/pestipeti" target="_blank">@pestipeti</a> advices for improving training speed but my hardware is not good for this. (no spaces and no time) Anyway, Thanks all. :)</p>
<ol>
<li><p>Yes, it is a single model.</p></li>
<li><p>Opt - Adam<br>
lr - 1e5 that is initial and I used linear schedule with warmup. I also tried other lr scheduler i.e. CosineAnnealingWarmRestarts but it is not good for me.</p></li>
</ol>
<p><a href="https://www.kaggle.com/kramadhari" target="_blank">@kramadhari</a> </p>
|
Lyft Motion Prediction for Autonomous Vehicles
|
classification approach
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: Lyft Motion Prediction for Autonomous Vehicles
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>thanks <a href="https://www.kaggle.com/hengck23" target="_blank">@hengck23</a> 😊</p>
<p>Yes 😊<br>
(Your message must have at least 10 characters.)</p>
<p>In the last week, I tried classification approach and it performed well or even better than my regression model.</p>
<p>Due to time limitations, I just use K-Means on validation trajectories to get 1K target classes. In test, merge Top70 predicts to 3. Last day, I trained a 5K classes model and use Top400 to merge.</p>
<p>Blend regression(three models) and classification(500, 1K, 5K classes) models to get public LB score improvement from 15 to 12.8</p>
<p>My merge code:</p>
<p>`from itertools import combinations</p>
<p>def optimize_predicts(preds, topK=3, yp=1):<br>
pred3 = []<br>
comb = np.array((list(combinations(range(preds.shape[-2]), topK))))</p>
<pre><code>for k in range(len(preds)):
p = preds[k,:,:-1]
y = preds[k,:,-1]
cost = pairwise_distances(p)*(y**yp)
labels = cost[comb[cost[comb].min(1).sum(-1).argmin()]].argmin(0)
pr=np.zeros((topK,101))
for i in range(topK):
sel = labels==i
pr[i,:100] = ((p[sel]*y[sel,None]).sum(0)/y[sel].sum())
pr[i,-1] = y[sel].sum()
pred3.append(pr)
return np.array(pred3)`
</code></pre>
|
M5 Forecasting - Accuracy
|
103rd place (silver medal) solution
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: M5 Forecasting - Accuracy
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>As a rookie, I'm here to learn from all you wise kagglers. I've learned a lot by reading your public kernels. Thank you all!</p>
<p>Although this competition seems a "a lottery", it's more imprtant to summary the experiences but not ranking.</p>
<p>In return, this is my solution, which most based on public kernels. Thanks to <a href="https://www.kaggle.com/ragnar123/">ragnar</a> and all other kernel authors!</p>
<h3>Accuracy-Competition</h3>
<ul>
<li><p>FE: adding a <code>weekends</code> feature.</p></li>
<li><p>I used 4 single models:</p>
<ul><li><p>time series split 3 fold cv - rmse loss function</p></li>
<li><p><a href="https://www.kaggle.com/rikdifos/timeseriessplit-cv-poisson">time series split 3 fold cv - poisson loss function</a></p></li>
<li><p>time series split 3 fold cv - self-defined loss function</p></li>
<li><p>rolling prediction</p></li></ul></li>
<li><p>Then I calculate all prediction's mean value, the I recode very tiny prediction to 0. Finally, I use a magic multiplier close to 1.</p></li>
</ul>
<p>All code could be downloaded from my github repo:
<a href="https://github.com/songxxiao/m5_compete">https://github.com/songxxiao/m5_compete</a></p>
|
M5 Forecasting - Accuracy
|
111th Place Solution (7th on Public) - Key Ideas
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: M5 Forecasting - Accuracy
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Tuning of sub_row, sub_feature and num_leaves give big gain. And when new feature was added, I increase num_leaves, and this give some gain.</p>
<ul>
<li>Week-by-week model (one model for first week with lag_7 feature, one model for second week with lag_14 feature, one model for third week with lag_21 feature, one model for fourth week with lag_28 feature). Recursive model works on Public, but don't work on CV and Private.</li>
<li>Target Encoding for item_<em>id, month, store</em>_id, mday, event__name, (hand written target encoding is used due to memory limitations).</li>
<li>Precise hyperparameter tuning (gives big gain). </li>
<li>Special Features :
<ul><li>Average Lag (lag_7 + lag_14 + lag_21 + lag_28 + lag_35 + lag_42) to capture weekday pattern</li>
<li>Expected Sales (lag_7 + (mean_7 - mean_28)) to capture sales trend</li>
<li>Price Diff (sell_price - sell_price_lag_7)</li></ul></li>
<li>One model in ensemble: y = mean_28(x) + LGBM.predict(x). y_train = y - mean_28</li>
</ul>
<p>Before training: ytrain = ytrain - mean28(xtrain) [for each sample: sample.y = sample.y - sample.mean28]
Trainning: LGBM.train(xtrain, ytrain)
Prediction: y_answer = LGBM.predict(x) + mean28(x)</p>
|
M5 Forecasting - Accuracy
|
123rd place solution
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: M5 Forecasting - Accuracy
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>I will share my solution on <a href="https://www.kaggle.com/xxbxyae/123rd-place-solution">this notebook</a>. <br>
(latest version is just running...)</p>
<ul>
<li>try: Basic FE(lag/diff/roll, calender feats)</li>
<li>model: single LightGBM
<ul><li>objective: 'poisson' or 'tweedie' (poisson was better.)</li>
<li>hyperparameter tuning with Optuna(not selected as final sub)</li></ul></li>
<li>CV: Custom time series split by opened kernel.</li>
<li>not try: weight tuning, FE with marketing knowledge.
<ul><li>We have to select only 1 submission as final, so I selected "robust" solution.</li></ul></li>
<li>result
<ul><li>public : 0.61444</li>
<li>private : 0.60825 (123rd place)</li></ul></li>
</ul>
<p>IMHO, the question was "how to reduce uncertainly" in this task. <br>
(I know that this competition name is "Accuracy"...🤔) </p>
<p>Congratulations for winners!
And thanks for organizers and all participants! 🐱 </p>
|
M5 Forecasting - Accuracy
|
14th place solution
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: M5 Forecasting - Accuracy
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks to everybody for a great competition.
Congratulations to the prize winners.
I got my first solo gold as my first medal in kaggle.</p>
<p>The outline of my solution is as follows:</p>
<p>1.Model: LGBM for each [store_<em>id] x [dept</em>_id] ( totally, 70 models )
- Objective: tweedie (custom object do not improve CV)
- Weight: cumulative actual dollar sales (last 28 days)
( I do not use scale for RMSSE. )</p>
<p>2.Data period: 2014/1/1~ (before 2014, the trends are different)</p>
<p>3.Features
- Lag demand
28 days shift + mean and std for 7, 14, 28 days, etc..
(day by day for 1~7, 14, 21 days, and recursive : I use one with lower CV for each [store_<em>id] x [dept</em>_id])
- Sells prices
some statistics of sells prices and, sell prices for same item__id in CA_3
(Sell prices for same item_id in CA_3 explain zero sales period for some items.)
- Calendar
Target encoding for ids (store, item, ...) x [weekday, events, or month] or ids with last 3M, 1Y, 2Y (rolling, no leak).
This variables works well.
Additionally ,I remove some variables following permutation importance.</p>
<p>4.CV: last 3 x 28 days, and (sub : last 2 x 28 days + same period at 1 year before)</p>
<p>I will consider that, but it will takes long time to prepare the codes since the codes are consist of many parts. Thanks your comment.</p>
<p>Thanks for your comment. I did not use early stopping.
"num_rounds" was fixed based on CV results.</p>
|
M5 Forecasting - Accuracy
|
16th Place Solution - Kalman Filters and Boosted Trees
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: M5 Forecasting - Accuracy
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>I just posted my team's solution <a href="https://nousot.com/blog/how-we-won-gold/">on my company Nousot's blog</a> and our code is <a href="https://github.com/nousot/Public/tree/main/Kaggle/M5">on Github</a>. In the article, the Section entitled "The Public Notebook Component," is where the methodological description starts. Cheers to <a href="/kyakovlev">@kyakovlev</a> for the excellent data pipelines.</p>
<p>Our custom component used Kalman Filters via the R package <a href="https://cran.r-project.org/web/packages/KFAS/index.html">KFAS</a>, an awesome time-series tool if you gravitate towards state space modeling. Our data pipeline for this solution was constructed from scratch and relatively simple. However, at the end of the contest we realized that our solution was loosing big for the sparse series, so we used a loess fit to help us choose between a boosted tree solution from the public notebooks and the Kalman Filter solution for each time series. I suppose that makes it a "mixture of experts."</p>
<p>Here's a case where the Kalman Filter looked more reasonable to us than the boosted tree solution:</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F114170%2F43c9ef6e9249743d6884a7f5269d427b%2FKalmanWins.png?generation=1595451979390581&alt=media" alt=""></p>
<p>And here's a case where the boosted tree's solution was more reasonable:
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F114170%2F827e75866eb49ce3285dc87f63c730e3%2FTreesWin.png?generation=1595452094881138&alt=media" alt=""></p>
<p>It was a great contest. Thanks everyone who competed!</p>
<p>Ben</p>
|
M5 Forecasting - Accuracy
|
175 position in M5 Forecasting - Accuracy
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: M5 Forecasting - Accuracy
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Yeah I used sales data and for features snap data(used based on state), events(one hot encoded), price. Coming to pre-processing, I did some outlier removal and also for sporadic data I did some analysis to separate no sales vs out of stock. </p>
<p>Congrats to all winners and participants!!.
This is my first medal in Kaggle platform. I felt very motivated after getting this. I would like to share my approach and why I chose to do like that.
Here I chose Deep State as my forecasting Algorithm/Estimator with GluonTS as my framework.
The reasons to choose this model is as follows:
1. DeepState is a Statespace form of Exponential Smoothing Algorithm using Deep Neural Network. Here the idea of forecasting is leveraged to maximum with Hidden Markov Model approach i.e., previous day’s forecast will determine today’s forecast.
2. DeepState uses a joint modelling approach, where it uses the covariates(regressors) to find the state space parameters. When I say state space parameters, they are latent variables like trend, level, seasonality.
3. In basic way, the current latent state of latent variable is a transformation on previous latent state along with transmission coefficients and emission coefficients. So, using the covariates, the neural network gets trained conjointly to get the latent variables and with this latent variables we forecast the future.
4. While forecasting/prediction, the network is unrolled to get the latent variables back and then predicted using them.
Hence with the above mentioned uses of DeepState where it can train jointly, we can learn features from other timeseries and also Gluonts framework has functionality to train on many timeseries at once can reduce a lot of training time as well.
Also, as the sales were hierarchical and also there was some dependency of one product in one department that might affect the sale of another product in the same department. Here joint modelling approach can benefit the forecasts.
<strong>Data Preparation/Training/Evaluation:</strong>
The Data Provided by M5 was in the form of (N,T) notation, where N denotes the no of timeseries and T denotes length of timeseries.
GluonTS builtin notation follows the same with that of provided by M5 where I leveraged the builtin Data Structure of gluon for modeling and the preparation time was less than 2 minutes. Coming to the Training, we need to specify the prediction length, frequency of timeseries, should we add trend or not for the Deepstate Estimator and the neural network parameters like batch_size, epoch where batch size is the no of timeseries that goes into training at once and log-loss is validated on them whereas epoch tells us the point where the network parameters should be updated. Training the 30490 timeseries took about 20 mins leveraging the benefits of GluonTS.
While evaluation, as mentioned the network is unrolled to get the latent variables and we had 30490 timeseries, it took around 1 hours to forecast.
So on total, the complete runtime was about 1.5 hours.</p>
|
M5 Forecasting - Accuracy
|
1st place solution
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: M5 Forecasting - Accuracy
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p><a href="/solomonxian">@solomonxian</a> Thanks a lot!</p>
<p>At first, i made dicision based on this <a href="https://www.kaggle.com/kyakovlev/m5-three-shades-of-dark-darker-magic">kernel</a>. For me, It worked well.
> lgb_params = {
'boosting_type': 'gbdt',
'learning_rate': 0.03,
'n_estimators': 1500,
} </p>
<p>At last for the final model, I usually use this way.
> lgb_params = {
'boosting_type': 'gbdt',
'learning_rate': 0.015,
'n_estimators': 3000,
} </p>
<p>learning_rate : 0.03 -> 0.015 (multiplying 1/n)
n_estimators : 1500 -> 3000 (multiplying n)</p>
<p>This way often leads to better result, for me.</p>
<p><a href="/yanyangayay">@yanyangayay</a> Thanks!!</p>
<blockquote>
<p>can you share your code? like in github, so I can understand your idea better.</p>
</blockquote>
<p>I'm going to do it from now on. I'll leave a comment when it's done.</p>
<p><a href="/kuluoluo">@kuluoluo</a> Thank you for congratulations!</p>
<blockquote>
<p>Could you share more details about how to choose best features? thank you</p>
</blockquote>
<p>Based on <a href="https://www.kaggle.com/kyakovlev/m5-three-shades-of-dark-darker-magic">this kernel</a>, i did additional feature engineering. However, the more features, the bigger std of my cvs. So, i didn't choose any of my additional feature.</p>
<p><a href="/tarique7">@tarique7</a>
Thanks a lot !!!</p>
<p><a href="/rdizzl3">@rdizzl3</a> these are the score from my cv! </p>
<p><img src="https://github.com/YeonJun-IN/data.science.competition/blob/master/4.%20%5Bkaggle%5DM5-Accuracy/img/cvs_score_1.png?raw=true" alt=""></p>
<p><img src="https://github.com/YeonJun-IN/data.science.competition/blob/master/4.%20%5Bkaggle%5DM5-Accuracy/img/cvs_score_2.png?raw=true" alt=""></p>
<p><a href="/choisgood">@choisgood</a> Thank you for congratulation!</p>
<blockquote>
<p>What is "recursive" or "non-recursive" methods?</p>
</blockquote>
<p>I guess <a href="https://www.kaggle.com/c/m5-forecasting-accuracy/discussion/151927">this discussion</a> will help you.</p>
<p><a href="/chatchann">@chatchann</a> Thank you for appreciating and congratulation!</p>
<p><a href="/headsortails">@headsortails</a> Thanks a lot !
Your brilliant EDA gave me a lot of insight. Really Thank you.</p>
<p>Thanks a lot ! <a href="/duykhanh99">@duykhanh99</a> </p>
<p><a href="/greenfantasy">@greenfantasy</a> Thanks a lot!</p>
<p>> Was there also variation in the predictions of the models trained on different "groups" (by cat, by store cat, by store dept)?</p>
<p>There was smaller variation on different groups than on recursive / non recursive.
So, the more important part of modeling strategies is (i think) to ensemble "non-recursive" and "recursive"</p>
<p><a href="/miguelpm">@miguelpm</a> Thanks a lot!</p>
<blockquote>
<p>If I may ask, what kind of non-recursive modeling you made? Did you: 1) avoid shorter than 28 days lags, 2) made 28 models or 3) modeled expected Nas distribution ? Or some other 4) I can not think of :-)</p>
</blockquote>
<p>"1) avoid shorter than 28 days lags" is correct !</p>
<p><a href="/kyakovlev">@kyakovlev</a> I learned a lot from you 👍
Thank you for congratulations.</p>
<p><a href="/robfrank26">@robfrank26</a> Thanks a lot. </p>
<blockquote>
<p>Was your ensemble just a simple equal weighted blend of the 6 predictions?</p>
</blockquote>
<p>Yes, i used just a simple weight.</p>
<p><a href="/salonsai">@salonsai</a> Thank you for comment and congratulations :)</p>
<p><a href="/stecasasso">@stecasasso</a> Thanks a lot :)</p>
<p>Hi kagglers! :)</p>
<p>This my first solution sharing, i hope it's helpful for you.</p>
<h2>Thanks to</h2>
<p>First of all, i'd like to thank the competition organizers and data scientists who participated in the competition. I have learned a lot from you, Really Really thank you.<br>
(especially, <a href="https://www.kaggle.com/kyakovlev" target="_blank">@kyakovlev</a>'s kernels and discussions. Really helpful.)</p>
<h2>Solution</h2>
<p>The method i've used is very simple and not that much great. This is all based on insights from community. </p>
<h3>Pre-processing</h3>
<ul>
<li>features based on price</li>
<li>features based on calendar</li>
<li>features based on target lag (recursvie / non recursive)</li>
<li>features based on target lag rolling mean / std (recursive / non recursive)</li>
</ul>
<h3>CV strategies</h3>
<p><strong>Time based split</strong> : mimic train/test split</p>
<ul>
<li>cv1 : d_1830 ~ d_1857</li>
<li>cv2 : d_1858 ~ d_1885</li>
<li>cv3 : d_1886 ~ d_1913</li>
<li>public : d_1914 ~ d_1941</li>
<li>private : d_1942 ~ d_1969</li>
<li>without early stopping</li>
</ul>
<h3>Modeling strategies</h3>
<ul>
<li>recursive / non recursive<ul>
<li>by store_id</li>
<li>by store_id - cat_id</li>
<li>by store_id - dept_id</li></ul></li>
</ul>
<h3>Model</h3>
<ul>
<li>LGBM(single)</li>
<li>objective = tweedie</li>
</ul>
<h3>Post-processing</h3>
<ul>
<li><strong>Without</strong> post-processing. (e.g.) magic multiplier.</li>
</ul>
<h3>Simple summary as diagram</h3>
<p><img src="https://github.com/YeonJun-IN/data.science.competition/blob/master/4.%20%5Bkaggle%5DM5-Accuracy/img/simple_summay.png?raw=true"></p>
<h2>Opinion</h2>
<p>A metric called WRMSSE was unfamiliar with me, and data structure was complicated. So I first read the documents provided by the organizer, and I got a lot of insights from the brilliant notebooks and discussions.</p>
<ol>
<li>different time series by state, store, cat, dept</li>
<li>the effect of disaster and weather on sales(target)</li>
<li>"out of stock" problem</li>
<li>the anomaly of sales</li>
<li>the importance of solid CV</li>
</ol>
<p>and so on…</p>
<p>I decided two things through these insights.</p>
<ol>
<li>divide into groups with similar time series, and model it.<br>
(e.g.) by store, by store cat, by store dept, etc.</li>
<li>select final model using mean(cvs, public score) and std(cvs, public score)<br>
(especially, focusing on std.)</li>
</ol>
<p>At first I made baseline using non recursive method, and i saw that there was a lot of variation in cv and public score.(large std)</p>
<p>Then, i made second baseline using recursive method based on <a href="https://www.kaggle.com/kyakovlev" target="_blank">@kyakovlev</a>'s kernel, but there still was a lot of variation. </p>
<p>The interesting part here is,</p>
<ol>
<li>Overall, the recursive method had a better score than non recursive.</li>
<li>non recursive method had best score at cv3.</li>
<li>recursive method had best score at public.</li>
</ol>
<p>Based on these insights, i expected that ensembling non recur and recur might lead to robustness.</p>
<p>Then, i selected as final model.</p>
<hr>
<p>As i mentioned earlier, my method is very simple and not that much great. so i didn't expect this at all. I was very lucky to learn a lot and to get unbelievable result. </p>
<p>Thank you to all the kagglers!!</p>
<p>(and very sorry for many participants who spent a lot of time and effort on this competition. It's all thanks to you.)</p>
|
M5 Forecasting - Accuracy
|
21st Place Solution (Nodalpoints)
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: M5 Forecasting - Accuracy
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h1>M5 Forecasting - Accuracy Writeup</h1>
<h2>Thanks</h2>
<p>Me and Ouranos would like to thank the organizers for putting out such a exceptional competition on this scale. We also need to mention that our involvement in the M5 competition was both tasked and sponsored by our company (Nodalpoint LTD, Athens, Greece). This gave us almost one month and half to be active in the competition.</p>
<h2>Warm up (Costas)</h2>
<p>First I would like to share a personal opinion regarding the hierarchical nature of this competition. I began working on hierarchical stuff one a half month ago focusing on R packages 'forecast', 'hts' (hierarchical time series) and Professor Hyndman's m4 winning solution repository. I was modelling time series in every level-1 beeing the most aggregated and level-12 the most disagregated (item_ids) in the compensate. </p>
<p>I soon after compensating 30490 low level time series, I had some descent results on levels 10, 11, 12 (better from the best performing LightGBM model), but when aggregated on top levels they produced worst results. So even if the lightGBM model failed to capture the individual sales count for each item, by daily aggregation the errors were cancelling out each other producing better high-level time series. That realization made me hold back from the classical time series approach and focus to other directions for the last one month. </p>
<p>I am currently experimenting to see how this approach (hts and m4-winning forecasting per time series) would eventually score by itself and if it could further help our blend.</p>
<h2>Solution</h2>
<p>We followed the most common strategy: “treating the problem as a regression one”. So, no classic time series models or even a proper recurrent one. One of the key ingredients of our approach was the validation set selection:</p>
<ul>
<li>Validation set 1: ['d_1914', 'd_1915', …, 'd_1941'] (=public LB data)</li>
<li>Validation set 2: ['d_1886', 'd_1887', ', …, 'd_1913']</li>
<li>Validation set 3: ['d_1578', 'd_1579', …, 'd_1605’] (exactly one year before the private LB)</li>
</ul>
<p>All modelling and blending were based on improving the weighted mean and standard deviation on these three folds. We used 4 models in our final blend:</p>
<h3>Model 1 (lgb_nas) Tabular regression using 10 LightGBM models on each store</h3>
<ul>
<li><p>Features
We used publicly available features (thanks to the exceptional work of Konstantin Yakovlev. <br>
The features were divided in the following categories:</p>
<ol><li><p>Categorical
item_id, dept_id, cat_id</p></li>
<li><p>Price related
price_max, price_min, price_std, price_mean, price_norm, price_unique, price_momentum,
momentum_m, momentum_y</p></li>
<li><p>Calendar related
event_name_1, event_name_2, event_type_1, event_type_2, snap_CA, snap_TX, snap_WI,
tm_d, tm_w, tm_m, tm_y, tm_wm, tm_w_end</p>
<ol><li><p>Lag related</p>
<ol><li><p>Lag only (15 features): sales_lag_28, sales_lag_29, …, sales_lag_42</p></li>
<li><p>Rolling only (8 features): rolling_mean_7, rolling_mean_14, rolling_mean_30, <br>
rolling_std_30, rolling_mean_60, rolling_std_60, rolling_mean_180, rolling_std_180 </p></li>
<li><p>Lag and roll (12 features): rolling_mean_tmp_i, j for i in [1, 7, 14] and j in [7, 14, 30, 60]. These features were king of tricky because they need recursive evaluation during.</p></li></ol></li></ol></li>
<li>Mean encodings
enc_cat_id_mean, enc_cat_id_std, enc_dept_id_mean, enc_dept_id_std,
enc_item_id_mean, enc_item_id_std</li></ol></li>
<li><p>Model
LightGBM model using the following configuration:
<code>
{ <br>
'boosting_type': 'gbdt',
'objective': 'tweedie',
'tweedie_variance_power': 1.1,
'metric': 'rmse',
'subsample': 0.6,
'subsample_freq': 1,
'learning_rate': 0.02,
'num_leaves': 2**11-1,
'min_data_in_leaf': 2**12-1,
'feature_fraction': 0.6,
'max_bin': 100,
'n_estimators': …, <br>
'boost_from_average': False,
'verbose': -1,
'num_threads': 12
} <br>
</code></p></li>
</ul>
<p>We trained 10 models, one for each store using variable number of estimators:</p>
<p><code>
rounds_per_store1={
'CA_1': 700,
'CA_2': 1100,
'CA_3': 1600,
'CA_4': 1500,
'TX_1': 1000,
'TX_2': 1000,
'TX_3': 1000,
'WI_1': 1600,
'WI_2': 1500,
'WI_3': 1100
}
</code></p>
<h3>Model 2 (lgb_cos): Tabular regression using 1 LightGBM for all data</h3>
<ul>
<li><p>Features
We used publicly available features, divided in the following categories:</p>
<ol><li><p>Categorical
item_id, dept_id, cat_id, store_id</p></li>
<li><p>Price related
price_max, price_min, price_std, price_mean, price_norm, price_unique, price_momentum, momentum_m, momentum_y</p></li>
<li><p>Calendar related
event_name_1, event_name_2, event_type_1, event_type_2, snap_CA, snap_TX, snap_WI, tm_d, tm_w, tm_m, tm_y, tm_wm, tm_w_end</p></li>
<li><p>Lag related</p>
<ol><li><p>Lag only (15 features): sales_lag_28, sales_lag_29, …, sales_lag_42. </p></li>
<li><p>Rolling only (8 features): rolling_mean_7, rolling_mean_14, rolling_mean_30, rolling_std_30, rolling_mean_60, rolling_std_60, rolling_mean_180, rolling_std_180 </p></li>
<li><p>Lag and roll (12 features): rolling_mean_tmp_i, j for i in [1, 7, 14] and j in [7, 14, 30, 60]. These features were king of tricky because they need recursive evaluation during.</p></li></ol></li>
<li><p>Mean encodings
enc_cat_id_mean, enc_cat_id_std, enc_dept_id_mean, enc_dept_id_std, enc_item_id_mean, enc_item_id_std</p></li></ol></li>
</ul>
<p>• Model
A single LightGBM model using the following configuration:
<code>
{
‘boosting_type’: ‘gbdt’,
‘objective’: ‘tweedie’,
‘tweedie_variance_power’: 1.1,
‘metric’: ‘rmse’,
‘subsample’: 0.5,
‘subsample_freq’: 1,
‘learning_rate’: 0.03,
‘num_leaves’: 2047,
‘min_data_in_leaf’: 4095,
‘feature_fraction’: 0.5,
‘max_bin’: 100,
‘n_estimators’: 1300,
‘boost_from_average’: False,
‘verbose’: -1,
‘num_threads’: 8
}
</code></p>
<h3>Model 3 (keras_nas): NN regression using Keras model with embeddings</h3>
<p>We created a neural network model using Keras/Tensorflow that uses low-dimensinoal embeddings for the categorical inputs:
* Features: We used the following subset of the publicly available features. All continuous features were scaled in [0, 1] using min/max values from the training set.
* Continuous
* sell_price,
* sell_price_rel_diff,
* rolling_mean_28_7,
* rolling_mean_28_28, <br>
* rolling_median_28_7,
* rolling_median_28_28,
* logd: np.log1p(sales.d-sales.d.min())
* snap_CA,
* snap_TX,
* snap_WI,
* Categorical
* wday,
* event_name_1,
* event_type_1,
* event_name_2,
* event_type_2,
* dept_id,
* store_id,
* cat_id,
* state_id</p>
<h3>Model 4 (fastai_cos): NN regression using a fastai tabular package</h3>
<ul>
<li><p>Features
Same as Model 2 (lgb_cos). Embeddings for item_id were reduced at 10. Used fillna(-1) to fill in non-available entries. No scaling used.</p></li>
<li><p>Model</p>
<ul><li>Architecture
Following the fastai tabular interface the model was created using
<code>
tabular_learner(data,
layers=[128, 64, 32, 16],
ps=[0.05, 0.05, 0.05, 0.05],
emb_drop=0.04,
emb_szs={'item_id': 10})
</code>
The model above was trained for 8 epochs using a custom Tweedie loss function </li>
<li>Loss function
Custom Pytorch implementation of Tweedie loss, that clipped zeros at 1.0e-6 to avoid NaNs
<h3> </h3></li></ul></li>
</ul>
<p>Final blend
For the final blending, we chose weighted geometric mean based on the average metric on three validation sets. We noticed that <strong>keras_nas</strong> NN predictions had an unexpected large peak on the last day (day 1969). See for example the plot below:
</p>
<p>After confirming this behavior to be dominant in almost all cases, we decided to exclude that model’s prediction for the last day. So our final ensembling looks like: </p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F281494%2F0c7aa88490d093ba1805dee8ba0380f4%2FScreenshot%202020-07-07%20at%2010.15.31%20AM.png?generation=1594106672787168&alt=media" alt=""></p>
<p>In the table below we present the score of each model and the final ensemble for each validation set. </p>
<p>| |lgb_nas| lgb_cos| keras_nas| fastai_cos| ensemble|
| --- | --- |--- |--- |--- |--- |
|weights days 1-27 |3.5 |1.0 |1.0 | 0.5 |0.531
|weight day 28 |3.0 | 0.5 | 0.0 | 1.5 |0.531
|Val. set 1 |0.474 |0.470 |0.715 |0.687 |0.531
|Val. set 2 |0.641 |0.671 |0.577 |0.631 |0.519
|Val. set 3 |0.652 |0.661 |0.746 |0.681 |0.598
|Average|0.589 |0.602 |0.679 |0.667 |0.549
|Std |0.08 |0.09 |0.05 |0.02 |0.03</p>
<p>Correlation matrix flatten()-ing the 30490 x 28 prediction:</p>
<p>| Final pred. | lgb_nas| lgb_cos|keras_nas |fastai_cos|
| --- | --- |--- |--- |--- |
| lgb_nas | 1.0000| 0.9941|0.9420 |0.9251 |
| lgb_cos | 0.9941 | 1.0000 |0.944 | 0.9281 |
| keras_nas |0.942 |0.9441 | 1.0000| 0.8952|
| fastai_cos | 0.9251 | 0.9281|0.8952 |1.0000 |</p>
<h2>Summary</h2>
<ul>
<li>Validation sets are very important. We were lucky enough to select those three because of it was relatively fast to calculate predictions for them (tripled the computation). </li>
<li>In time series modelling you need to be extra careful not to leak information from train to validation set.</li>
<li>Model diversity was really important. Ouranos spent many hours trying to stabilize keras_nas outcomes. A tedious process with a lot of trial-and-error that resulted in a hand full of features that gave great diversity</li>
<li>Our local validation was <strong>0.549</strong> and our final private score was <strong>0.552</strong> without any magic multiplier. We did tried out various multipliers but 1.0 was the best choice. This was by far the most important result of our methodology. We manage to emulate the performance on the private test. We were confident about the final score but we just didn't know were all the competitors would end up.</li>
<li>Talking about multipliers: if we 've used the magic number 0.97 we would end up on the top of the leaderboard </li>
<li>We regret not adding classical methods (R packages hts, forecast) to the ensemble </li>
<li>We ‘ve also played around with recurrent implementations, but they never reached the level maturity so as to include them in the final blend</li>
<li>Our best submission was our last one!!</li>
</ul>
<p>I will append the keras_nas architecture as well. Only one model was trained using all data for the last year. Actually this is something I should amend to all descriptions. How far in the past did we go..</p>
|
M5 Forecasting - Accuracy
|
25th place solution
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: M5 Forecasting - Accuracy
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>I learned a lot from this competition. I appreciate excellent discussion and notebook.
My solution may be worthless and I wonder why this works well in private, but I share it.
I predict level 1~10 and 12 values.</p>
<p>[model]
lightgbm
level 12 recursive, objective poisson
level 1~10 day-by-day (target->sale*price) objective rmse (level 1~9) tweedie (level 10)</p>
<p>[feature]
simple shift roll diff, product count , some calender features, price</p>
<p>[validation]
d1830-d1857, d1858-d1885, d1886-d1913, d1914-d1941</p>
<p>I spent time on level1~10 prediction, cv of level 1~10 predictions were stable.
I tuning level1~10 parameters using StratifiedFold.</p>
<p>I combine prediction like this,
<code>df[level12]*=df[price]</code>
<code>df[level_] = df[level_prediction]*(df[level12]/df.groupby(level_).transform(sum))</code>
<code>df[final_prediction] = 0.65*mean(df[level8, level9]) + 0.35*mean(df[level1~7, level10, level12])</code></p>
<p>I cloud not get good level 12 wrmsse, but get better score when combining the predictions of level 1~10. I believe level1~10 predictions boost wrmsse score.</p>
<p>| | single level 12 | combine level 1~10|
| --- | --- |
|d1942-d1969|0.73233|0.55895|
|d1914-d1941 | 0.60359 | 0.5635|
| d1886-d1913| 0.56219 | 0.51489|
|d1858-d1885 | 0.67186 | 0.60522|
|d1830-d1857 | 0.71142 | 0.644|</p>
<p>I post clearn <a href="https://www.kaggle.com/mothermoto/m5-solution/notebook">notebook</a>.</p>
<p>level - 12, 10 past 200 days
level - 1 past 900 days
level - 2~9 past 730 days</p>
<p>I wanted to estimate pattern of arrival of products which are out of stock, but it takes long time when using long term level 12 and 10 data, so i used past 730, 900days for lower level, 1~9.
I'm not sure but I think arrival of products occurs at the same time for some group
products (dept-store, cat-store) and it means I may be able to estimate pattern of arrival of products with lower level predictions.</p>
|
M5 Forecasting - Accuracy
|
2nd place solution
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: M5 Forecasting - Accuracy
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Hi Kagglers!</p>
<p>first of all I would like to thank Prof. Makridakis, Evangelos Spiliotis, the organizing team, the generous sponsors and everyone else involved for hosting this interesting competition.</p>
<p>Also I want to thank all the great public kernel contributors that built the basis for my solution and final rank. Without your great work this would not have been possible! (Please see credits at the end of the summary)</p>
<h3>1. Before we start...</h3>
<p>The overall approach consists of two separate modelling streams on top and bottom of the grouping hierarchy that are aligned to get a result.
It should be reproducible for any given time-frame as well as automatable and therefore valuable for any complex grouped/hierarchical time series problems.</p>
<h3>2. The starting point</h3>
<p>As a quick reminder what our baseline was <a href="https://www.kaggle.com/chrisrichardmiles/simple-model-avg-last-28-days-grouped-by-weekday">a quick look at this notebook</a> is helpful.
Pretty clear that if we cannot beat 0.75 significantly we are on the wrong track.</p>
<h3>3. The bottom level lgb model - "Probability" of single item being bought:</h3>
<p>The bottom level is based on the lgb models that many participants used. ( <a href="/kyakovlev">@kyakovlev</a> - thank you for your great inputs in this challenge )
One really important aspect is that I did not use any historic sales data as features (no rollings, no lags, no last buy etc.).
My hypothesis is that the drivers for a peppermint candy bar being bought in the WI_1 shop are not whether or not this candy bar was bought once yesterday and twice on Monday but only price, date-time, SNAP, etc.</p>
<p>The lgb model learns a "probability" for each item(-quantity) being bought in a given shop on a given day based on the external drivers.
( By the way - <a href="https://youtu.be/uHGlCi9jOWY">sorry to all the statisticians reading my crazy ideas here</a> )</p>
<p>It will be a major next step to dig into the understanding of this bottom level models.
For example: Why do errors cancel out so nicely when aggregating? (I have a theory too embarrassing to write about yet - will follow up after some testing) </p>
<p>Maybe my hypotheses turn out completely wrong but empirically they did hold for this given data set.
As a sidenote: lr 0.2, 3600 iterations ... pretty basic settings on this one. Trained by store.</p>
<h3>4.) The problem with the correct level</h3>
<p>When following this bottom level approach we run into one problem. <em>The resulting models do not incorporate any trend or seasonalities.</em> (See comments for discussion - this point is not correct)
We cannot (or at least I cannot) "de-trend" the underlying signals due to their intermittent nature.</p>
<p>Maybe incorporating some kind of rolling/lag data might work - but I didn't see how to do this in a stable way that I understand or at least believe to understand (sometimes not the same :-) ) and am able to control.</p>
<p>A lot of people in this competition chose to tackle this issue with "magic multipliers".</p>
<p>What I used to shift the level up or down was <a href="https://www.kaggle.com/c/m5-forecasting-accuracy/discussion/140564">one of the custom loss functions discussed in the forums</a>. </p>
<p><code>
def custom_asymmetric_train(ypred, ytrue):
y_true = y_true.get_label()
residual = (y_true - y_pred).astype("float")
grad = np.where(residual &lt; 0, -2 * residual, -2 * residual * multiplier)
hess = np.where(residual &lt; 0, 2, 2 * multiplier)
return grad, hess
</code></p>
<p>With a multiplier >1 we can train the model to "overshoot" the ground-truth with a multiplier <1 we train the model to "undershoot" the ground truth.
I think the loss approach will work better than shifting the result with a multiplier but did not compare the two approaches.</p>
<p>Top level aggregations for a good fit and an overshot fit look like this:</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F449263%2F89417feac00e6cd0dc83aaa8043f9fd9%2FVal6_quite_good_example.png?generation=1594061478181612&alt=media" alt=""></p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F449263%2F34365bac17a83cb7b37130ee9709403e%2FVal5_3mult_too_high_example.png?generation=1594061508266861&alt=media" alt=""></p>
<h3>So how do we find the right level if we do not want to guess? (i.e. "play the lottery")</h3>
<h3>5.) Aligning with an independent top-level prediction</h3>
<p>What we need to find the right level is a top level prediction for which we are confident that trends and seasonalities are learned very well.
The approach I used was to use N-Beats for the top 5 levels. </p>
<p>The resulting predictions are very good and a great alignment basis as you can see for example in this top level (lvl1) validation result:</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F449263%2F35b8f0bca46bc996a57c6b9711698e6f%2FN-Beats-TopLvl.png?generation=1594061615328817&alt=media" alt=""></p>
<p>Now I trained 15 different bottom level lgb solutions with different loss multipliers.
Those bottom level predictions were aggregated and aligned with the N-Beats predictions for levels 1-5.
Selection of the best fit was basically done when the mean error between N-Beats and aggregated bottom level predictions "flipped" from positive to negative or vice versa. </p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F449263%2Fd71aea79739d8a17c2c0ef86369ad5d5%2FFinal_Ensemble_Table.png?generation=1594061859331963&alt=media" alt=""></p>
<p>After selecting the best fitting bottom level solution I built an ensemble consisting of this solution and the 2 solutions above as well as the 2 solutions below.
( In my earlier experiments I saw that this had a quite beneficial effect for hitting the optimal level - my intuition was that we get a better "loss surface" with the ensemble - but again ... a lot of "intuition" here given that there was no time to analyze all ideas I had and given that I am not the best programmer. )</p>
<p>The final alignment for Level1 of my submission looked like this:</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F449263%2Fa9e79adaf0b4f6653ff6741c0cce28ba%2FFinal_Ensemble_Lvl1_aligned.png?generation=1594061940630819&alt=media" alt=""></p>
<h3>6. ) What did not work</h3>
<p>In the beginning I played around with DeepAR and some other ideas.
Later on I tried to reconcile the different prediction levels with the R/hts implementation.
After renting out a 128Gig instance on AWS and a sleepless night I came to the conclusion that this will not work for me :-) - I am pretty sure I messed up the residual calculation for MinT but my feeling is that it will not work anyway given that we have >30k bottom level signals and just over 100 top level signals .... OLS/WLS did not work for me either.</p>
<h3>7. ) What I would love to see</h3>
<p>Solutions that did not use lgb at all. Just saw the 3rd place writeup a minute ago - looking forward to reading more on this one.</p>
<h3>8. ) Credits</h3>
<p>The kernel I used for all my features is: <a href="https://www.kaggle.com/kyakovlev/m5-simple-fe">https://www.kaggle.com/kyakovlev/m5-simple-fe</a>
From the same author the starting point of my lgbm exploration was (many of you may have seen it already): <a href="https://www.kaggle.com/kyakovlev/m5-three-shades-of-dark-darker-magic">https://www.kaggle.com/kyakovlev/m5-three-shades-of-dark-darker-magic</a>
Another input to my lgbm exploration was: <a href="https://www.kaggle.com/ragnar123/simple-lgbm-groupkfold-cv">https://www.kaggle.com/ragnar123/simple-lgbm-groupkfold-cv</a></p>
<p>The kernel that put me in touch with GluonTS (great framework!!) was this one: <a href="https://www.kaggle.com/steverab/m5-forecasting-competition-gluonts-template">https://www.kaggle.com/steverab/m5-forecasting-competition-gluonts-template</a>
Even though I did not end up having success with DeepAR getting to know GluonTS was key to my final path.</p>
<p>The kernel that allowed me to rapidely test hypothesis and give me visual insight to the results was this one (really love this one!!): <a href="https://www.kaggle.com/tnmasui/m5-wrmsse-evaluation-dashboard">https://www.kaggle.com/tnmasui/m5-wrmsse-evaluation-dashboard</a> </p>
<p>My aggregation code was copied from this kernel: <a href="https://www.kaggle.com/lebroschar/aggregate-forecast-eda">https://www.kaggle.com/lebroschar/aggregate-forecast-eda</a></p>
<p>You see that a lot of community input was used - thank you everyone also for the great discussions on the kernels.</p>
<p>Thank you all for this amazing competition.</p>
<p>The aggregation levels 1-12 - for alignment I am using the level 1 (i.e. top level)</p>
<p>I trained a set of bottom level models with multipliers ranging from 0.9 to 1.23.
By comparing (see the mean error flip part above) the aggregates of those models with the N-BEATS reference I figured out that the optimum is somewhere in the range 0.93-0.95 and built an ensemble with 0.9, 0.93, 0.95, 0.97 and 0.99 </p>
<p>I have (manually) checked alignement between lgb models and actuals for validation timeframe and three 28 day periods before that to be sure that bottom level performs as I expected. </p>
<p>Yes all date time features from the referenced simple-fe kernel are used - so you are right that this will include some trend and seasonal data. This will be a bit "regularized" over the whole training set.</p>
<p>So my point that it does not learn <em>any</em> trend or seasonality is wrong. </p>
<p>What I wanted to point out is that the model learns how much peppermint candy is sold on a given day in a given shop based on datetime features, price, SNAP etc. But not based on short term intermittent demand.
So what it does not learn is how to align with the long-term trend and seasonalities that are important for the end result.</p>
<p>Does that make sense?</p>
<p>Loss multipliers of ensemble were in range 0.9 to 0.99</p>
<p>That data is not available for the evaluation period so I never tested that ...</p>
<p>Hey <a href="https://www.kaggle.com/mavillan" target="_blank">@mavillan</a> just saw that I never responded to this one - sorry!: Regarding the implementation please have a look at: <a href="https://github.com/matthiasanderer/m5-accuracy-competition" target="_blank">https://github.com/matthiasanderer/m5-accuracy-competition</a></p>
<p>The N-BEATS implementation was GluonTS - for parameters please have a look at the notebook.</p>
<p>The "right" multiplier was found by aligning the aggregate bottom level signals with the N-Beats forecast as seen in the table above.</p>
<p>For those upper levels my hypothesis is that you will not find a better representation of multiple trends/seasonalities than what N-Beats learns …</p>
|
M5 Forecasting - Accuracy
|
3rd place solution - NN approach
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: M5 Forecasting - Accuracy
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>We loaded all time series with features into the memory and randomly sampled 64-batch of 28days slice on-the-fly (we removed the period before starting sales for each item). For the training data, 2~3G memory would be needed approximately. We used a pytorch version of GluonTS (<a href="https://github.com/zalandoresearch/pytorch-ts">https://github.com/zalandoresearch/pytorch-ts</a>) as a backbone.
We've tried to cluster similar time series but we did not find any useful setups.</p>
<p>Hi everyone,
We would like to share our solution with you.</p>
<p>Firstly, we would like to thank hosts, Kaggle for opening this great competition. Also, thanks to all participants for useful discussions. Personally, this is the first competition I've joined, and I am happy to achieve a meaningful result.</p>
<p>Our goal was to achieve a high rank in this competition using deep learning (neural network) approach. I and my colleague are more familiar with deep learning methods and we believed that NN can get competitive result with other ML approaches (especially gradient boosting).</p>
<hr>
<h3>Summary</h3>
<p>We trained modified DeepAR with Tweedie loss and make a final prediction from the ensemble of multiple models chosen using the past 14 periods of WRMSSEs.</p>
<h3>Network</h3>
<p>Our base network is DeepAR(<a href="https://arxiv.org/abs/1704.04110">https://arxiv.org/abs/1704.04110</a>) which consisted of multiple LSTMs. We modified the baseline network to predict 28days with rolling predictions in the training phase (original DeepAR only predict 1-day in the training phase). Our modified DeepAR generates losses from rolled 28days and this gives more stable predictions on rolled prediction.</p>
<h3>Loss</h3>
<p>Tweedie Loss
- Thanks to <a href="/timetraveller">@timetraveller</a> for a good discussion (<a href="https://www.kaggle.com/c/m5-forecasting-accuracy/discussion/150614">https://www.kaggle.com/c/m5-forecasting-accuracy/discussion/150614</a>)</p>
<h3>Features</h3>
<p>We used the following features. All features are concatenated and fed to the network.</p>
<ul>
<li>Sale values
<ul><li>Lag 1 value</li>
<li>Moving average of 7, 28 days</li></ul></li>
<li>Calendar: all values are normalized to [-0.5,0.5]
<ul><li>wday</li>
<li>month</li>
<li>year</li>
<li>week number</li>
<li>day</li></ul></li>
<li>Event
<ul><li>Event type : use embedding</li>
<li>Event name : use embedding</li></ul></li>
<li>SNAP : [0, 1]</li>
<li>Price
<ul><li>raw value</li>
<li>Normalized across time</li>
<li>Normalized within the same dept_id</li></ul></li>
<li>Category
<ul><li>state_id, store_id, cat_id, dept_id, item_id : use embedding</li></ul></li>
<li>Zero sales
<ul><li>Continuous zero-sale days until today</li></ul></li>
</ul>
<h3>Training Scheme</h3>
<p>We randomly sampled 28-days slice from each sequence and made 64 slices for each batch. Each batch is fed to the network and network predicts the next 28-days. Training iterated 300 epoch (one-epoch = 30490/64 iterations). We used Adam optimizer and used cosine annealing for the learning rate schedule. We used all periods including validation(~1942) for training.</p>
<h3>CV</h3>
<p>It was hard to select CV period as WRMSSE is severely fluctuated according to the period. Besides, we found that 1914~1942 period is more unreliable as the characteristics of this period are more different from other periods. (There were many items start to selling from zero-sales)
As the level 12 value is intermediate and sporadic, we conclude that the network also struggles to learn about training values. And we conclude that we don't need to much care about over-fitting. Instead, we concentrate to select good model from the trained model, which has low WRMSSE values for a specific period.</p>
<p>We evaluated WRMSSE for the past 14 periods ((1914, 1886, 1858,... 1550) and selected a model that has a low mean of WRMSSEs. For each model, we evaluated every 10-epoch (from 200~300 epoch) and selected the top-3 epoch. From the trained 8 models, we make an ensemble model from 8*3 selected model for the final prediction.
- More precisely, we make a final prediction using 24 + 19 models (24 models have applied dropout, 19 models are not applied dropout). This was just a heuristic strategy.</p>
<h3>What we tried, but failed</h3>
<ul>
<li>Models
<ul><li>We used other network architectures including CNN, Transformers, ..., etc. We could not find any model superior to others, and we choose the most basic model, DeepAR. </li></ul></li>
<li>Loss
<ul><li>Classification loss (CE loss)</li>
<li>WRMSSE as a loss</li></ul></li>
<li>Forecast Reconciliation
<ul><li>Used different level but worse than using lv12</li></ul></li>
</ul>
<hr>
<p>We are happy to achieve the goal with our method. More importantly, we've learned many things from this competition. Thanks to all again!</p>
<p>Its difference is just random initialization.</p>
<p>Originally, we planned to submit uncertainty competition as well, but we missed the timeline to join. And we did not test our solution for uncertainty predictions.</p>
|
M5 Forecasting - Accuracy
|
4th place solution
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: M5 Forecasting - Accuracy
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thank you! Yes, you are correct.
Finally, I trained d1-d1941 and predicted d1942-d1969 for submission.</p>
<p>Yes, that's right.</p>
<p>First of all, I would like to appreciate the participants and organizers of the competition very much. I have learned a lot from this competition.
My solution may not seem to be of much value, but I have gained a lot of insight from the community so I felt obligated to share the solution with you.
(I especially learned a lot from @kyakovlev kernel. Thank you.)</p>
<p>[Solution]
- Model
- LightGBM (single)
- objective = tweedie
- Validation
- 5 holdout (d1578-d1605, d1830-d1857, d1858-d1885, d1886-d1913, d1914-d1941)
- no early stopping
- Model split
- for each store
- for each week
- model w1 predicts F01, F02, ..., F07
- model w2 predicts F08, F09, ..., F14
- model w3 predicts F15, F16, ..., F21
- model w4 predicts F22, F23, ..., F28
- Features
- General time-series features
- General price features
- General calendar features
- No recursive features</p>
<p>When the competition began, I first understood the data and evaluation metrics and created a baseline model.
Then I realized that the validation scores varied significantly over the period of time. (I can't build a proper validation.)
I was strongly convinced that this competition would be very difficult and that it would be impossible to build a model with high accuracy.</p>
<p>So I decided to give up on trying to get a high ranking in the competition. Instead of it, I decided to try to build a "practical" solution.
My strategy is as follows:
- Not to use post processing, multiplier, and leaks
- In practice, it is not possible to utilize such information, so I have decided that it should not be used.
- Trust CV but Not care about official evaluation metrics (WRMSSE)
- WRMSSE is evaluation metrics by the competition organizer, but in practice, I think WRMSSE is not always reasonable. Therefore I didn't make a custom loss function to avoid overfit this competition task itself.
- Not to use complex and recursive features
- Just use general features that can be applied to any practical tasks.
- Recursive features lead to error accumulation
- Not to use computation resources too much
- Single model (LightGBM only, no stacking/blending)
- Memory efficiency (model for each store and week)</p>
<p>As I mentioned earlier, I was not aiming for the high ranking, so I was very surprised by this result (4th place).
As you can see from the solution above, I'm not doing anything special.
What was valuable to me was learning a lot about building a simple solution that can be widely used in practice. The ranking itself means absolutely nothing to me.
(However, I feel very sorry for those of you who put in a great deal of effort to get to the top...)</p>
<p>Either way, I have learned a lot from this competition and community.
Thank you to all the kaggle community members.</p>
<p>Thank you! Please find my previous comment about week model. (I just wanted to save computation time by not making a day-by-day model.)</p>
<p>I mean recursive features are the use of the output of a model as input to the next model.</p>
<p>Thank you for your comment. First, I tried to build a day-by-day model (28 days x 10 stores = 280 models), but I found that it would have taken too long time. And I did not find so much accuracy improvement. Therefore, I created a weekly model (4 weeks x 10 stores = 40 models).
The lags are different for each week model. Model w1's lags are {7, 8, 9, ...}. Model w4's lags are {28, 29, 30, ...}</p>
<p>LightGBM's objective is tweedie. Evaluation metrics are WRMSSE (and RMSE) but please also find my previous comment about evaluation metrics).</p>
<p>"Not care about official evaluation metrics" -- sorry for the vague explanation.
I used WRMSSE (and RMSE) for evaluation metrics. However, I did not actively try to improve the metrics.
This may seem odd to other participants, but as I mentioned above, my goal of this competition was to learn how to build a practical solution.
For me, it was more important to be simple solution than to be a little more accurate...</p>
<p>Training data is split by store, but the model predicts the item level sales.</p>
<blockquote>
<p>What are general time-series features? Are these like rolling averages, etc?</p>
</blockquote>
<p>Yes. Lag features and rolling mean/std with different widows size.</p>
<blockquote>
<p>If so, then for each week you would have to shift those features forward by 7 days for the first week, 14 days for the second, etc. correct?</p>
</blockquote>
<p>That's right.</p>
<blockquote>
<p>Did you use all of the data for training?</p>
</blockquote>
<p>Yes, I did. I trained d1-d1941 and predicted d1942-d1969 for submission.</p>
<blockquote>
<p>What type of scores did you see in your CV across the different folds?</p>
</blockquote>
<p>I will check it later.</p>
<p><a href="/rdizzl3">@rdizzl3</a> <a href="/dantlion">@dantlion</a> Don't worry! I believe my code is not worth learning but I have to submit my code within two weeks. Of course, I plan to prepare the code by the deadline.
This is the rule of this competition, according to M5 Participants Guide.</p>
<blockquote>
<p><a href="https://mofc.unic.ac.cy/m5-competition/">https://mofc.unic.ac.cy/m5-competition/</a>
Reproducibility
The prerequisite for winning any prize will be that the code used for generating the forecasts, with the exception of companies providing forecasting services and those claiming proprietary software, will be put on GitHub, not later than 14 days after the end of the competition (i.e., the 14th of July, 2020). In addition, there must be instructions on how to exactly reproduce the M5 submitted forecasts. In this regard, individuals and companies will be able to use the code and the instructions provided, crediting the person/group that has developed them, to improve their organizational forecasts.</p>
</blockquote>
<p>I don't think my code is worth learning.
As I mentioned above, I learned a lot from <a href="/kyakovlev">@kyakovlev</a> 's kernels.
I recommend learning his excellent notebooks.
<a href="https://www.kaggle.com/kyakovlev/m5-simple-fe">https://www.kaggle.com/kyakovlev/m5-simple-fe</a>
<a href="https://www.kaggle.com/kyakovlev/m5-lags-features">https://www.kaggle.com/kyakovlev/m5-lags-features</a>
<a href="https://www.kaggle.com/kyakovlev/m5-custom-features">https://www.kaggle.com/kyakovlev/m5-custom-features</a>
<a href="https://www.kaggle.com/kyakovlev/m5-three-shades-of-dark-darker-magic">https://www.kaggle.com/kyakovlev/m5-three-shades-of-dark-darker-magic</a></p>
<p>I agree to you. It takes about 15 hours per holdout set using 8 cores / 32GB memory machine.
Therefore, I also utilized 10% random sampling.</p>
<p>I have created an overview slide of my solution.
Please find the attached image.
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F2668122%2F08557b1b7fe03b2be4f4a7aaacfbd7f8%2FM5A_4th_solution.png?generation=1594484107013484&alt=media" alt=""></p>
<p><a href="/etnemelc">@etnemelc</a> <a href="/rajaslonkar">@rajaslonkar</a> Regarding features and models, please see the overview slide.</p>
<p><a href="https://www.kaggle.com/webman19" target="_blank">@webman19</a> <a href="https://www.kaggle.com/yyyzzzwww" target="_blank">@yyyzzzwww</a> <a href="https://www.kaggle.com/babinu" target="_blank">@babinu</a> <a href="https://www.kaggle.com/etnemelc" target="_blank">@etnemelc</a> <a href="https://www.kaggle.com/rajaslonkar" target="_blank">@rajaslonkar</a> <a href="https://www.kaggle.com/dantlion" target="_blank">@dantlion</a> <a href="https://www.kaggle.com/rdizzl3" target="_blank">@rdizzl3</a><br>
Sorry to keep you waiting. I also pushed my code reproducing 4th place solution to my repository.<br>
If you have any questions, please let me know.<br>
<a href="https://github.com/monsaraida/kaggle-m5-forecasting-accuracy-4th-place" target="_blank">https://github.com/monsaraida/kaggle-m5-forecasting-accuracy-4th-place</a></p>
|
M5 Forecasting - Accuracy
|
54th place solution [No lottery - just a baseline]
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: M5 Forecasting - Accuracy
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>First of all I want to thank all Kaggle community: besides you can learn lots of new stuff here almost on every competition, community is very welcomed. </p>
<p>In this post I want to share my approach, for me the result was not surprising.</p>
<p>When the competition was firstly announced I was really motivated to invest lots of time into it in order to get a high place, but I faced some challenges at my work, so my competition-start was postponed and I started working under the competition about 1 month before the deadline when public LB had been already published.</p>
<p>Based on my CV and lots of top-scoring public notebooks with custom multipliers I decided to build just a good baseline. </p>
<p><strong>Validation</strong>
In my opinion it was the most important part.</p>
<p>I validate my score on 3 folds:</p>
<ul>
<li>(2016-03-27;2016-04-24]</li>
<li>(2016-04-24;2016-05-22]</li>
<li>(2015-05-17;2015-06-14]</li>
</ul>
<p>In my 3d validation fold I tried to choose aprox the same period of year - the same as final evaluation part.</p>
<p><strong>Pre-processing</strong>
There were some outliers and spikes in each individual ts so I did some smoothing:
using MAD (median absolute deviation) of last 180 days of an item to find outliers and replace it with value 7 days ago - without this smoothing rolling mean features which included holidays (like Christmas) didt work in proper way.</p>
<p><strong>Models</strong></p>
<ul>
<li><p>Standart LGBM with Tweedie Loss (1 model for all dates)
<code>params = {
'boosting_type': 'gbdt',
'objective': 'tweedie',
'tweedie_variance_power': 1.1,
'metric': 'rmse',
'subsample': 0.75,
'subsample_freq': 1,
'learning_rate': 0.03,
'num_leaves': 2**11-1,
'min_data_in_leaf': 2**12-1,
'feature_fraction': 0.7,
'max_bin': 100,
'n_estimators': 1400,
'boost_from_average': False,
'verbose': -1,
}</code></p></li>
<li><p>Wavenet with GRU-part</p></li>
</ul>
<p>Final submission was weightened average with 0.8 and 0.2 coefs for models.</p>
<p><strong>Target</strong>
For my LGBM I didnt use <strong>Demand ** as a target - instead I used **<em>Difference</em></strong> of Demand and Demand of 28 days ago - for tree-based model it`s a nice trick to work wih trends. </p>
<p><strong>Post-processing</strong>
No custom coefficients :)</p>
<p><strong>Features</strong>
Pretty standart, most of them can find in public notebooks.
In my CV worked pretty good ratios of rolling mean and median.</p>
<p><code>data['ratio_mean_60'] = data['rolling_mean_t60'] / data['rolling_median_t60']</code></p>
<p><strong>What didn`t work</strong>
- custom loss with WRMSSE gradient
- out of stock prediction (spent lots of time on it - didnt way right way)
- mean encodings
- hts-method with upper-level correction
- and lots of other ideas from previous competitions and public ideas</p>
<p>It was a really great journey working under this competition - learned lots of tricks as usual, somehow this competition reminded me a LANL competition with a huge shake-up and custom multipliers. </p>
<p>Big congratulations to winners and big thanks to @kyakovlev, @girmdshinsei, @sibmike which notebooks and ideas i included in my solution.</p>
<p>~0.03 - 0.05</p>
|
M5 Forecasting - Accuracy
|
59th place solution - there is nothing special
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: M5 Forecasting - Accuracy
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>First of all, I would like to express my sincere gratitude to Kaggle, University of Nicosia and Walmart for hosting the competition.
This competition was really amazing and fun and I learned a lot.</p>
<h2>Feature Engineering</h2>
<p>I used <a href="https://www.kaggle.com/kyakovlev/m5-simple-fe">M5 - Simple FE</a> datasets as baseline and added below featues.</p>
<ul>
<li>the day before holiday</li>
<li>the day after holiday</li>
<li>lag feature of sales - latest 28 days </li>
<li>rolling window aggregation feature of sales - sum, max, min and mean with rolling [ 7 14 30 60 ]</li>
<li>Average sales for 4 weeks going back every 7 days (feature of the day of the week)</li>
<li>Average sales for 8 weeks going back every 7 days (feature of the day of the week)</li>
<li>Average sales for 12 weeks going back every 7 days (feature of the day of the week)</li>
</ul>
<p>Just all. Quite simple.</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F1110061%2Ffcdc0559ad488bee843d3d3f683309f7%2Ffeature_importance.png?generation=1593670446657269&alt=media" alt=""></p>
<h2>Model</h2>
<p>Using only single LightGBM model.</p>
<p>My PC environment is ordinal standard PC spec with 16G memory and intel i5-3470 3.2GHz CPU (no GPU).
As reason of not sufficient memory I couldn't use whole datasets, I used train data set using March, April, May, June in 2011-2015 and all 2016 data.
I created model each 28 predict days and each 3 category (foods, hobby and household), finally I created total 28*3=84 models.</p>
<p>Final trained model included validation period data 4/25(d1914) to 5/22(d1941).</p>
<h2>Ensembling</h2>
<p>No ensemble. (single LightGBM model)</p>
<h2>Post-Processing</h2>
<p>I tried out of stock prediction as extracting all 10 stores or 9 stores that have continued sales 0 in the day before the forecast.
I couldn't determine how long out of stock continues, so I gave up out of stock prediction.
There were some out of stock items, I decided that FOODS_2_242 was out of stock, filled sales=0 and created a submission.</p>
<p>With this post-processing, score seems to be slightly improved to 0.58026 -> 0.57987.</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F1110061%2F4470decff7c1a1cbf51da08e38aebb35%2FFOODS_2_242_lack.png?generation=1593670444594244&alt=media" alt=""></p>
<p>As you can see my solution, there is nothing really special or new. I just followed Konstantin( <a href="/kyakovlev">@kyakovlev</a> )'s kernel and discussion. It was something like standing on the shoulder of giants and reaching out a bit more.</p>
<p>Thank you and congrats to all the winners!</p>
<p>...</p>
<p><a href="https://qiita.com/takaaki_inada/items/3f822737cf306a7bbce9">日本語版解法まとめ</a> </p>
<p>Yes. I update the description. Thank you for your review.</p>
|
M5 Forecasting - Accuracy
|
5th place solution
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: M5 Forecasting - Accuracy
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Hi guys, I would like to share my solution with you, </p>
<p>but first I would like to thank Kaggle, the hosts, and all participants, especially @kneroma and @kailex for their kernel contributions. In addition, thanks to the whole discussion about the magic multiplier led by the @kyakovlev kernels.</p>
<p><strong>1) The features:</strong></p>
<p>A) From the calendar:
I created features from the remaining days for the event. Each event would be a column, and the values in this column refer to the "strength" of the proximity of the event limited to 30.
Still in this matter, a new variable that would be the sum of all these "forces" was created, if this column had a high value, it would indicate that they would have one or more events nearby.
Also used some variables to indicate seasonality. For example, indicating how near the day is to the end of the month. Week of the year, day of the week...</p>
<p>B) Prices:
I decided to remove the current price of the items in the model. Instead, I calculated the percentage difference between the price of the week and the price of previous weeks, thus creating some columns related to that price difference. I figured that a fall or rise in price that week was going to make more sense for a more generalized prediction.</p>
<p>C) Historical series
Here, thanks to the @kkiller and @kxx kernels with the variables
['lag_7', 'lag_28', 'rmean_7_7', 'rmean_28_7', 'rmean_7_28', 'rmean_28_28']. </p>
<p>Also inserted some other variables like the item id and the store id as cat variables.</p>
<p><strong>2) The model</strong></p>
<p>I used an LGBM model with early stopping, and with Poisson objective, for each department, resulting in a total of 7 models. It made it easier for me not to burst the memory and be able to use more days from the past.
I also used the predicted value to predict the next (eg lag_7)</p>
<p><strong>3) Post-processing magic multipliers.</strong></p>
<p>A magic multiplier of ~1.03 really improved the result, but I was not confident on that.</p>
<p>So I went to analyze how the true values differed from the predicted values, for each store and department. And we have graphs like these:</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F2657722%2Fb7ab4696d212a626e80e415466d7f736%2F1.PNG?generation=1593826682424401&alt=media" alt=""></p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F2657722%2Ff6b446ac9535247f848a98874cf033ee%2F2.PNG?generation=1593826699867532&alt=media" alt=""></p>
<p>Some stores/departments showed the prediction "constantly below" (of course with a lot of noise) of the true value. And other stores/departments showed the prediction "constantly above" the true value. I then decided to create an average correction factor for each store/department, based on the last week (validation). And we have a matrix like this:</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F2657722%2F1f27c2fbb90bba19b7aa3b734a5b46c8%2F3.PNG?generation=1593826632224426&alt=media" alt=""></p>
<p>...</p>
<p>That is, ~ 0.92 represents a specific factor for FOODS_1/CA_1, because the true value was, on average, 92% of the predicted value to the validation set.</p>
<p>In this way, I imagined that the historical correction factors for the validation would behave similarly from the historical to the evaluation.</p>
<p>In summary for this item, instead of using a magic multiplier, I used a magic multiplier for each store/department. Here, I was not afraid of overfitting the result. It could be much worse, I could overfit a lot more by creating a factor for each item, but it would be too much. So, it was a compromise between creating just one magic multiplier for the entire result and one magic multiplier for each item.</p>
<p><strong>4) A simple diagram:</strong></p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F2657722%2F232d7d80e729f5e374499e74470aa883%2FUntitled%20Diagram.png?generation=1593830988541757&alt=media" alt=""></p>
<p>The solution in the public was far from winning, but the private score remained close to the public one.</p>
<p>Finally, I hope to be able to contribute more to the discussions of the next challenges. </p>
<p>I am very grateful to everyone for the great learning I was able to absorb in this competition, regardless of the result.</p>
<p>Thank you again</p>
<p>Hi <a href="/solomonxian">@solomonxian</a> , thank you for the question.</p>
<p>It is a triangle (an isosceles rectangle triangle)</p>
<p>30 days before the event gets the value of 0
29 days before the event gets the value of 1
28 days before the event gets the value of 2
...
2 days before the event gets the value of 28
1 day before the event gets the value of 29
the event day gets the value of 30</p>
<p>the day after the event, like the other common days, gets the value of 0</p>
<p>I didn't spend a lot of time thinking if that would be ideal, but that's how I did it. </p>
<p>However, I agree with you in the sense that we should think about how to deal with it in a more smooth way, and sometimes the days right after the events may be bad sales days (just guessing, depending on the department)</p>
|
M5 Forecasting - Accuracy
|
63rd place solution
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: M5 Forecasting - Accuracy
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thank you to all the participants.
We learned a lot from your discussions and notebooks.
Below is a summary of our model:</p>
<p><strong>Models</strong>
10 * 28 LGBM ([10 store_id] * [28 day-by-day]) </p>
<p><strong>Features</strong></p>
<ul>
<li><a href="https://www.kaggle.com/kyakovlev/m5-simple-fe">https://www.kaggle.com/kyakovlev/m5-simple-fe</a></li>
<li><p><a href="https://www.kaggle.com/kyakovlev/m5-lags-features">https://www.kaggle.com/kyakovlev/m5-lags-features</a>
But we didn't use the recursive features.</p></li>
<li><p>Target encoding of 8 groups by ordered time series:
<code>
['id'],['item_id'],['dept_id'],['cat_id'],['id','tm_dw'],['item_id','tm_dw'],['dept_id','tm_dw'],['cat_id','tm_dw']
</code>
We used the average of sales for 28 or 60 days as a feature for the next 28 days.
source code: <a href="https://www.kaggle.com/suuuuuu/m5-target-encoding">https://www.kaggle.com/suuuuuu/m5-target-encoding</a></p></li>
<li><p>Stacking - Binary prediction (sales = 0 or else) features by above features.
source code: <a href="https://www.kaggle.com/suuuuuu/binary-challenge-evaluation-ca-1-2">https://www.kaggle.com/suuuuuu/binary-challenge-evaluation-ca-1-2</a></p></li>
<li><p>Deviation from the day of the event.
source code: <a href="https://www.kaggle.com/suuuuuu/m5-event-lag">https://www.kaggle.com/suuuuuu/m5-event-lag</a></p></li>
<li><p>sales lag from 1 to 27 (day-by-day)</p></li>
</ul>
<p><strong>Objectives</strong></p>
<p>We used custom objectives. These were determined based on our metric below.</p>
<p>|store_id|objective|
|---|---|
|CA_1| tweedie (power = 1.1)
|CA_2| custom_asymmetric_train
|CA_3| tweedie (power = 1.2)
|CA_4| asymmetric_tweedie (p = 1.1, a = 1.2)
|TX_1| tweedie (power = 1.1)
|TX_2| tweedie (power = 1.1)
|TX_3| tweedie (power = 1.1)
|WI_1| asymmetric_tweedie (p = 1.08, a = 1.16)
|WI_2| asymmetric_tweedie (p = 1.1, a = 1.15)
|WI_3| asymmetric_tweedie (p = 1.06, a = 1.2)</p>
<p><code>
def custom_asymmetric_train(y_pred, y_true):
y_true = y_true.get_label()
a = 1.15
b = 1
residual = (y_true - y_pred).astype("float")
grad = np.where(residual &lt; 0, -2 * residual * b, -2 * residual * a)
hess = np.where(residual &lt; 0, 2 * b, 2 * a)
return grad, hess
</code></p>
<p>```
def asymmetric_tweedie(y_pred, y_true):
p = 1.1
a = 1.2
b = 1
y_true = y_true.get_label()
residual = (y_true - y_pred).astype("float")
grad = -y_true*np.exp(y_pred*(1-p))+np.exp(y_pred*(2-p))
grad = np.where(residual < 0,grad*b,grad*a)
hess = -(1-p)*y_true*np.exp(y_pred*(1-p))+(2-p)*np.exp(y_pred*(2-p))
hess = np.where(residual < 0,hess*b,hess*a)
return grad, hess</p>
<p>```</p>
<p><strong>Metrics and Validation</strong>
We defined WRMSSE for each store. The LGBM hyperparameters were tuned using this evaluation metric.
- Validation: [1884-1913] and [1914-1941]
- grid search by optuna
source code: <a href="https://www.kaggle.com/suuuuuu/m5-ca1-grid-final">https://www.kaggle.com/suuuuuu/m5-ca1-grid-final</a></p>
<p><strong>Final training</strong>
- train data: from 1 to 1941
- no early-stopping
- LGBM round : 300
- ensemble of num_iteration = 100, 200, and 300
- source code: <a href="https://www.kaggle.com/suuuuuu/m5-ca1-model-final">https://www.kaggle.com/suuuuuu/m5-ca1-model-final</a></p>
<p>Finally, we learned a lot from this competition and the community.
We want to make use of it in future competitions.
Thanks to all Kaggle community members.</p>
|
M5 Forecasting - Accuracy
|
7th place solution
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: M5 Forecasting - Accuracy
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>I learned a lot from the community in this competition, so I wanted share my solution and some learnings I had from the competition as well. </p>
<p>Before I go deeper, I wanted to first thank the hosts, Kaggle, and the community as a whole. I learned a lot from this experience and am glad to have done it. Credit also to these two notebooks where a lot of my inspiration came from:
* <a href="/kyakovlev">@kyakovlev</a> : <a href="https://www.kaggle.com/kyakovlev/m5-three-shades-of-dark-darker-magic">https://www.kaggle.com/kyakovlev/m5-three-shades-of-dark-darker-magic</a>
* <a href="/kneroma">@kneroma</a> : <a href="https://www.kaggle.com/kneroma/m5-forecast-v2-python">https://www.kaggle.com/kneroma/m5-forecast-v2-python</a></p>
<h1>Solution</h1>
<p>My solution itself is not too innovative, but how I got there might be interesting. One of the big things I learned from this competition is the importance of having a reliable and fast cross-validation method. Common with themes in other posts, I ended up finding that simpler was better. With the cross-validation, I pruned a lot of features that I found did not provide a large benefit to keep the model simpler.</p>
<h2>Algorithm</h2>
<p>Gradient boosting trees (LightGBM), one model per store</p>
<h2>Features</h2>
<ul>
<li>Item id, department id, category id</li>
<li>Price features: current price, price relative to past prices, statistics on the price (max, min, standard deviation, mean… etc.)</li>
<li>Sales features: recursive 7-day, 14-day lagged rolling means + 28-day lagged rolling means. No lagged rolling standard deviations</li>
<li>Date features: date attributes (e.g. month, year, is weekend, day of week, … etc.), nearest upcoming/past event name, event name 1, event name 2, SNAP, no event type</li>
</ul>
<h2>Cross-validation / hyperparameter optimization</h2>
<ul>
<li>It took me a while to come up with a cross-validation approach I was happy with, trying to balance accuracy and speed. I took the data for stores CA1, TX2, and WI3 to increase training speed, and used time periods d1550-d1577, d1858-d1885, d1886-d1913 as my cross-validation periods. For each period, I trained a model with all data before the period, and then used the models to predict the sales within the period.</li>
<li>I tested the sensitivity of the method by running it on the same model with different seeds to see how widely the scores varied by random chance.</li>
<li>Even with those optimizations, cross validation took a while: ~24 hours for 40 parameter sets</li>
<li>I tuned LightGBM parameters with <a href="https://github.com/hyperopt/hyperopt">hyperopt</a>.</li>
<li>A shoutout also to <a href="https://www.kaggle.com/c/m5-forecasting-accuracy/discussion/148273">this thread</a> for helping to improve LightGBM training speed by ~2x.</li>
</ul>
<h2>Things that I tried but did not include</h2>
<p>I think the following, if done better, may have helped. However, I found the benefit of these improvements to be marginal so opted not to use them for simplicity.
* Predicting overall sales for each day and scaling predictions accordingly. I did notice that if I could perfectly predict overall sales for each day, the scores would improve tremendously.
* Weighting data points
* Predicting number of dollars spent per item instead.
* Removing "out-of-stock" periods from the training dataset.</p>
<p>For those that are interested, I also wrote a quick <a href="https://medium.com/<a href=">@eugene</a>.c.tang/things-i-learned-from-my-first-kaggle-competition-362409a9f5b0?source=friends_link&sk=17e49797b631c13586350c308b4e5603">blog post on some high-level learnings.</p>
<p>Hope you might find some of these thoughts helpful and happy to answer any questions!</p>
<p>No problem! Would be interested in seeing if the difference was systematic v. due to chance.</p>
<p>1) Loss function: Tweedie with <code>tweedie_variance_power = 1.1</code>. I did not tune this parameter and just took the value presented in <a href="https://www.kaggle.com/kyakovlev/m5-three-shades-of-dark-darker-magic">https://www.kaggle.com/kyakovlev/m5-three-shades-of-dark-darker-magic</a></p>
<p>2) I trained one model per store (split by <code>store_id</code>) and used the entire time period available.</p>
<p>3) My mean WRMSSE CV score for the final model was 0.636 (it’s a little weird because I tried to scale the WRMSSE to account for the fact that I was calculating an WRMSSE for only 3 stores). These were the optimal parameters found by the hyperparameter tuning <code>{'learning_rate': 0.048550444824869955, 'max_bin': 140, 'min_child_samples': 14848, 'n_estimators': 462, 'num_leaves': 8192}</code>. </p>
<p>3b) Below are the results of some CV experiments. One thing I likely did wrong is that I did not do hyperparameter tuning after making an adjustment. (I started hyperparameter tuning after running these experiments).
* Feature selection: I hand-picked a set of features that I thought would do well, and then added/removed different set of features to test their performance.
* Training on “in-stock” items improved score by -0.009
* Training a model to predict overall sales and adjusting based on that made things worse by 0.022
* Weighting provided marginal improvement: -0.006, but made things worse for some other parameters I was trying, which made me trust less the reliability of the improvement.
* Total dollars provided marginal improvement: -0.010, but again made things worse for some other parameters I was trying.</p>
<p>4) Correct. My hunch is that magic numbers were overfit to the public leaderboard, so I did not use them.</p>
|
M5 Forecasting - Accuracy
|
A few thoughts - 24th Place
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: M5 Forecasting - Accuracy
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Like a few others I was one of those that benefited from the leaderboard shakeup. For reference I didn’t use any multipliers. My solution I think was relatively simply, being a combination of light gbm and a simple LSTM. The biggest benefit I found was in getting local WRMSSE working which allowed me to do a better job tuning and also where I found the biggest benefit in feature selection especially given the large number of features I’d engineered throughout the competition. </p>
<p>I think one of the challenges with this competition was the evaluation metric. While I did work with a custom objective function during training a lot of different approaches I tried often didn’t have the outcomes I expected when evaluating. </p>
<p>In the end I found my cross validation to be fairly consistent by the end and was close to the score I got on private LB. Incidentally my model would still perform poorly on the public leaderboard against some scores on there.</p>
<p>It would also be interesting to understand if the hosts actually picked this particular period for scoring on purpose or they were just arbitrary. Was there some nuances in this period that other forecasting methods have struggled with and that’s why they were selected?</p>
|
M5 Forecasting - Accuracy
|
An article about my solution for this competition.
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: M5 Forecasting - Accuracy
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>I am happy to share a few words about how I chose to handle the M5 competition by Kaggle.<br>
It was fun to take part in this competition, and it was also fun to write about it :) ~!</p>
<p>Also, I want to thank Kaggle for this competition :)<br>
<a href="https://avivlevi-815.medium.com/my-solution-for-the-m5-kaggle-competition-top-14-8f004c92a51" target="_blank">https://avivlevi-815.medium.com/my-solution-for-the-m5-kaggle-competition-top-14-8f004c92a51</a></p>
|
M5 Forecasting - Accuracy
|
From Public LB #3762 --> Private LB #80... How I got there
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: M5 Forecasting - Accuracy
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>When I started, I did not harbour much hopes of getting a good placing
Reasons:
1) Didn't fare well in past time series competitions (eg ASHRAE & Liverpool ion switching)
2) Many public kernels suggested "best solution" is LGBM + recursive prediction</p>
<p>What I did before 1 June:
1) Trying to replicate results of above kernels w/o much success (eg Three shades of Dark Magic)
2) Did not understand why Public LB score changed drastically from 1 submission to another</p>
<p>What happened after 1 June (evaluation set released):
a) uses fast.ai Tabular model, each run only 1-2 hours (no more LGBM)
loss fn = Poisson Loss; Also tried MAE & MSE but Poisson still best</p>
<p>b) no more recursive prediction (need too much run time; prediction errors can grow with time)</p>
<p>c) Analysis --> thanks to Vopani kernel ( <a href="https://www.kaggle.com/rohanrao/m5-anatomy-of-the-public-lb">https://www.kaggle.com/rohanrao/m5-anatomy-of-the-public-lb</a> ), I was able to visualize where my model excels & where it is poor
--> most errors from lowest level (due to spike demands followed by long periods of '0')
I just optimize for mean of these fluctuating sales, ensure not too much overfitting
--> my model forecasts at higher levels are quite good </p>
<p>d) Used different starting days for different runs; start_train=700, 950, 1200, 1350, 1500
Averaging over these runs help to improve score by about 0.1</p>
<p>e) Tried Magic Number (multiplier) but finds best score obtained w/o magic !</p>
<p>f) Feature Engr : Lag, roll, window features ideas from Konstantin, but with diff lags / window size selected (since I don't need recursive predictions)</p>
<p>Overall, I think fast.ai Tabular model helps me avoid overfitting at lowest level. Averaging over several runs (start day not too far from forecast dates optimal ~1-3 years earlier) helps alot !</p>
<p>With this competition, I earned my 2nd Silver & becomes Expert in Competitions ;-)</p>
<p>For those interested, my kernel:
<a href="https://www.kaggle.com/sidneyng/k-m5-final-public/output?scriptVersionId=37866057">https://www.kaggle.com/sidneyng/k-m5-final-public/output?scriptVersionId=37866057</a></p>
<p>Hi, my kernel : <a href="https://www.kaggle.com/sidneyng/k-m5-final-public/output?scriptVersionId=37866057">https://www.kaggle.com/sidneyng/k-m5-final-public/output?scriptVersionId=37866057</a>
Pls take a look & upvote if you find useful 8-)</p>
|
M5 Forecasting - Accuracy
|
Group k-fold works (102nd solution)
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: M5 Forecasting - Accuracy
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Code: <a href="https://github.com/MitsuruFujiwara/M5-Forecasting-Accuracy">https://github.com/MitsuruFujiwara/M5-Forecasting-Accuracy</a></p>
<p>Group k-fold with group=year+month works both in public & private.</p>
<p>I prepared 4 models with different cv strategies (TS or group) and different data split (by category or by week or no split). Finally, I selected blending of them as final submission.</p>
<p>The scores of individual models are as below.</p>
<p>|name|cv|split|cv score|weight|private|
|:---:|:---:|:---:|:---:|:---:|:---:|
|Weekly Group|Group|Week|0.58741|0.4175|0.57412|
|Weekly TS|TS|Week|0.60825|0.2320|0.60082|
|Category Group|Group|Category|0.60203|0.2052|0.54479|
|No split Group|Group|-|0.58963|0.1732|0.58869|
|Blend|-|-|0.56715|-|0.60101|</p>
|
M5 Forecasting - Accuracy
|
My solution, and yet another magic multiplier story..
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: M5 Forecasting - Accuracy
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>I started this competition pretty late, after the validation set labels were released, so I relied entirely on my own CV, which comprised of backtesting on a selection of 7 X 28-days windows, including recent windows, as well as windows in the same date range as the private leaderboard period from previous years (May/June 2015 and 2014).</p>
<p>The model was a day-by-day GBT model, 1 model per each forecast horizon day. As discussed in several threads (e.g. <a href="https://www.kaggle.com/c/m5-forecasting-accuracy/discussion/151339">here</a>), as well as [1], this has the advantage over recursive models, of not amplifying model bias in subsequent horizon days (at the cost of higher variance between different days). A single model was trained for all data slices (store, state, etc), to maximize cross-learning, especially since many individual item-store series were quite intermittent, as many people have noticed.</p>
<p>Feature-wise, I used some of the usual suspects such as:</p>
<ul>
<li>moving window statistics (avg, median, std, skew, kurt, quantiles) on different lags (7, 14, 30, 60, 180 days)</li>
<li>seasonal lags and statistics, for different seasonalities and lengths (same day-of-year, day-of-month, day-of-week)</li>
<li>for holidays, besides categorical variables, I added a continuous "days to" variable per each holiday (which became positive after the holiday passes, and was bounded to 28 days around the holiday), assuming that sales may be influenced pre-/post- holidays (e.g. Christmas shopping etc). Perhaps as expected, looking at feature importance shows that the importance of the "days to" feature varies widely, from moderately high (e.g. for LaborDay, Easter, and Chanukah) to very low (President's Day, Cinco De Mayo etc). This may mean simply that consumer behavior is different for each holiday, or that effects on sales for some holidays are already encoded efficiently by the day-of-year feature</li>
<li>categorical variables, as well as combinations thereof (e.g. state_id + dept_id) were target encoded, with no smoothing applied (since enough examples were available in each category in this dataset). Only high cardinality categorical variables were target encoded (e.g. state_id was not). Among these, the item_id|store_id encoding was the most successful</li>
<li>price and derived statistics on it, as proposed Konstantin's great <a href="https://www.kaggle.com/kyakovlev/m5-simple-fe">kernel</a>, among which price_momentum proved to be very successful (on average, my top 5 features were store_id, dept_id, day-of-week, price momentum and the holiday category).</li>
<li>for dealing with long "out of stock" gaps (around 20% of the data as discussed <a href="https://www.kaggle.com/c/m5-forecasting-accuracy/discussion/138085#790628">here</a> I tried several approaches, including removing them (and all examples affected indirectly by gaps via lags or seasonality, e.g. days right after, or in weeks after an out-of-stock gap), as well as inputing values into these gaps (using seasonal weighted averages of past days-of-week/month/year).
Perhaps surprisingly, inputation actually hurt CV scores, and gap removal only helped moderately. This is possibly due to not using a gap predictor model to correct for non-gap bias at evaluation time. Another approach, which I did not have time to try, could have been imputing past gaps using my own model (basically pseudo-labeling past gaps).</li>
</ul>
<p>Finally, I implemented some post-processing (aka "magic"), which in retrospect was a veery bad idea, and the source of a painful lesson :) On the assumption that predictions from GBT trees will basically be based on past sales of similar items on past windows, as clustered by the model (I trained on 830 past days from the target window), I assumed that the model must be biased towards lower values, which I attempted to correct based on a per-item yearly trend estimation (using only past data, aggregated per-item and per-department), basically a per-item "magic multiplier" vector. While this seemed to work well in my CV for the windows I looked at, it was sort of a last moment addition and I didn't have time to properly tune and test the trend generator.
After some deliberation, I decided to submit the postprocessed version rather than the raw one (as you know, we were allowed a single submission in this comp), which gave me a score of 0.72667 on the private LB. This morning, I did a late submission with the same exact output, but with the "magic" removed on the private dataset part, which would have given me a private LB score of 0.58797 (or a jump of 614 places on the LB from top 13% to top 1,2%, or silver zone). Ouch!:</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F3220715%2Fbcad4d92dec187860bb1c8d35887b6d6%2Fsubs.png?generation=1593611584483631&alt=media" alt=""></p>
<p>Anyway, I guess the main lesson here, which many people seem to also have run into in this competition, is stay clear of postprocessing for non-stationary data, especially if not properly tuned / tested ;) I suppose a better per-item trend estimation, or item clustering better than per department might have worked if properly validated..</p>
<p>I used LGBM (1 per horizon day), with a 'tweedie' objective, RMSE metric, max depth of 7, 1400 estimators, and no lambda regularization or feature subsampling, which was tuned by CV.</p>
<p>Kudos to everyone that contributed to this comp, it was definitely a fun one!</p>
<p>[1] "Recursive and direct multi-step forecasting: the best of both worlds", Souhaib Ben Taieb and Rob J Hyndman</p>
|
M5 Forecasting - Accuracy
|
Rank 172, sharing code for the first time.
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: M5 Forecasting - Accuracy
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Referring to the code of Konstantin Yakovlev , the holiday features of each store are made based on Konstantin Yakovlev, and the final 28 day forecast is obtained by weighted fusion of by store and by state.<br>
Code link: <a href="https://github.com/Greak-1124/Kaggle_M5_Forecasting_Accuracy_Pro" target="_blank">https://github.com/Greak-1124/Kaggle_M5_Forecasting_Accuracy_Pro</a></p>
|
M5 Forecasting - Accuracy
|
Silver Medal Solution
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: M5 Forecasting - Accuracy
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>This competition is a weird one. I have seen kernels that baffle me, such as picking random samples as validation, using magic multipliers, etc.. I said screw it and trained a LightGBM with these params:</p>
<p><code>
params = {
'objective': 'poisson',
'num_iterations': 700,
'num_leaves': 80, <br>
'min_data_in_leaf': 100, <br>
'metric': 'rmse',
'learning_rate': 0.1,
'feature_fraction': 0.65,
'bagging_fraction': 0.87,
'bagging_freq': 19,
'num_threads': 16,
'seed': 69
}
</code></p>
<p>I used all labelled data to train (without train-test split).</p>
<p>That's it.</p>
<p>Of course there are much better solutions and I can't wait to see them, but I think my solution shows that it is important to not overfit, and you definitely don't need to use any magic multipliers =).</p>
<p>Thank you. I think for any competition, the most important thing is to create a good validation set. For time series, I simply put the sales from d_1914 to d_1941 as validation. I did not iterate many hyperparameters as training takes a long time since it is a big dataset. But based on LightGBM's docs, the most important parameters are <code>num_leaves</code> and <code>min_data_in_leaf</code>. So I only tuned them.</p>
<p>I however did not too very well on the public leaderboard. Only got around 0.50. A lot of kernels that dominate the public LB use magic multipliers that I suspected would overfit. Hence I did not follow their methods.</p>
<p>Congrats to you too!</p>
<p>I just use the features created using some of the public kernels.</p>
<p>Your <code>min_data_in_leaf</code> is definitely too high. From <a href="https://lightgbm.readthedocs.io/en/latest/Parameters-Tuning.html">LightGBM docs</a>, a large value will cause underfitting.</p>
|
M5 Forecasting - Accuracy
|
Top 1% solution (28th)
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: M5 Forecasting - Accuracy
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>exactly!</p>
<p>Glad to share with you all!</p>
<p>Using a walk-forward validation, each fold took around 15-20 min, and I had 4 folds validating a period of 14 days. WRMSSE during training wasn't consistent so I ignored it and would just look at it in the end, after predictions.</p>
<p>I changed my strategy a few days before the deadline so I ended up using the same features for all stores. So there's a lot of room for improvement in this area.</p>
<p>Besides trying to get a distribution closer to the evaluation set, the decision was also based on my computational power.</p>
<p>So I thought about sharing some points of my strategy with you guys.</p>
<p>I decided not to use any multipliers. I'm not a big fan of it and prefer to work on generalizing my model by working on feature engineering and tuning hyper parameters.</p>
<h2>Feature Engineering</h2>
<p>I used some ideas published by @kyakovlev at <a href="https://www.kaggle.com/kyakovlev/m5-three-shades-of-dark-darker-magic">https://www.kaggle.com/kyakovlev/m5-three-shades-of-dark-darker-magic</a> such as:
- rolling mean and std - lag [ 28 ] rolling [ 7 14 30 60 180 ]
- rolling mean - lag [ 1 7 14 30 ] rolling [ 7 14 30 60]
- mean and std target encoding for 'item id', 'cat id' and 'dept id'</p>
<p>From <a href="https://www.kaggle.com/sibmike/m5-out-of-stock-feature-640x-faster">https://www.kaggle.com/sibmike/m5-out-of-stock-feature-640x-faster</a> I took
- 'gap e log10' and 'sale prob' and obtained its rolling mean with lag 28.</p>
<p>I have also used features such as last 2 digits of 'sell price', 'days from last price change', 'sell price ratio', 'days from last sale', 'release week', 'weeks from release', 'cluster', 'ADI rolling mean' and target encoding taking 'weekend', 'snap' and 'event' + 'preholidays' into account. </p>
<p>There are other features as well that don't need mentioning as they were basic ones. I also fixed some outliers I've found and others mentioned at <a href="https://www.kaggle.com/c/m5-forecasting-accuracy/discussion/161718">https://www.kaggle.com/c/m5-forecasting-accuracy/discussion/161718</a> .</p>
<p>About the data, I actually calculated the features using the whole dataset since 2011 except encoding features where I set the lowest date to 2013.</p>
<h2>Model</h2>
<p>I used lightgbm and created models for each store, departing from @kyakovlev s model, and tuning it to my needs. </p>
<p>I trained using a walk-forward cross validation I adapted from <a href="https://towardsdatascience.com/time-based-cross-validation-d259b13d42b8">https://towardsdatascience.com/time-based-cross-validation-d259b13d42b8</a></p>
<h2>My thoughts</h2>
<p>I think my solution can be improved, a lot. By Sunday, my model started to behave very strangely and I decided to rebuild everything from zero, so I didn't have much time to analyze which features were indeed good or not. I cut off a bunch of features, and didn't have time to test Bayesian encoding and other ideas, which I'll do now with more calm.</p>
<p>Hope this helps you all understand some approaches of your fellow competitors, although we saw that the result of this competition could have also been met simply with 'some' multipliers. A big thanks to those that shared their ideas and helped to improve my model.</p>
<p>Let me know if I forgot to mention anyone's idea, and I'll give the proper credit/ referencing.</p>
|
M5 Forecasting - Accuracy
|
Top 3% simple solution
|
Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
|
<|system|>You can successfully explain and teach others topics and concepts from Kaggle competition solution write-ups. You are a highly talented data scientist who has shown exceptional performance in this data-science Kaggle competition: M5 Forecasting - Accuracy
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h3>Code is here: <a href="https://github.com/btrotta/kaggle-m5">https://github.com/btrotta/kaggle-m5</a></h3>
<p>The code is quite short (<300 lines) and uses only fairly basic features in a LightGBM model. </p>
<h3>Modelling approach</h3>
<p>I didn't use any "magic" adjustment factors. I also didn't use any custom metrics, just rmse. I think the evaluation metric is noisy, especially for features with short history, because random fluctuations in the day-to-day sales history can cause products to be weighted very differently even if they have similar long-term average. So I thought trying to optimise for this metric would lead to overfitting.</p>
<p>Rather than using a recursive approach, I trained separate models for each day of the forecasting horizon, and for each n I recalculated the features so that the n-day-ahead model is trained on data that has been lagged by n days. Based on discussions in the forum (specifically, this post <a href="https://www.kaggle.com/c/m5-forecasting-accuracy/discussion/144067#">https://www.kaggle.com/c/m5-forecasting-accuracy/discussion/144067#</a>), I decided that the recursive approach was only performing well on the training period by coincidence.</p>
<p>I noticed that in the test period, there are very few new products (i.e. products that have not been sold before the test period). So I excluded from the training set rows before the first sale date of a product in a store, and also excluded these rows when calculating aggregate features.</p>
<p>I used 3 years of data to calculate the features (to reduce noise and capture seasonal trends) and 1 year to actually train the model. I excluded December from the training period because of the effect of Christmas.</p>
<h3>Features</h3>
<p>The feature engineering is mainly common sense: as well as the obvious date features, just lagged sales at various
levels of aggregation. For the aggregated features, I took the mean of sales at 3 levels of aggregation:
- item and store
- item (aggregated over all stores)
- dept id and store id</p>
<p>The idea of this was that the higher levels of aggregation provide a less noisy view of item-level and store-level trends.</p>
<p>Specifically, the features are:
- dept id and store id (categorical)
- day of week, month, snap (i.e. is today a snap day for the current store)
- days since product first sold in that store
- price relative to price 1 week and 2 weeks ago
- item-level holiday adjustment factor (for each holiday and each item, calculate the average change in sales in the week
leading up to the holiday and the holiday itself)
- long-term mean and variance of sales at the 3 levels of aggregation
- long-term mean and variance of sales at the 3 levels of aggregation for each day of week
- average of last 7, 14, and 28 days of sales at the 3 levels of aggregation
- average sales lagged 1-7 days at the 3 levels of aggregation</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.