Title of Competition stringclasses 168 values | Title of Writeup stringlengths 9 139 | User stringclasses 1 value | Writeup stringlengths 419 61.5k |
|---|---|---|---|
Riiid Answer Correctness Prediction | Only LGBMs. Private 71st LB 0.800 | 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: Riiid Answer Correctness Prediction
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h1>Good competition!</h1>
<p>First of all, I'd like to thank the organizers and Kaggle for offering this wonderful competition. The amount of data and the inference API made this competition more challenging, interesting, and practical.</p>
<h1>LGBM only solution</h1>
<p>I tried several models including LightGBM, CatBoost, and SAKT. In December, I decided to use only LGBM models mainly because of my limited GPU resource. (I bet some teams used only Kaggle GPUs and made better models.)</p>
<h1>Stack</h1>
<p>My final model is a stack of LGBM models.</p>
<h2>Level 0</h2>
<p>The first level of the stack is an LGBM model with typical features such as timestamp lag, rolling mean accuracy, and whether a user saw the same quiz before. I also created a custom quiz ranking.</p>
<p>The level 0 model itself trained with half of the data scored the public LB 0.791.</p>
<h2>Level 1</h2>
<p>In addition to the same features as level 0, I added</p>
<ul>
<li>level 0 lgbm prediction</li>
<li>previous level 0 lgbm prediction error</li>
<li>previous 10 records of these features + some features</li>
</ul>
<p>The level 1 model trained with the other half of the data scored the public LB 0.798. I created two level 1 models changing the number of leaves 256 and 500. Averaging them gave me LB 0.799.</p>
<p>The private score was 0.8000.</p>
<h2>Wish I could do</h2>
<p>As I couldn't optimize the memory usage, there are several things I couldn't include in the solution.</p>
<p>For example, the quiz history for each user such as has_see_this_quiz_before, has_answered_this_quiz_before, how_long_has_past_since_last_saw_this_quiz. To save memory, I was using 'content_id' mod p, where I took p=409. Of course, this introduces some noise. There were discussions to use Sqlite3 but I didn't give it a try. In my final model, I didn't use mod p but instead, I only keep track with saw_this_quiz_before and how_long_has_past_since_last_saw_this_quiz features. My notebook used almost all 16GB of memory. If I added one more model for an ensemble, it gave me a memory error.</p>
<h1>Finally</h1>
<p>I like this challenging competition. It not only requires data science skills but also engineering skills to make a model work at inference. I look forward to learning new things from your solutions! If you have questions or comments, please leave a comment below!</p>
<p><strong>Thank you for reading!</strong></p> |
RSNA STR Pulmonary Embolism Detection | 18th 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: RSNA STR Pulmonary Embolism Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p><em>I am actually quite surprised I was able to do this well in the competition, I joined way too late and trained very few models. I only had one selected submission that luckily didn't time out. It is a 5-fold efficientnet-b3 followed by a 5-fold sequential model based on its features.</em></p>
<h3>Introduction</h3>
<p>My solution consists of a two steps pipeline, similarly to the overpowered baseline :</p>
<ul>
<li>Image level efficientnet-b3, trained to classify whether the image has PE. This model is then used to extract features for each slice of the CT scan.</li>
<li>A sequential is trained on the features extracted by the CNN, it predicts both the image and exam level labels, and directly optimizes the competition metric.</li>
</ul>
<p>I joined the competition 9 days before the end, with the overall motivation of doing something similar to the winners of the previous RSNA competition. <br>
I was able to quickly build the CNN pipeline, and started training a bunch some models. The issue was that those models would be really long to train on my hardware (1x RTX 21080Ti), so I had to improvise.</p>
<p>Then, it was about quickly engineering the second part of the pipeline and the inference code, which was far from easy. </p>
<p>Shortly after I joined, the overly powerful baseline was released. I did not end up really using any of the components of it, but it was an additional motivation for me to keep pushing.<br>
I was able to come up with my first submission one day before the deadline, which <em>somehow</em> scored 23rd on the public leaderboard. </p>
<h3>Data</h3>
<p>As I could not fit the 900 Gb dataset on my computer, I solely relied on the <a href="https://www.kaggle.com/vaillant/rsna-str-pe-detection-jpeg-256" target="_blank">256x256 jpgs</a> extracted by <a href="https://www.kaggle.com/vaillant" target="_blank">@vaillant</a>.<br>
Thanks a lot for making it possible for people like me to join the competition.</p>
<p>I therefore didn't experiment at all with the windowing, and simply loading the data takes a huge part of my runtime.</p>
<h3>First level : Convolutional Neural Networks</h3>
<h4>Undersampling</h4>
<p>The issue with 2D images constructed from CT scans is that images are very similar. Therefore it makes sense not to use every slice per patient. <br>
As there is about 400 slices per patient on average, one epoch would take ages and this is not a path I wanted to go. <br>
Therefore, I only used 30 images per patient at each epoch, this is done using a custom sampler. </p>
<p>Once this was done, I was able to train the models for 20 epochs in approximately 9 hours, using a 5-fold grouped by patient validation.</p>
<h4>Models</h4>
<p>Models were trained as part of a classical binary classification problem, using the binary cross-entropy<br>
First experiments were conducted with a ResNeXt-50 model as it is usually a reliable baseline. <br>
I then tried to switch to a bigger ResNext-101, but results were not bigger so I quickly gave up with big architectures.<br>
The last model I trained is an efficientnet-b3, which was chosen because a batch size of 32 could fit on my GPU. <br>
It performed slightly better so I sticked with this model, and I had no time left to train other models.</p>
<p>The efficientnet was trained for 15 epochs using a linear scheduled learning rate with 0.05 warmup proportion. </p>
<h4>Augmentations</h4>
<pre><code>- albu.HorizontalFlip(p=0.5)
- albu.VerticalFlip(p=0.5)
- albu.ShiftScaleRotate(shift_limit=0.1, rotate_limit=45, p=0.5)
- albu.OneOf([albu.RandomGamma(always_apply=True), albu.RandomBrightnessContrast(always_apply=True),], p=0.5)
- albu.ElasticTransform(alpha=1, sigma=5, alpha_affine=10, border_mode=cv2.BORDER_CONSTANT, p=0.5)
</code></pre>
<h3>Second Level</h3>
<h4>Model</h4>
<p>The model I used is a MLP + BidiLSTM one that predicts both the image and exam targets using the CNN extracted features as input. <br>
Two 2-layer classifiers are plugged on the concatenation of the output of the MLP and of the LSTM.<br>
I used the concatenation of average and max pooling for the exam level targets.<br>
In addition, multi-sample dropout was used for improved convergence. </p>
<h4>Training</h4>
<p>The model was trained using the loss function that matches the metric. <br>
I also used stochastic weighted averaging for the last few epochs, once again to have a bit more robustness.<br>
A single epoch took approximately a minute. </p>
<p>The validation scheme is a normal 5-fold, and my CV scores were quite close to the 0.179 score I had on the public LB.</p>
<h3>Inference</h3>
<p>My inference code is available here : <a href="https://www.kaggle.com/theoviel/pe-inference-2" target="_blank">https://www.kaggle.com/theoviel/pe-inference-2</a><br>
I used clipping to make sure the label assignment rules were respected, which dropped my score of approximately <code>0.003</code>.</p>
<h3>Final words</h3>
<p>Congratz to the winners, I'm pretty sure my solution is nowhere near what the top 10 has come up with and I'm really glad I was able to finish 18th. I wanted to tackle a medical imaging challenge for a long time but was always hesitating because of the dataset sizes.</p>
<p>Hopefully next time I don't procrastinate too much and join a bit earlier, I'm pretty sure I'll benefit a lot from teaming up with people and spending more time experimenting.</p>
<p>Also, the code is available on <strong>GitHub</strong>, although I still have some cleaning to do, and the ReadMe to complete : <a href="https://github.com/TheoViel/kaggle_pulmonary_embolism_detection" target="_blank">https://github.com/TheoViel/kaggle_pulmonary_embolism_detection</a></p>
<p>Thanks for reading ! </p> |
Riiid Answer Correctness Prediction | 76th Place Solution | Minimal SAINT+ 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: Riiid Answer Correctness Prediction
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks to the organizers of this very interesting and difficult competition. Congratulations to all the winners. I have learned a lot in this competition. I am not a novice myself but not an expert either. This competition had some of the best discussion threads I could ask for. 2 days back I wasn't sure if my team is even gonna get a medal let alone in the top 100. I should say it is all thanks to the simple SAINT+ model we have build and the efforts of my teammates <a href="https://www.kaggle.com/vishwajeet993511" target="_blank">@vishwajeet993511</a> and <a href="https://www.kaggle.com/padma3" target="_blank">@padma3</a>. We are calling our model minimal because this is the first version we could come up with. Didn't get to try any hyperparameter tuning due to the constraint of time and computation power.</p>
<h2>SAINT+</h2>
<h3>Encoder</h3>
<p>We used the following features in the encoder model:</p>
<ul>
<li><code>question_id</code>: Embedding: 0 for padding</li>
<li><code>part_id</code>: Embedding: 0 for padding</li>
<li><code>correct_answer</code>: Embedding: 0 for padding. we thought that by giving both questions actual answers and the user's previous answers, the model should be able to come with a pattern and improve the prediction accuracy.</li>
<li><code>lsi_id</code>: Embedding: 0 for padding. I took lsi tags from <a href="https://www.kaggle.com/gaozhanfire/riiid-lgbm-val-0-788-offline-and-lsimodel-updated" target="_blank">this popular notebook</a>. </li>
<li><code>question_accuracy</code>: Linear: This and the below features are adding value in LightGBM. Giving the transformer model this info might have also helped. This is the mean value of accuracy for the question_id.</li>
<li><code>question_elapsed</code>: Linear: Quantile Transformed (Normal, 100 quantiles). Large Inputs to Neural Networks make it hard to converge. From my previous competition (MoA), I understood this much, so used it here. I can confirm that the convergence was faster. Could have tried bucketing as specified in the paper but didn't get time. This is the mean value of elapsed time for the question_id.</li>
<li><code>question_lagtime</code>: Linear. Quantile Transformed (Normal, 100 quantiles). I have discussed this <a href="https://www.kaggle.com/c/riiid-test-answer-prediction/discussion/209303" target="_blank">in this thread</a>. This is the mean value of lagtime for the question_id.</li>
<li><code>part_accuracy</code>: Linear</li>
<li><code>lsi_accuracy</code>: Linear</li>
</ul>
<p>We take to add the embedding above and send it to the <a href="https://pytorch.org/docs/stable/generated/torch.nn.Transformer.html" target="_blank">transformer model</a> as src input.</p>
<h3>Decoder</h3>
<p>We used the following features in the decoder model:</p>
<ul>
<li><code>responses</code>: Embedding: 0/1 feature. Shifted back by 1 interaction. I had also tried the way SAKT encodes responses but it wasn't optimal for me.</li>
<li><code>user_answer</code>: Embedding. Shifted back by 1 interaction.</li>
<li><code>prior_question_had_explanation</code>: Embedding. </li>
<li><code>elapsed_time</code>: Linear: Quantile Transformed (Normal, 100 quantiles).</li>
<li><code>lagtime</code>: Linear: Quantile Transformed (Normal, 100 quantiles).</li>
</ul>
<p>We take to add the embedding above and send it to the transformer model as tgt input.</p>
<h3>Masking</h3>
<ul>
<li>Masking is very important for transformer models. A lot of people have posted an AUC of 1.0. This is due to bad masking. I have discussed masking <a href="https://www.kaggle.com/c/riiid-test-answer-prediction/discussion/209303" target="_blank">in this thread</a>.</li>
<li>Should have used future masking for encoder and task_container_id based masking for the decoder.</li>
<li>1 thing I would like to highlight is that, look for the dtype of masking. Changing from bool to float makes inverses the mask. This created a lot of pain for me. </li>
</ul>
<h3>Parameters</h3>
<p>MAX_SEQ = 180<br>
NUM_ENCODER_LAYERS = 2<br>
NUM_DECODER_LAYERS = 2<br>
EMBED_SIZE = D_MODEL = 512<br>
BATCH_SIZE = 128<br>
DROPOUT = 0.1<br>
TEST_SIZE = 0.1<br>
LEARNING_RATE = 2e-4<br>
EPOCHS = 20<br>
EARLY_STOPPING_ROUNDS = 3</p>
<p>We tried out embedding sizes of 128 and 256. They were good but increasing the size helped us. Initially, we were using a higher learning rate, but the results were not optimal.</p>
<h3>Training</h3>
<ul>
<li>We understood that training a transformer model is not easy. The learning rate, optimizer, and scheduler are very important. Try to use a small learning rate with Adam optimizer or a variant of it. Initially we used <a href="https://pytorch.org/docs/stable/optim.html#torch.optim.lr_scheduler.OneCycleLR" target="_blank">OneCycleLR</a> but we shifted to <a href="https://pytorch.org/docs/stable/optim.html#torch.optim.lr_scheduler.CosineAnnealingWarmRestarts" target="_blank">CosineAnnealingWarmRestarts</a></li>
<li>We were constrained by the Kaggle GPUs. Just training the model 4 times was enough to complete a week of our GPU quota.</li>
<li>Training each model took around 20-30 minutes per epoch. 5 to 6 hours in total.</li>
<li>We weren't able to reach early stopping in our best model. </li>
<li>I discussed debugging my model <a href="https://www.kaggle.com/c/riiid-test-answer-prediction/discussion/209303" target="_blank">in this thread</a>.</li>
<li>The single model gives CV 0.792, Public 0.793 and <strong>Private 0.795</strong></li>
<li>If we had time, we wanted to do <a href="https://www.kaggle.com/c/riiid-test-answer-prediction/discussion/209633" target="_blank">pretraining of SAINT+</a> with the next question prediction task. </li>
</ul>
<h2>Ensemble</h2>
<ul>
<li>We had our LightGBM pipeline ready but weren't able to spend training LightGBM models. Our features are very basic. In the end, I used the public popular LightGBM model. 1 change we did is that instead of using the first x million data as input, we used the last 20/30 million rows. Since the test data immediately start from the end of the train data, it makes sense to use the last part instead of the first. </li>
<li>It gave us a boost of 0.004 to the SAINT+ model we had.</li>
<li>We also tried to use ELO and FTRL models but they were getting 0 weights in our bagging experiments we did on the last day.</li>
<li>One thing we missed is that we should have used my SAKT model in the ensemble. But we weren't sure if it could have added value as it is very similar to SAINT.</li>
</ul>
<h2>Final Words</h2>
<ul>
<li>Thanks to all the people who were sharing good notebooks and sharing their ideas in the discussion forum. Even if I hadn't got a medal, I would have been happy with the things I learned in this competition. </li>
<li>For the next tabular competition, I would like to team up with other competitors who are good at building Boosting Models. I am pretty bad at feature engineering for LightGBM kind of models. I want to learn it. </li>
<li>I will be uploading my code to GitHub. Once I have done this, I will add the link.</li>
<li>I will be becoming a <strong>Kaggle Expert</strong>. Would like to try for a GOLD medal in the next one 😆. Kaggle Master, here I come.</li>
<li>Thanks a lot to everyone who participated. This is a good experience. </li>
</ul>
<p>(edited)</p> |
Google Research Football with Manchester City F.C. | SaltyFish: Current 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: Google Research Football with Manchester City F.C.
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>It has been a great pleasure to join this football competition on Kaggle! We thank the <strong>Kaggle team</strong>, <strong>Manchester City</strong>, and <strong>Google research</strong> for the effort of making this happen! It seems that the gfootball team launched this competition in early 2020 and was intended to hold the final on ICML. Unfortunately, it is a tough year…… and we hope everybody is okay. Back to the competition, we also wanna thank all the participants, and it is you guys that make this competition wonderful and exciting! Special thanks to <strong>Wekick</strong>, your agents are really impressive and we also learned a lot from you.</p>
<h3>Summary</h3>
<p>Generally speaking, we train our agents through <strong>reinforcement learning</strong> by integrating <strong>PVE</strong> and <strong>Selfplay</strong>. Under <strong>limited computation resources</strong>, it is hard for the agents to learn from scratch (selfplay) in such a difficult environment (long-time horizon and sparse reward). By first training against the easy bot (difficulty_level = 0.05) and then the hard bot (difficulty_level = 1.0) until convergence, our agents get some clue on offense (e.g., dribbling the ball from backcourt to frontcourt, shooting skill). The selfplay phase then enables the agents to learn defense skills and further enhances the offense skill by learning passing skills. Let's get into some details.</p>
<h3>Algorithm</h3>
<p>We use distributed IMPALA implemented in our framework <strong>RLEase</strong>. RLEase is a highly efficient reinforcement learning based library developed by <a href="https://fuxi.163.com/en/" target="_blank">Netease Fuxi Lab</a>, which both incorporates state-of-the-art algorithms (such as IMPALA, APEX-rainbow, PPO, VDN, QMIX, etc.) and supports distributed training, models' auto testing, imitation learning and offers an easy API to incorporate new game environments. The framework looks like this:<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F939404%2Fa38228598d92a6254426204c2f03b026%2FRLease_struc.png?generation=1607673598249995&alt=media" alt=""></p>
<h3>Feature</h3>
<p>We first tried the simple115 wrapper that is mostly based on absolute values, which turned out to be lacking generalization capabilities. Then we extended it to the multi-head vector input by adding relative information and grouping related features into one head. Besides, <strong>surgery</strong> is also used to add extra features since training from the very beginning is both costly and not feasible under limited resources, just like what <a href="https://openai.com/projects/five/" target="_blank">OpenAI Five</a> did. The figure below shows what the multi-head vector inputs look like, where the blue columns represent the original input and the red columns and texts represent the surgery part.<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F939404%2Ffacb024666627b89576cfb62618efe2d%2Fmulti_head_vec.png?generation=1607668154777146&alt=media" alt=""></p>
<h3>Network</h3>
<p>We use several fully-connected layers. See Figure below:<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F939404%2F892538fb2739d7d96dd4059fc8e4be87%2Fnetwork.png?generation=1607667587785648&alt=media" alt=""></p>
<h3>Action</h3>
<p><br>We use different action sets for the algorithm in different 'ball_owned_team' modes (i.e., 0, 1, and -1). The main purpose is to ignore the unnecessary actions and reduce the exploration space. For example, when one player of our team has the ball, there is no need to choose the SLIDING action. For each 'ball_owned_team' mode, we simply generate a corresponding legal/illegal mask vector to indicate which of the 19 actions can be or cannot be taken. The output of the policy network (i.e., the probability of taking each action) will be updated according to the mask vector. We list the illegal actions in each 'ball_owned_team' mode as follows:<br>
<em>ball_owned_team</em> = 0: SLIDING<br>
<em>ball_owned_team</em> = 1: LONG_PASS, HIGH_PASS, SHORT_PASS, SHOT, DRIBBLE, STOP_DRIBBLE<br>
<em>ball_owned_team</em> = -1: LONG_PASS, HIGH_PASS, SHORT_PASS, SHOT, DRIBBLE, STOP_DRIBBLE, SLIDING<br>
<br>Although such a trick can accelerate learning by avoiding unnecessary actions, it also makes our algorithm unable to learn some strong policies. For example, in the last few weeks of this competition, we found that one entry of WeKick had learned the skill of passing the ball between players without stopping the ball. When the ball was flying from the passer to the receiver, the receiver had already chosen the most appropriate position and facing direction for performing the next pass. Once the ball got very close to the receiver (we found that the `ball_owned_team' at that time was still -1), the ball would be passed to the next receiver. This kind of ball-passing tactic really impressed us and we realized that our model cannot pass the ball in the same way. Therefore, in the last week, we trained another model without legal action masks. This no-legal-action model actually has the highest score (1597.5) among all our submitted models at the end of the extra evaluation week. Interestingly, the highest score achieved by our legal-action models is 1597.0. The no-legal-action model successfully learned the ball-passing skill, though not as skillful as WeKick. We expect it will perform better if there are another extra week and more computation resources for training…</p>
<h3>Reward</h3>
<p>For the PVE training, we use the scoring reward and checkpoint reward. The latter is also provided by the gfootball environment (please refer to the gfootball paper). We found that using the checkpoint rewards is really helpful in the early training stage because such rewards are the most straightforward for encouraging the player to take the ball from the backcourt to the frontcourt and make a goal. At the end of the PVE training phase, our model can beat the hard bot (difficulty_level = 1.0) with a goal difference higher than 10. However, the disadvantage of the checkpoint rewards is that the behavior of the player output by the model is always dribbling the ball (maybe with sprint). In fact, the PVE-trained model is not a strong model and the learned policy is very easy to exploit. The only purpose of using the checkpoint rewards is to let our agent get some clue on the offense.<br><br>
For selfplay training, we use the scoring reward and abandon checkpoint reward to let our model learn more sophisticated behaviors. Note that the model is based on the PVE-trained model, which is good at dribbling, shooting, and scoring. Therefore, the reward signals are not that sparse in selfplay.<br><br>
We also tried different shaping rewards in order to learn models with different behavior styles, such as using ball possession rewards (e.g., 0.1 for getting the ball and -0.1 for losing the ball possession) to encourage tighter defense and using ball passing rewards (e.g., 0.01 for a successful pass and -0.01 for an unsuccessful one) to get a pass-favored policy. The positive result is that with different shaping rewards, the behavior styles learned by the models are quite different. For example, with the ball passing rewards, the number of passes executed and the number of passes completed of the corresponding model in a match is at least two times higher than those of the other models. However, none of the shaping rewards adopted were able to train very strong models. The reasons are two-fold. Firstly, setting an appropriate value for each type of reward is a difficult problem and needs tedious tuning. Secondly, our shaping rewards actually are not directly related to the goal of scoring, which is also pointed out by the <strong>Raw Beast</strong> team.</p>
<h3>Resource</h3>
<p>During the first several months before the Kaggle competition, we only have 80 CPU cores and it takes ages to get the model to work (around 190k episodes per week). The training scale is similar to that of <a href="https://www.kaggle.com/c/google-football/discussion/201376" target="_blank">liveinparis</a>) and after training for two weeks, the model can reach up to 1400+ on the previous leaderboard before Kaggle. For the Kaggle competition, we use 1000 CPU cores for each experiment (20k+ fps in our framework) and a maximum of 2500 CPU cores in the last two weeks (1000 for non-legal action masks training, 1000 for adding pre-16 steps action surgery training, and 500 for curriculum training and imitation learning). In addition, GPUs are not necessary since we use vectors as inputs.</p>
<h3>Other methods we tried:</h3>
<ol>
<li>ELO-based Opponent Selection: We tried to select the opponent by using the Elo rank during selfplay, which turns out to be similar to the performance of selecting the newest opponent with a certain ratio (70%) in this football environment.</li>
<li>Curriculum Learning and Imitation Learning:We also used curriculum learning to help our agents to learn useful skills such as shooting from the middle of the field during freekick (see the gif bellow). Besides, we also cloned the behavior of Wekick and put the model in our opponent pools.<br>
<img src="https://pic1.zhimg.com/50/v2-ead94061921f49028929cc30cdf10afc_r.gif" alt=""></li>
<li>Action Semantics Network: We tried the action semantics network (ASN), which is proposed in an ICLR2020 paper (<a href="https://openreview.net/forum?id=ryg48p4tPH)" target="_blank">https://openreview.net/forum?id=ryg48p4tPH)</a>. The motivation of using ASN is that in this football scenario, different actions of a player may require differnt observations. For example, for applying the SLIDING action, a player should pay more attention to the ball and the player controlling the ball. And for applying the SHOT action, the player should take the ball, the opponent goalkeeper, maybe the opponent players nearby as well into consideration. However, our computation resources are limited and this model is still in the training process.</li>
<li>Behavior Tree as Macro Action: We extended the action space size from 19 to 20 by adding a new action 'behavior tree' and trained a new model. This new action means to get the behavior of the player controlled according to a behavior-tree AI. You can simply treat a behavior-tree AI as a rule-based AI. Most importantly, such a behavior-tree AI is a python version of the <strong>eliza_controller</strong> in the internal C++ code of the gfootball_engine, namely the internal bot provided by the environment. The motivation for utilizing the internal bot is that such a bot is good at ball passing and ball controlling. We believe that a stronger model can be obtained if it has the ball passing and ball controlling skills of the internal bot. However, this model is still in the training process under limited resources.</li>
<li>Graph Neural Networks: We also tried the graph neural networks (such as GCN and GAT) to extract features. The features of the players are designed as a fully connected graph, where we represent the players' information with the graph's nodes and relations between players with edges. However, this model is still being trained under limited resources.</li>
</ol>
<h3>Some interesting stuff:</h3>
<ol>
<li>We found that the goalkeeper may keep dribbling from its own goal to the opponent's goal in one of the early models we trained, LOL…<br>
<img src="https://pic4.zhimg.com/50/v2-ecf0fe0cde3aaf27035fa4d31dd42373_r.gif" alt=""></li>
<li>The game version changing from 2.6 (left) to 2.8 (right) replaces the guards with the fronts during the kickoff, which makes one of our models' kicking-off strategy (see the gif below) useless since the guards tend to run back while the fronts tend to kick forward.<br>
<img src="https://pic4.zhimg.com/50/v2-7626e3f78b67489adc87965e9d13976d_r.jpg" alt=""><br>
<img src="https://pic3.zhimg.com/50/v2-63591ea9d7262b08f18b6cbdaa67a66a_r.gif" alt=""></li>
</ol> |
Mechanisms of Action (MoA) Prediction | 35th 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: Mechanisms of Action (MoA) Prediction
<|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%2F2350982%2Fbc8d816ce80c4b07e2cab451d1c30085%2Fmoa.png?generation=1606888296177049&alt=media" alt="DSG's 35th place solution"></p>
<h2>Notebooks</h2>
<ul>
<li>Kon's ResNet: <a href="https://www.kaggle.com/yxohrxn/resnetclassifier-fit" target="_blank">https://www.kaggle.com/yxohrxn/resnetclassifier-fit</a></li>
<li>Blending: <a href="https://www.kaggle.com/yxohrxn/votingclassifier-fit-without-lightgm-and-svm" target="_blank">https://www.kaggle.com/yxohrxn/votingclassifier-fit-without-lightgm-and-svm</a></li>
<li>Inference: <a href="https://www.kaggle.com/yxohrxn/votingclassifier-predict-without-postprocessing" target="_blank">https://www.kaggle.com/yxohrxn/votingclassifier-predict-without-postprocessing</a></li>
</ul>
<h2>Our approach</h2>
<h3>1. Data augmentation</h3>
<p>We tried Gaussian noise, Cutout, Mixup, and CutMix, and CutMix improved the CV score the most. In particular, it worked well when we increased the alpha, which is a hyperparameter. Removing ctl_vehicle made CutMix less effective.</p>
<h3>2. Weighted seed-fold averaging</h3>
<p>Since <a href="https://www.kaggle.com/c/lish-moa/discussion/195195" target="_blank">Deotte's CV scheme</a> takes into account drug_id, a situation often arises where there are no positive examples in the training data, especially for minor classes. The predictions of the model created in this case are completely meaningless. Therefore, we counted the positive examples of each class in the training data for each fold and weighted the predictions using their number as weights.</p>
<h3>3. Class-wise blending</h3>
<p>We improved <a href="https://www.kaggle.com/gogo827jz/optimise-blending-weights-with-bonus-0" target="_blank">Zhang's notebook</a> to compute weights to minimize the per-class log loss.</p>
<pre><code>weights.shape = (n_classes, n_models)
</code></pre>
<p>To find the best model combination, we evaluated the performance with CV. In addition, early stopping and label smoothing were performed to avoid overfitting. We created nearly 20 models in total, and the above combination was the best.</p> |
Riiid Answer Correctness Prediction | [62nd solution, LB: 0.801] Single light GBM with 113 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: Riiid Answer Correctness Prediction
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Many many thanks to the organizers and all kagglers.<br>
Throughout this competition, I realized good kagglers are not just smart data scientists, but also proficient engineers. They have deep and broad knowledge about how to speed up processing, handle data memory efficiently, and debug submission error. I learned a lot from their notebook and comments. <br>
I achieved 62nd (0.801 CV /0.799 public / 0.801 private) and got my first medal with a single LGB model. I tried blending with catboost and SAKT models, but it did not work well for me. I think it is mainly due to the time constraint to refine them.<br>
The code and model are opened <a href="https://www.kaggle.com/tomooinubushi/62nd-solution-lightgbm-single-model-lb-0-801" target="_blank">here</a>.</p>
<p>I mainly focused on feature engineering and used 113 features. The feature importance of them was as follows</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F3754725%2Fc09711551a883f6995032d91b6408bd9%2F__results___42_0.png?generation=1610076363046071&alt=media" alt=""></p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F3754725%2F35c076ded96a2ef0d40ec307d0b8da51%2F__results___42_1.png?generation=1610076387230945&alt=media" alt=""></p>
<p>The meanings of abbreviations were as follows </p>
<ul>
<li>acc: answered_correctly</li>
<li>exp: prior_question_had_explanation</li>
<li>time: prior_question_elapsed_time</li>
<li>count: number of trial</li>
<li>count_lecture: number of lecture</li>
<li>tfl: timestamp from last nth trial to that from n+1th trial</li>
<li>dif: difficulty (1 - content-wise accuracy)</li>
<li>dpt: difficulty point (add difficulty if users answer was correct)</li>
<li>avg: average</li>
<li>std: standard deviation</li>
<li>sum: sum</li>
<li>hist: historical average with temporal decay of gamma 0.75 </li>
<li>hist2: historical average with temporal decay of gamma 0.25</li>
<li>u: user-wise</li>
<li>t: tag-wise</li>
<li>tg: taggroup-wise</li>
<li>p: part-wise</li>
<li>c: content-wise</li>
<li>b: bundle-wise</li>
<li>uc: user-content-wise</li>
<li>ub: user-bundle-wise</li>
<li>up: user-part-wise</li>
<li>time_per_count_u: timestamp/count_u</li>
<li>count_u_nondiagnostic: user-wise count of non-diagnostic questions</li>
<li>exp_avg_u_corrected: user-wise average of prior_question_had_explanation corrected for diagnostic questions. Th user cannot read explanation for diagnostic questions.</li>
<li>pp_ratio: ratio of paid part (part1, 3, 4, 6, 7) trials per all trials, only paid users of SANTA app can solve them if it is not diagnostic questions</li>
<li>listening_ratio: ratio of listening part trials per all trials</li>
<li>relative_dif: relative difficulty of questions calculated with acc_avg_c / dif_avg_u</li>
<li>notacc_sum: sum of failed trials</li>
<li>wp_ts: trueskill feature of win probability</li>
<li>umu_ts, usigma_ts, qmu_ts, qsigma_ts: trueskill features of mu, and sigma of user and content</li>
</ul>
<p>I learned a lot from many notebooks and comments of other kagglers. </p>
<ul>
<li>CV strategy, loop feature engineering, time series emulater by <a href="https://www.kaggle.com/its7171" target="_blank">@its7171</a></li>
<li>use of sqlite to prevent memory error from <a href="https://www.kaggle.com/higepon" target="_blank">@higepon</a> and <a href="https://www.kaggle.com/calebeverett" target="_blank">@calebeverett</a> </li>
<li>use true skill features from <a href="https://www.kaggle.com/zyy2016" target="_blank">@zyy2016</a> and <a href="https://www.kaggle.com/neinun" target="_blank">@neinun</a> </li>
<li>convert dataframe to numpy array memory-eficiently from <a href="https://www.kaggle.com/markwijkhuizen" target="_blank">@markwijkhuizen</a> </li>
<li>use of taggroup from <a href="https://www.kaggle.com/radema" target="_blank">@radema</a></li>
</ul>
<p>Please notify me if I missed anyone.</p>
<p>Random thought about this competition.</p>
<ul>
<li>The quantity and quality of the dataset were very high. We saw good cv-lb relationship.</li>
<li>The concept of submission API is very interesting. It is realistic and highly adequate for time-series prediction.</li>
<li>I think the kaggle system needs some improvements. The computational power is so small to handle huge dataset of this competition. The error message of submission should be more user-friendly.</li>
</ul>
<p>Any comments and questions are welcome!</p> |
Riiid Answer Correctness Prediction | 39th 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: Riiid Answer Correctness Prediction
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>I took me a while to post my solution since I was cleaning all the messy code I had. My solution was a SAINT-like model, however a bit simpler in architecture. I was surprised how stripping the model out of features that intuitively make sense can improve the score.</p>
<p>It was d_model: 128 , att_heads: 2 , ff_model: 512 , dropout: 0.1 , 4 layers , trained on whole data for 100 + epochs. It breaks the 0.800 ROC bar around the 60th epoch.</p>
<p>Since many people failed to successfully implement the SAINT model, I created a notebook with detailed explanation, and clear code that takes raw data, created a dataloader, train the SAINT model, then perform inference using Tito's iterator. The model in the notebook is 64 d_model, it score 0.789 in validation, scaling it would take it 0.800+.</p>
<p>Notebook: <a href="https://www.kaggle.com/abdessalemboukil/saint-training-inference-guide-39th-solution" target="_blank">https://www.kaggle.com/abdessalemboukil/saint-training-inference-guide-39th-solution</a> </p>
<p>Thanks for the awesome competition!</p> |
Google Research Football with Manchester City F.C. | TamakEri: 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: Google Research Football with Manchester City F.C.
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><blockquote>
<p>TamakEri (“球蹴”) means “play with ball” in Japanese.</p>
</blockquote>
<p>Congratulations to the winners! 🎉<br>
Thanks to all participants, Kaggle team, Manchester City and Google Research for exciting games! ⚽️</p>
<p>Our team participated in this competition with about three weeks left to the deadline. We have been working towards winning by using reinforcement learning (RL). Fortunately, we got 5th place and we are happy to share our solution and <a href="https://github.com/YuriCat/TamakEriFever" target="_blank">code</a> with the kaggle community.</p>
<p>Special thanks to my teammate <a href="https://www.kaggle.com/yuricat" target="_blank">@yuricat</a> !!</p>
<h1>Overview</h1>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F263142%2F9e44f206976c657267718188cd130bfb%2Foverview.png?generation=1608013227102716&alt=media" alt=""></p>
<p>We mainly trained our agents with (deep) reinforcement learning on a learner-actor architecture like <a href="https://arxiv.org/abs/1802.01561" target="_blank">IMPALA</a>. Our neural network model is trained through self-play combined with single-play games against various opponent agents (rule-based bots, built-in AI, etc).</p>
<p>In the early steps of learning, we simultaneously used supervised learning (SL) with the top players' replays for the purpose of helping with the start of RL. The effect of supervised learning decayed as the training progressed, and the model was finally being trained only with reinforcement learning.</p>
<p>Our model consists of multi-head self attention, CNN, GRU, and MLP networks. The detailed model and input features are described later.</p>
<p>Our agents were mainly evaluated against a hard-level built-in AI (i.e. team difficulty = 1.0) that is implemented in the football game engine. On the last day of the competition, the win-rate of the latest model reached ~90% against the built-in AI and was still getting higher!<br>
(However we found out just before the deadline that we couldn't submit the next model while scoring the previous model, so we couldn’t submit the latest (ensemble) model 😭😭😭 . We will make use of this experience at the next BIG match!! ⚽️)</p>
<p><a href="https://github.com/YuriCat/TamakEriFever" target="_blank">Our implementation script</a> is based on OSS RL library <a href="https://github.com/DeNA/HandyRL" target="_blank">HandyRL</a>.</p>
<h1>Algorithm and Training</h1>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F263142%2F5ebb310566f08e2fee190c4fba6c1e24%2F2020-12-13%2013.15.36.png?generation=1608013364797563&alt=media" alt=""></p>
<h2>Main algorithm</h2>
<ul>
<li>Off-policy distributed reinforcement learning</li>
<li>TD(λ) + importance sampling (clipped variant)</li>
</ul>
<p>We used an off-policy distributed reinforcement learning to efficiently update an agent’s policy from the results of a large number of games. The learning algorithm is based on a policy gradient algorithm. The model learns policy, value, and return. Our value estimates final game outcome, and our return estimates discounted score reward. Then our policy maximizes both of them. In other words, the policy learns to maximize the expectations of scoring a next goal and winning a game. In our training, when one of the teams scores, the calculation of return is reset to break the episode down into before and after scores.</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F263142%2F1d347faa39aa3b6cc75ceae55e65f4c1%2F2020-12-11%2017.08.35.png?generation=1608013435775391&alt=media" alt=""></p>
<h2>Losses</h2>
<h4>RL loss</h4>
<ul>
<li>Policy loss<ul>
<li>importance sampling (1-step Retrace) * advantage * log(policy)</li>
<li>advantage = (value advantage + return advantage) / 2</li>
<li>value advantage = UPGO(λ)</li>
<li>return advantage = TD(λ)</li></ul></li>
<li>Value loss<ul>
<li>MSE</li>
<li>target = λ-value (TD(λ))</li></ul></li>
<li>Return loss<ul>
<li>Huber loss (SmoothL1Loss)</li>
<li>target = λ-return (TD(λ))</li></ul></li>
<li>Entropy loss</li>
</ul>
<h4>SL loss</h4>
<ul>
<li>Policy loss <ul>
<li>NLL (Negative Log-Likelihood) loss</li>
<li>target = replays’ action</li></ul></li>
<li>Value loss<ul>
<li>MSE</li>
<li>target = outcome</li></ul></li>
</ul>
<p>The advantage, which is used in the RL policy loss, is an average of value and return advantages. The value advantage is calculated based on UPGO(λ), which is combined with upgoing policy update (UPGO) and λ-value. The return advantage is calculated based on λ-return. The policy loss is calibrated by using a clipped importance sampling weight between behavior policy and target policy (1-step Retrace). The value target is computed based on a score difference with tanh to consider the degree of win/lose. That means when the score is 4-1, the outcomes of both players are tanh(4-1)=0.995 and tanh(1-4)=-0.995. When the score is 2-1, the outcomes are 0.76 and -0.76. In the beginning of the competition, we trained the model only with the outcome, so the above idea was used to encourage the agent to go for more scores. After that, we introduced the score as an immediate reward at the end of the competition. Now, we expect that the naive outcome -1(lose), 0(tie), 1(win) with immediate score rewards will also work fine.</p>
<p>The score reward (+1/-1) is used to calculate the return target with a discount factor. Note that we also tried a checkpoint reward similar to the one described in <a href="https://arxiv.org/pdf/1907.11180.pdf" target="_blank">the original paper</a>.</p>
<p>The percentage of supervised data in an experience buffer started with 10%. We manually reduced the ratio of supervised learning through training by removing the supervised data from the buffer. When the accuracy of the predicted action in supervised learning saturated, the ratio was set to 0%. From that timing, the model was trained only with reinforcement learning.</p>
<h2>Training settings (see <a href="https://github.com/YuriCat/TamakEriFever/blob/master/config.yaml" target="_blank">the code</a> for details)</h2>
<ul>
<li>learning rate with decay (default=3e-8 x batch size)</li>
<li>optimizer: Adam</li>
<li>batch size: 156 ~ 400</li>
<li>buffer size: 3000 (min) - 30000 (max)</li>
<li>action repetitions: 4 (if an agent choose the action “→” at time t, “→” is repeated next four time steps t, t+1, t+2, t+3)</li>
<li>SL loss coefficient: 0.01</li>
</ul>
<h2>Computational resources</h2>
<ul>
<li>small experiment<ul>
<li>worker: 96-core CPU</li>
<li>learner/trainer: 24-core CPU + 1 GPU (NVIDIA T4) </li></ul></li>
<li>large experiment<ul>
<li>worker: 96-core CPU x8</li>
<li>learner/trainer: 96-core CPU + 4 GPU (NVIDIA T4) </li></ul></li>
</ul>
<p>We used the small setting per experiment in the early phase. In the last three days, we leveraged large amounts of resources in parallel to accelerate multiple experiments (total ~4000 CPUs and ~20 GPUs). The final agent has played a total of ~700k games through the training.</p>
<h1>Features and Model</h1>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F263142%2Fc9f3326262984ded006e46effe668f0e%2Ffeatures_model2.png?generation=1608013747792952&alt=media" alt=""></p>
<p>Our model consists of several input features and modules.</p>
<ul>
<li>Attention between players (encoder, multi-head self attention, control module)<ul>
<li>The encoder module embeds the index of all players and game modes, and then encodes the embedding and some features to a fixed tensor</li>
<li>The tensor is fed to the multi-head self attention modules to get features considering attentions between all players</li>
<li>The control module mainly extracts (decodes) the feature of the active player using like an encoder-decoder attention mechanism based on the output from the previous modules</li>
<li>We also tried RNN as control module to manage a long horizon memory, but it didn't improve the performance so much</li></ul></li>
<li>Action history (GRU)<ul>
<li>The latest action history (sequence length = 8) is input to GRU for acquiring the context of actions</li>
<li>GRU outputs the latent features of the sequence</li></ul></li>
<li>Left vs right player tensor (CNN)<ul>
<li>This CNN is expected to learn the relationships between left vs right-side players with 1x1 conv and pooling (not for spatial structure)</li>
<li>This approach is based on <a href="https://www.kaggle.com/c/nfl-big-data-bowl-2020/discussion/119400" target="_blank">1st solution</a> of the NFL Big Data Bowl competition</li></ul></li>
<li>Head modules (fully-connected networks)<ul>
<li>Concatenates the features of the previous stages and feeds them into the policy, value, and return networks</li></ul></li>
</ul>
<h1>Agents</h1>
<p>Our neural network was trained through self-play combined with single-play games against various opponent agents. To keep the winning percentage at 50%, the weights of opponent agents were dynamically changed depending on the progress. The ratio of strong opponents increases when the training agent becomes stronger.</p>
<ul>
<li>Self-play agent<ul>
<li>The latest model is always used for self-play</li>
<li>The training is started with 10% self-play and finally ended up with 80%</li></ul></li>
<li>Opponent agents when not self-play<ul>
<li>Simple agents<ul>
<li>Idle (do nothing), random, run right</li></ul></li>
<li>Rule-based agents (Great kernel agents. Thanks to the authors!)<ul>
<li><a href="https://www.kaggle.com/yegorbiryukov/gfootball-with-memory-patterns" target="_blank">https://www.kaggle.com/yegorbiryukov/gfootball-with-memory-patterns</a></li>
<li><a href="https://www.kaggle.com/eugenkeil/simple-baseline-bot" target="_blank">https://www.kaggle.com/eugenkeil/simple-baseline-bot</a></li>
<li><a href="https://www.kaggle.com/mlconsult/1149-ish-bot-rl-approximation" target="_blank">https://www.kaggle.com/mlconsult/1149-ish-bot-rl-approximation</a></li>
<li><a href="https://www.kaggle.com/mlconsult/best-open-rules-bot-score-1020-7" target="_blank">https://www.kaggle.com/mlconsult/best-open-rules-bot-score-1020-7</a></li>
<li><a href="https://www.kaggle.com/shotaro/optimizing-tunable-bot-with-optuna" target="_blank">https://www.kaggle.com/shotaro/optimizing-tunable-bot-with-optuna</a></li></ul></li>
<li>Built-in AI<ul>
<li>Hard-level AI (right_team_difficulty = 1)</li></ul></li>
<li>Past trained agents<ul>
<li>Agents created by multiple experiments</li></ul></li>
<li>Mixed agents<ul>
<li>e.g., built-in AI + RL agent, built-in AI + rule-based agent</li></ul></li></ul></li>
</ul>
<h3>Ensemble agent</h3>
<p>By the end of the competition, multiple agents had been created. To further improve the accuracy of the policy, we tried an ensemble agent. The ensemble methods may include, for example, (weighted) voting of each agent and (weighted) policy averaging. We adopted the weighted policy averaging for the ensemble agent.</p>
<pre><code>policy(agentA) = [0.1, 0.8, 0.1]
policy(agentB) = [0.2, 0.5, 0.3]
policy(agentC) = [0.3, 0.6, 0.1]
weight = {A: 3, B: 1, C: 2}
ensemble policy = (policy(agentA) * 3 + policy(agentB) * 1 + policy(agentC) * 2) / 6 = [0.183, 0.663, 0.133]
</code></pre>
<p>The win-rate of the ensemble agent achieved a highest score against the built-in AI in the local environment.</p>
<h1>Evaluation</h1>
<h2>vs. various agents (1000-step game)</h2>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F263142%2F431834d169b7ea12429fdb28579cb707%2FFigure_1-15.png?generation=1608014159413305&alt=media" alt=""></p>
<p>Some workers were assigned for evaluation to get the win rate during training. Some of the opponent agents are rule-based agents and the others are trained agents. The above figure shows the win-rate curves of a certain model at the time of saving the model. This graph shows our model was still getting stronger even at the deadline.</p>
<h2>vs. built-in AI (full 3000-step game)</h2>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F263142%2Ffe90aaf906feea39281bf57c8c47214a%2Fvs_builtin.png?generation=1608014208575876&alt=media" alt=""></p>
<p>The win rate against built-in AI was used as a main metric to evaluate the performance of the agent. We evaluated 1,000-2,000 games to improve the reliability of the win-rate for the submission agents. We found that the rating of leaderboard is highly correlated to the win-rate against the built-in AI. The higher the win-rate against the built-in AI is, the higher the rating of the submission agent is. The win-rate of our final model reached ~90% against the built-in AI.</p>
<h1>Additional features</h1>
<h2>New action set</h2>
<p>In football, the direction of passing and shooting is important. We analyzed some matches and found that the kick and pass actions might be related to the sticky direction. So, we created a new action set that combined the two actions (Pass/Shot + Direction). With this extension, the quality of pass and shot was enhanced qualitatively, for example crossing from side space, shot direction, free kicks, and so on.</p>
<p>New action set is like the following.</p>
<pre><code>20 = LongPass + Left
21 = LongPass + TopLeft
...
28 = HighPass + Left
...
36 = ShortPass + Left
...
44 = Shot + Left
…
51 = Shot + BottomLeft
</code></pre>
<h2>Skipping initial steps</h2>
<p>In a certain percentage of games during training, the initial frames were skipped by using the rule-base agents (e.g. 30% skipped games and 70% full games). This is expected to increase the variety of the states for the exploration and robustness of the agent. The number of the skipping steps was determined randomly at the start of a match After skipping, the training started from the state on the way.</p>
<h2>Model distillation</h2>
<p>We came up with a lot of ideas, but we didn't have much time left to create a new model from scratch. RL from scratch would take too much time! Therefore, we used a technique of model distillation (a.k.a knowledge distillation) to transfer the skills from the past model to the new one. At the start-up of training, the output of a pre-trained model was used as a teacher with reinforcement learning. As a result, the agent was able to beat the rule-based and other agents in a few hours. Note that it’s only applied in the early stages of training.</p>
<h2>Deterministic opponent in self-play</h2>
<p>We also used a deterministic policy for the opponents in self-play without frame skip (action repetition). As a result, the trained agent could always play against opponents who are stronger than itself, and it could be balanced with weaker rule-base agents and past models to achieve 50% winning rate.</p>
<h1>Code</h1>
<p><a href="https://github.com/YuriCat/TamakEriFever" target="_blank">https://github.com/YuriCat/TamakEriFever</a></p>
<p>The implementation code is based on <a href="https://github.com/DeNA/HandyRL" target="_blank">HandyRL</a>, which is an open-source library for distributed reinforcement learning. The library can be applied to many problems of reinforcement learning. Because of its good parallelism, neural network training and episode data generation can scale easily. The simple implementation makes it easy to incorporate your game environments and algorithms into the library. We recommend this RL library for future simulation competitions, if you like it ❤️</p>
<hr>
<p>P.S. The early agent prefers Marie Curie and Rosalind Franklin to quickly get behind a defender and score a goal. </p>
<div>
<img src="https://raw.githubusercontent.com/YuriCat/TamakEriFever/master/curie.gif" alt="cuire">
</div> |
Riiid Answer Correctness Prediction | My personnal journey through the RIID competition - Silver LGB 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: Riiid Answer Correctness Prediction
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>First of all, and as many others, I had a lot of pleasure participating to that competition. The challenge was fun and there were many challenges that I was not used to face. </p>
<p>I joined the competition a bit late (1 month before the end) so I really decided to focus on the feature engineering part. I had the aim of reaching the silver zone, and that's what I did, so very happy about it !</p>
<p>Overall I learned a lot of tricks to handle RAM and improve CPU computational time:</p>
<ul>
<li>Making a single loop to make the whole feature engineering rather than using several pandas.apply()</li>
<li>Using a csv iterator rather than iterating through a numpy array fully loaded (or worst, a dataframe!)</li>
<li>Smart use of sets to calculate presence or not of elements in a list</li>
<li>The potential of dictionaries that I clearly underestimated until now !</li>
<li>Some RAM tricks such than converting the training array column by column to float32 before feeding it to the LGB model and avoid RAM explosion</li>
<li>The potential of SHAP for feature selection</li>
<li>The possibility to use conditional features rather than doing One hot Encoding</li>
<li>…</li>
</ul>
<p>For me, one of the key challenges was to not get lost in the amount of code I was producing, and it happened more than once that I decided to start again from a blank page to have a clear view of what I was actually doing ! If there is something I will try to handle better next time it is really global code organization. I think I lost a lot (too much) on it.</p>
<p>Separating the code in 3 parts worked very well for me, with one part handling creation of user history, one part updating it, and one part creating the features based on the user history.</p>
<p>Apart from all classical features that have been already discussed, one of my model key differentiation was the bayesian probability index that I built and discussed <a href="https://www.kaggle.com/c/riiid-test-answer-prediction/discussion/207148" target="_blank">there</a>. Following <a href="https://www.kaggle.com/authman" target="_blank">@authman</a> comment, I created an efficient cluster-based feature, illustrated by the feature below:<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1161354%2F9a1323fb5376e39469c104cae83ac379%2Fclusterriid.png?generation=1610124766536795&alt=media" alt=""></p>
<p>For those interested, I created a detailed kernel with all my inference pipeline and feature engineering. You can check it out here, there is probably one or two thing interesting to pick up !<br>
<a href="https://www.kaggle.com/bowaka/riid-lgb-single-model-0-793-full-summary" target="_blank">Notebook here</a></p>
<p>I will personally continuing to work on the datasets and take the opportunity to improve my knowledge and expertise about transformers (that is currently close to 0 !)</p> |
Riiid Answer Correctness Prediction | 126th place solution - LGBM with B-IRT features (LB 0.795) | 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: Riiid Answer Correctness Prediction
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h4>Overview:</h4>
<p>My solution is a single LightGBM model with a total of 48 features.</p>
<h4>Best Features:</h4>
<p>Unfortunately, I didn't keep track of exactly how much each feature affected my model's CV, but from empirical evidence I noticed the best features to be those based on:</p>
<ul>
<li>Elo rating system</li>
<li>boolean determining whether or not a student has already seen a question</li>
<li>previous timestamps</li>
<li>Question difficulty based on the parameters of a Bayesian IRT model.</li>
</ul>
<p>A total list of the features is shown below (in no particular order):</p>
<pre><code>analysis_columns = [
'answered_correctly',
'timestamp',
'prior_question_elapsed_time',
'prior_question_had_explanation',
'task_container_id',
'bundle_id',
'has_seen_question',
'user_correct_ratio',
'content_correct_ratio',
'correct_streak',
'incorrect_streak',
'user_total_question_count',
'part_correct_ratio',
'time_since_last_timestamp',
'time_since_last_lecture',
'tag_correct_ratio',
'previous_question_same_bundle',
'previous_correct_and_same_bundle',
'previous_lecture_type',
'previous_lecture_id',
'user_part_correct_ratio',
'user_part_avg_elapsed_time',
'user_part_timestamp_diff',
'user_tag_correct_ratio',
'user_tag_avg_elapsed_time',
'user_tag_timestamp_diff',
'question_history',
'lecture_count',
'questions_since_last_lec',
'hardest_question_correct_ratio',
'easiest_question_correct_ratio',
'smallest_pqet',
'largest_pqet',
'user_rating',
'content_rating',
'highest_elo',
'lowest_elo',
'elo_user_content',
'elo_content_user',
'tag',
'irt_difficulty',
'irt_discrimination',
'timestamp_n1',
'timestamp_n2',
'timestamp_n3',
'tag_difficulty',
'tag_discrimination',
'pqhe_true_correct_ratio',
'pqhe_false_correct_ratio',
]
</code></pre>
<p>Feature importance graph (Note: the names somewhat vary from above):<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F3785972%2F3078d4cb7724c798c7091f7dbb48f66e%2F.png?generation=1610411000057392&alt=media" alt=""></p>
<h4>Things I tried that didn't work:</h4>
<p><strong>Factorization Machine:</strong><br>
As others have stated, the goal of this task can be, to some extent, compared to that of a recommendation system where the recommendation score can be interpreted as a student's ability to answer some question. Although not without criticism, Riiid! has also used or referenced Matrix Factorization in their own work (see <a href="https://educationaldatamining.org/files/conferences/EDM2020/papers/paper_91.pdf" target="_blank">[1]</a>, <a href="https://arxiv.org/pdf/2005.05021.pdf" target="_blank">[2]</a>, <a href="https://arxiv.org/pdf/2012.05031.pdf" target="_blank">[3]</a>).</p>
<p>The <a href="https://ieeexplore.ieee.org/document/5694074" target="_blank">Factorization Machine</a> algorithm is quite simple as is as follows:</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F3785972%2F137e8b1e4d9cb771c1c526f665801e65%2Fsagemaker-factorization-1.png?generation=1610412377437882&alt=media" alt=""></p>
<p>Unfortunately, I was unable to get a successful submission using existing Factorization Machine tools, as well as my own implementation. Instead, I tried incorporating the latent factors from the <em>V</em> interaction matrix (shown in the formula above), but they didn't have any noticeable positive effect on the outcome of the model.</p>
<p><strong>Bayesian Knowledge Tracing (BKT):</strong><br>
Bayesian Knowledge Tracing is the precursor to Deep Knowledge Tracing. The particular model I was interested in was the individualized variation that include contextualization of guessing and slipping estimates. My goal was to train a model offline and use the <em>guess</em> and <em>slip</em> parameters in the LGBM model. Unfortunately, these also showed very little positive effect on the model's overall CV. This may be due to the poor performance of the trained BKT model as well.</p>
<p><strong>Neural Halflife Regression:</strong><br>
Using Tensorflow, I also intended to implement forgetting of a question's tag into my model based on Duolingo's <a href="https://research.duolingo.com/papers/settles.acl16.pdf" target="_blank">Halflife regression</a> model, inspired by <a href="https://link.springer.com/chapter/10.1007/978-3-030-52240-7_65" target="_blank">this</a> paper.</p>
<p>The formula used is also quite simple and is as follows:<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F3785972%2Fb8e08c0ede4d0a3244dad4a882ea8cba%2F2021-01-12%20100012.png?generation=1610413465690518&alt=media" alt=""><br>
, where <em>h</em> and <em>C</em>, are encoders, representing a learner's strength and a question's complexity respectively.</p>
<p>However, in the short amount of time I had left, I was unable to ensemble the model with the LGBM model to test whether or not it may have had a positive effect on the outcome of the model.</p>
<h4>Conclusion</h4>
<p>Overall this was a great experience, I learned a lot and had a lot of fun. I hope to get more comfortable with TensorFlow and PyTorch so I can have a more competitive edge in future competitions.</p>
<p>All of the code I used for this project I have uploaded to the following github repository: <a href="https://github.com/jwnz/Riiid-AIEd-Challenge-2020" target="_blank">https://github.com/jwnz/Riiid-AIEd-Challenge-2020</a></p> |
Riiid Answer Correctness Prediction | 24th Place Solution saintpp + lgb private0.810 | 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: Riiid Answer Correctness Prediction
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Firstly, thanks to Kaggle hold such a good competition, almost no shake. Congrats tops and very thanks to my teammates <a href="https://www.kaggle.com/jaideepvalani" target="_blank">@jaideepvalani</a> <a href="https://www.kaggle.com/ekffar" target="_blank">@ekffar</a>. Finally our team finally public score 0.808, private 0.810, and final rank 24. we missed gold, it's ok, now i want to share our method</p>
<p>because of jet lag, i have no read discuss in detail, so i just see my teammate <a href="https://www.kaggle.com/jaideepvalani" target="_blank">@jaideepvalani</a> had shared our <a href="https://www.kaggle.com/c/riiid-test-answer-prediction/discussion/209625" target="_blank">solution</a> right now. As a complementary, not repeat, i just expand the detail based on <a href="https://www.kaggle.com/c/riiid-test-answer-prediction/discussion/209625" target="_blank">jaideepvalani's solution</a></p>
<h1><strong>Architecture</strong></h1>
<pre><code>SaintPlusPlus, lgb
</code></pre>
<h1>Embeddings</h1>
<h2>Exercise:</h2>
<pre><code>Question_id
Part
Community id (tried, but no boosting, maybe need tuning)
Task container id (tried, but no boosting, maybe need tuning)
</code></pre>
<h2>Interaction:</h2>
<pre><code>lag time (same container id, keep same with first one) (discrete embedding)
prior question elapsed time(continuous embedding)
prior had explain (discrete embedding)
Prior lecture(discrete embedding)
</code></pre>
<h2>Response:</h2>
<pre><code>Prior question correctness(discrete embedding)
</code></pre>
<h1>Data sample optimization</h1>
<p>Data sampling is important in our experiment<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F347724%2F8884cd3f5fca04b3232adb038b131f0f%2Friiid.png?generation=1610088827710995&alt=media" alt=""></p>
<h1>optimization</h1>
<p>## SAINTPP<br>
1 skip connection, we add skip connection for multi encoder layers inner, and multi decoder layers inner, the origin implement i use from github have no this skip connection <br>
2 add dropout for encoder, decoder, FFN<br>
3 try TCN causal conv after embedding, no boost, but now, i think it should tune and will work<br>
4 big seq len for saintpp give our team boosting, i think it maybe caused by too short seq make <br>
transformer link model struggle into local minest point </p>
<h2>LGB</h2>
<p>updating</p>
<h1>Conclusion</h1>
<p>Our best saintpp(seqlen 320, embdim224, 2 x encder+ 2 x decoder) get cv 0.8016 lb 0.806, and lgb near get 0.796. Finally submission is merge lgb(lb 796) + saintpp cv1(cv 8016) + saintpp cv3(cv 0.7992) = public lb 0.808, and private 0.810.<br>
should do things:<br>
1 should continue optimize our net with casual conv(because transformer like is a global attention, some local correlation maybe ignored) and gru, but finally have no time<br>
2 should try big net continue</p>
<p>Thanks again to my teammates, they give me a lots of help and let me learn a lot. Going for gold next Compete, keep moving.</p> |
Riiid Answer Correctness Prediction | 3rd place solution (0.818 LB): The 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: Riiid Answer Correctness Prediction
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><ul>
<li><strong>2021-01-16 edit 2</strong>: added missing linear layers after categorical embeddings + tag features to diagram</li>
<li><strong>2021-01-16 edit 1</strong>: the <a href="https://github.com/jamarju/riiid-acp-pub" target="_blank">source code</a> is up.</li>
</ul>
<p>Wow, what a ride this has been. First off, thanks <a href="https://www.kaggle.com/sohier" target="_blank">@sohier</a> <a href="https://www.kaggle.com/hoonpyotimjeon" target="_blank">@hoonpyotimjeon</a> Kaggle, Riiid and everyone involved in setting up this challenging competition.</p>
<p>Congratulations to #1 and #2 <a href="https://www.kaggle.com/keetar" target="_blank">@keetar</a> and <a href="https://www.kaggle.com/mamasinkgs" target="_blank">@mamasinkgs</a>!!! We truly look forward to reading about your solutions!</p>
<p>Also huge thanks to my teammate <a href="https://www.kaggle.com/antorsae" target="_blank">@antorsae</a> who joined me in the last stretch and without whose ideas, intuition and hardware I wouldn’t have gotten this far.</p>
<p>I was attracted to this competition by the relatively small dataset footprint compared to my other two previous competitions (deep fakes and RSNA pulmonary embolisms) but this ended up being much more resource intensive than I anticipated.</p>
<p>Our solution is a mixture of two Transformer models with carefully crafted attention, engineered features and a time-aware adaptive ensembling mechanism we nick-named “The Blindfolded Gunslinger”.</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F3076212%2F59b490f2f38b6d8b2412e5fd83585d2c%2Fblindfolded.jpg?generation=1610064421822590&alt=media" alt=""></p>
<p>(“Blindfolded gunslinger” hand-drawn by <a href="https://www.kaggle.com/antorsae" target="_blank">@antorsae</a> inspired by Red Dead Redemption 2)</p>
<h1>The Transformer</h1>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F3076212%2F2bba4e4717ba0cc0f7e6af00dfe4a709%2FEsquemaRiid%202.jpg?generation=1610837878777203&alt=media" alt=""></p>
<p>We use two transformers trained separately with 2.5% of the users held out for validation and sequences of 500 interactions. At train we simply split user stories in 500 non-overlapping interaction chunks and sample the chunks randomly.</p>
<ul>
<li>Transformer 1: 3+3 layers (encoder+decoder), no LayerNorms, <a href="http://www.cs.toronto.edu/~mvolkovs/ICML2020_tfixup.pdf" target="_blank">T-Fixup init</a> see paper for reasons why we used it, ReLU activations, d_model=512</li>
<li>Transformer 2: 4+4 layers, no LayerNorms, T-Fixup init, GELU activations, d_model=512</li>
</ul>
<p>We feed both the encoder and the decoder ALL the features. We use learned features for continuous variables (simply projecting them to d_model) and for categorical variables we first map it to embeddings with low dimensionality and then project it also to d_model=512 (to avoid potential overfitting). We use an embedding bag for question tags.</p>
<p>To prevent the transformer from looking into the future we shift the encoder input including both questions + answers to the right, hide all the answer-specific features from the decoder (user_answer, answered_correctly, qhe, qet), ie. those that are not immediately available upon inferring the interaction and use the appropriate attention masks in all 3 attentions.</p>
<p>To our surprise the 3+3 model outperformed its bigger 4+4 brother even if we tried to finetune the latter at the final hours of the competition.</p>
<h1>Engineered features</h1>
<p>This was a very rich dataset but we found the following derived features helped the transformer converge faster and reach a higher AUROC score. A lot of them have been discussed in the forum:</p>
<ul>
<li><code>qet</code>, <code>qhe</code>: these are the <code>prior_qet</code> and <code>prior_qhe</code> counterparts shifted upwards one container. This was probably discussed first by <a href="https://www.kaggle.com/doctorkael" target="_blank">@doctorkael</a> here: <a href="https://www.kaggle.com/c/riiid-test-answer-prediction/discussion/194184" target="_blank">https://www.kaggle.com/c/riiid-test-answer-prediction/discussion/194184</a></li>
<li><code>tsli</code>: time since list interaction, AKA timestamp delta. Discussed in many threads.</li>
<li><code>clipped_tsli</code>: <code>tsli</code> clipped to 20 minutes. <a href="https://www.kaggle.com/claverru" target="_blank">@claverru</a> hinted at this in the Saint benchmark mega-thread: <a href="https://www.kaggle.com/c/riiid-test-answer-prediction/discussion/195632" target="_blank">https://www.kaggle.com/c/riiid-test-answer-prediction/discussion/195632</a></li>
<li><code>ts_mod_1day</code>: <code>timestamp</code> modulus 1 day. This may reveal daily patterns such as the user being more / less attentive / tired in the mornings / after work, etc.</li>
<li><code>ts_mod_1week</code>: timestamp modulus 1 week. We similarly hope this will reveal weekly patterns (are “mondays” a bad day? etc.)</li>
<li><code>attempt_num</code>, <code>attempts_correct</code>, <code>attempts_correct_avg</code>: about 11% of the questions were <strong>repeated</strong> questions, so it made a lot of sense to keep a record of which question had been answered by whom and how many times it was answered correctly. This was revealed by <a href="https://www.kaggle.com/aravindpadman" target="_blank">@aravindpadman</a> in his great thread: <a href="https://www.kaggle.com/c/riiid-test-answer-prediction/discussion/194266" target="_blank">https://www.kaggle.com/c/riiid-test-answer-prediction/discussion/194266</a> and it was an extremely demanding feature to code since it takes a total of 11.2 GB of space at inference all by itself.</li>
</ul>
<h1>Attention</h1>
<p>Our architecture follows the auto-regressive application of sequence to sequence transformers, so a causal attention mask is needed to make sure a given interaction cannot attend to interactions in the future; however there is an exception to this which we believe is critical: interaction grouped by the same task_container_id.</p>
<p>We compute separate attention masks for the encoder and decoder, preventing the encoder self-attention from attending past interactions if they belong to the same task_container_id, and conversely modifying the decoder self-attention to allow to attend to all interaction belonging to the same task_container_id, we further restrain the output of the encoder to the decoder with the encoder attention to prevent a leakage of information from the residual connections in the encoder.</p>
<pre><code>causal_mask = ~torch.tril(torch.ones(1,sl, sl,dtype=torch.bool,device=x_cat.device)).expand(b,-1,-1)
x_tci = x_cat[...,Cats.task_container_id]
x_tci_s = torch.zeros_like(x_tci)
x_tci_s[...,1:] = x_tci[...,:-1]
enc_container_aware_mask = (x_tci.unsqueeze(-1) == x_tci_s.unsqueeze(-1).permute(0,2,1)) | causal_mask
dec_container_aware_mask = ~(x_tci.unsqueeze(-1) == x_tci.unsqueeze(-1).permute(0,2,1)) & causal_mask
</code></pre>
<h1>The Blindfolded Gunslinger</h1>
<p>We made a joke in the <a href="https://www.kaggle.com/c/riiid-test-answer-prediction/discussion/208356#1137339" target="_blank">meme thread</a> about us wanting to ensemble multiple models, but the competition having only 9 hours to run full inference…</p>
<p>It was already reported that the public test set was sitting on <a href="https://www.kaggle.com/c/riiid-test-answer-prediction/discussion/203383#1115680" target="_blank">the first 20% of the test set</a> so it is possible to maximize the allotted time for the private test set by skipping model inference in the first 20% and predicting only the last 80%. </p>
<p>We implemented dynamic ensembling that attempts to perform as much ensembling as it is possible in the allotted time for the last 80%.</p>
<p>We dubbed this idea “The Blindfolded Gunslinger” because it fires two guns (models) as much as it can (after a while it will only fire one) but it is blindfolded in the sense that the public LB will be ~0.5 so we cannot be sure if it worked or not until now…</p>
<h1>Hardware</h1>
<ul>
<li>1 computer with Ryzen 3950x (16c32t) + 64 Gb RAM + 1x3090</li>
<li>1 computer with Threadripper 1950x (16c32t) + 256 Gb RAM + 6x3090</li>
</ul>
<p>We set up the big computer during the competition which was a project on its own:</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F3076212%2Ff1186277b6c2045ba9c00053192d6be2%2Fpasted%20image%200.png?generation=1610065136682440&alt=media" alt=""></p>
<p>Also in the last 8 hours of the competition we rented a 190 Gb RAM + 6x3090 but it did not help us much.</p>
<h1>Software</h1>
<p>We used pytorch 1.7.1, fastai and we trained using distributed training and mixed precision (both as implemented in fastai). </p>
<p>For inference we included the last 500 interactions and summaries in both pickle files and memory-mapped numpy matrices.</p>
<h1>Source code</h1>
<p>Available at: <a href="https://github.com/jamarju/riiid-acp-pub" target="_blank">https://github.com/jamarju/riiid-acp-pub</a></p> |
Mechanisms of Action (MoA) Prediction | 3rd Place Public - We Should Have Trusted CV - 118th Private | 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: Mechanisms of Action (MoA) Prediction
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h1>Please Congratulate my Teammates - Thank You</h1>
<p>In every competition, i'm the one saying "trust your CV" and often I post a reliable validation scheme such as my double stratified <a href="https://www.kaggle.com/c/lish-moa/discussion/195195" target="_blank">here</a> for MOA comp.</p>
<p>In this competition, I analyzed the public test for 2 weeks and was convinced that the test dataset was significantly different than the training dataset. Thus I encouraged my teammates to "<strong>not</strong> trust our CV" and instead, I post processed all of our teams' submissions. <strong>Big Mistake!</strong></p>
<p>Please help me congratulate my teammates. </p>
<ul>
<li>Intwzt <a href="https://www.kaggle.com/intwzt" target="_blank">@intwzt</a></li>
<li>Mizanur <a href="https://www.kaggle.com/mizanurr" target="_blank">@mizanurr</a> </li>
<li>Phi <a href="https://www.kaggle.com/ajinomoto132" target="_blank">@ajinomoto132</a> </li>
<li>Reza <a href="https://www.kaggle.com/vaghefi" target="_blank">@vaghefi</a></li>
</ul>
<p>They built 12 incredible models of 12 different types which beat all the public notebooks of that type. They worked day and night and a simple average (without weights) of their models would have achieved 11th place gold. I applied post process to all our submissions and decreased our position to 118th. </p>
<p>I apologize for my post process. Below I describe their models and I describe my post process. Our final Kaggle notebook with (detrimental) post process can be seen <a href="https://www.kaggle.com/cdeotte/3rd-place-public-lb-1805/" target="_blank">here</a> </p>
<h1>TabNet - LB 1830 (private 1622)</h1>
<p><a href="https://www.kaggle.com/josemori" target="_blank">@josemori</a> <a href="https://www.kaggle.com/hiramcho" target="_blank">@hiramcho</a><br>
<a href="https://www.kaggle.com/josemori/moa-tabnet?scriptVersionId=44549085" target="_blank">https://www.kaggle.com/josemori/moa-tabnet?scriptVersionId=44549085</a>. <br>
<a href="https://www.kaggle.com/hiramcho/moa-tabnet-with-pca-rank-gauss?scriptVersionId=45407015" target="_blank">https://www.kaggle.com/hiramcho/moa-tabnet-with-pca-rank-gauss?scriptVersionId=45407015</a><br>
These public notebooks achieve LB 1848. We improved these notebooks to achieve LB 1830 and excellent CV. Our TabNet code is <a href="https://www.kaggle.com/intwzt/inference-tabnet-1830" target="_blank">here</a></p>
<h1>DAE (denoising autoencoder) - LB 1830 (private 1628)</h1>
<p><a href="https://www.kaggle.com/felipebihaiek" target="_blank">@felipebihaiek</a><br>
<a href="https://www.kaggle.com/felipebihaiek/prediction-with-swap-auto-encoder-features-0-01865?scriptVersionId=46316906" target="_blank">https://www.kaggle.com/felipebihaiek/prediction-with-swap-auto-encoder-features-0-01865?scriptVersionId=46316906</a><br>
This public notebook achieves LB 1865. We improved it to LB 1830 and CV 1560 (double stratified with control). Our DAE code is <a href="https://www.kaggle.com/c/lish-moa/discussion/200680" target="_blank">here</a></p>
<h1>EffNet (deepinsight images) - LB 1840 (private 1618)</h1>
<p><a href="https://www.kaggle.com/markpeng" target="_blank">@markpeng</a><br>
<a href="https://www.kaggle.com/markpeng/deepinsight-efficientnet-b3-noisystudent" target="_blank">https://www.kaggle.com/markpeng/deepinsight-efficientnet-b3-noisystudent</a><br>
This public notebook achieves LB 1861. We improved it to achieve 1840 and CV 1495 (single stratified with control). Our EffNet code is <a href="https://www.kaggle.com/ajinomoto132/efficientnet-swish-augmentation-training" target="_blank">here</a></p>
<h3>NVIDIA <a href="https://rapids.ai/start.html" target="_blank">RAPIDS</a> UMAP</h3>
<p>For diversity some EffNet DeepInsight models use images made from <a href="https://rapids.ai/start.html" target="_blank">RAPIDS</a> UMAP instead of TSNE using <code>import cuml</code> and <code>cuml.UMAP()</code>. These models score the best private LB score of all single models!</p>
<h1>MX10 (transfer learning) - LB 1842 (private 1628)</h1>
<p><a href="https://www.kaggle.com/tolgadincer" target="_blank">@tolgadincer</a><br>
<a href="https://www.kaggle.com/tolgadincer/moa-tensorfow-mx10" target="_blank">https://www.kaggle.com/tolgadincer/moa-tensorfow-mx10</a><br>
This public notebook achieves 1862. We improved it to achieve 1842 and excellent CV. Our MX10 code is <a href="https://www.kaggle.com/intwzt/updated-inference-final-mx10-transfer" target="_blank">here</a></p>
<h1>PyTorch NN - LB 1833 (private 1619)</h1>
<p><a href="https://www.kaggle.com/thehemen" target="_blank">@thehemen</a> <a href="https://www.kaggle.com/kushal1506" target="_blank">@kushal1506</a> <a href="https://www.kaggle.com/riadalmadani" target="_blank">@riadalmadani</a><br>
<a href="https://www.kaggle.com/thehemen/pytorch-transfer-learning-with-k-folds-by-drug-ids?scriptVersionId=46944058" target="_blank">https://www.kaggle.com/thehemen/pytorch-transfer-learning-with-k-folds-by-drug-ids?scriptVersionId=46944058</a><br>
This public notebook achieves LB 1835. We improved it to achieve LB 1833 and CV 1560 (double stratified with control)</p>
<h1>Diversity</h1>
<p>Here is a correlation plot of our 12 models showing their diversity. Each model has about 30 folds (for 360 models total). We upload trained fold models, and our Kaggle notebook infers all 360 models in 50 minutes commit and 100 minutes submit! Our submission notebook is <a href="https://www.kaggle.com/cdeotte/3rd-place-public-lb-1805/" target="_blank">here</a></p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1723677%2F1dfeee89deeecc810f995b8e8e8f3214%2Fcorr.png?generation=1606795896928096&alt=media" alt=""></p>
<h1>Our Best CV scores Private LB 1603 and 11th Place Gold!</h1>
<p>If we use our best CV and do not post process our final submission, we achieve private LB 1603 and public LB 1816. (Post process improves public LB by 0.00011 and degrades private LB by 0.00008)<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1723677%2Fba6a39001ebfd95ca087a7aeaec028ad%2FLB.png?generation=1606792461633187&alt=media" alt=""></p>
<h1>Post Process Explained</h1>
<p>If you plot the predictions and log loss of each target separately, you will discover that models cannot recognize certain targets. For these difficult targets models simply predict the mean value from the train dataset for all test rows. See the two examples below. The x axis is row index. The y axis is prediction probability.</p>
<h3>Model Does Not Recognize Adrenergic_Receptor_Antagonist</h3>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1723677%2Fc11158914af3b8c4a1a91a3745930728%2Fno.png?generation=1606791968334845&alt=media" alt=""></p>
<h3>Model Does Recognize CDK_Inhibitor</h3>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1723677%2F7df2dc2d1ba64fa4b2137d26e950a94e%2Fyes.png?generation=1606792014668054&alt=media" alt=""></p>
<h1>What is Test Mean?</h1>
<p>If the test dataset has a different distribution than train, then a target that is rare in train may occur often in test. And a target that occurs often in train may occur rare in test. If we have no idea about the test dataset mean and our model does not recognize a target, it is better to predict a mean closer to the average of all target means. Therefore we post processed our predictions by multiplying the unrecognized "often" target predictions by 0.75 and we multiply the unrecognized "rare" target predictions by 4. (actual multipliers vary based on train mean and statistical expectation and can be seen in the notebook <a href="https://www.kaggle.com/cdeotte/3rd-place-public-lb-1805/" target="_blank">here</a>).</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1723677%2Fb7014baf8fa77703d2a6955f33be2dd9%2Fpot.png?generation=1606792283964252&alt=media" alt=""></p>
<h1>Post Process Improves Public LB 0.00011</h1>
<p>The above post process improves public LB by 0.00011. It is not tuned to public test dataset specifically. If our models are predicting any dataset that has a distribution different than train dataset, then our post process will improve log loss. Unfortunately, private dataset is similar to train and our post process hurts our private LB by 0.00008 (The distribution of test dataset is explained <a href="https://www.kaggle.com/c/lish-moa/discussion/200832" target="_blank">here</a>)</p>
<h1>Thank you Kaggle</h1>
<p>Thank you everyone for posting so many interesting notebooks and discussions. I learned so many new ways from the community and my teammates to build models for tabular data such as TabNet, DeepInsight EffNet, Transfer Learning, Residual MLPs. I learned new feature engineering techniques using Autoencoding, PCA, ICA, Factor Analysis, FeatureAgglomeration, KernelPCA, Quantile Transformer, and many others! This has been a great competition! </p>
<p>We posted our final submission notebook <a href="https://www.kaggle.com/cdeotte/3rd-place-public-lb-1805/" target="_blank">here</a>. Our TabNet code that scores LB 1830 <a href="https://www.kaggle.com/intwzt/inference-tabnet-1830" target="_blank">here</a>. Our DAE that scores LB 1830 <a href="https://www.kaggle.com/c/lish-moa/discussion/200680" target="_blank">here</a>. Our EffNet code that scores LB 1840 with 4 seeds <a href="https://www.kaggle.com/ajinomoto132/efficientnet-swish-augmentation-training" target="_blank">here</a>. And our MX10 that scores LB 1842 <a href="https://www.kaggle.com/intwzt/updated-inference-final-mx10-transfer" target="_blank">here</a></p> |
Riiid Answer Correctness Prediction | 4th place solution : Single Transformer 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: Riiid Answer Correctness Prediction
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Hi everyone,<br>
It has been a real pleasure competing in this wonderful challenge. Thank you Kaggle and the Competition Host for making it possible.</p>
<p>I'm happy to share here my solution which got me to the 4th place. It is a single transformer model inspired from previous works (like <em>SAINT, SAKT</em>) very much discussed in this competition. </p>
<h1>The model</h1>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F37949%2F2ec8f0682b82bb47954f2816f221093b%2Friiid-model%20(1).png?generation=1610229212586102&alt=media" alt="Riiid 4th solution model architecture"><br>
I hope my figure is straightforward. Below are key features of the model I'd like to explain more:</p>
<h3>Input sequences</h3>
<p>I tried to include all data available from the train table and metadata tables. I also add <em>time lag</em>, which is the delta time from the previous interaction (questions in the same container have the same timestamp so they share the same <em>time lag</em>). <br>
Also, on the question table, I added 2 features : difficulty level (<em>correct response rate</em> of each questions), popularity (<em>number of appearances</em>), which are computed from the whole training data.</p>
<h3>Input embeddings</h3>
<p>Same size of embeddings for all inputs, the embeddings are then concatenated and go through linear transform to feed to the first encoder and decoder of the transformer.</p>
<p>Embeddings of continuous features (<em>time lag</em>, <em>question elapsed time</em>, <em>question difficulty</em>, <em>question popularity</em>) are computed using a <em>ContinuousEmbedding</em> layer. The idea of <em>ContinuousEmbedding</em> is to sum up <code>(</code>weighted sum<code>)</code> a number of consecutive embedding vectors (from the embedding <em>weight matrix</em>). <br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F37949%2F13b93a94023bb1ee627b220204f34272%2FContinuousEmbeddings.png?generation=1610279445750633&alt=media" alt=""><br>
This way we have a "smooth" version for the embeddings of the continuous variable: 2 values very close together should have similar embeddings. </p>
<h3>The transformer</h3>
<p>Input of the encoder are embeddings of all input elements. Input of the decoder doesn't not contain user answer related elements.<br>
Encoder and decoder layers are almost the same as in the original paper (<a href="https://arxiv.org/abs/1706.03762" target="_blank">Attention is all you need</a>).<br>
One key difference is of course the causal masks to prevent the current position from seeing the future. The other is a feature that I add to improve the performance and convergence speed : a kind of time aware weighted attention. The idea is to decay the attention coefficient by a factor of \(dt^{-w}\) where \(dt\) is the difference in timestamp of a position and the position it attends to and \(w\) is a trainable parameter constrained to be non-negative <code>(</code>one parameter per attention head<code>)</code>. This is pretty easy to implement: compute the timestamp difference matrix in log scale, multiply it with the parameters \(w\) and subtract it from the attention logits (<em>scaled dot product</em> output of the attention layer).</p>
<h1>Training</h1>
<p>I use the cv method <a href="https://www.kaggle.com/its7171/cv-strategy" target="_blank">https://www.kaggle.com/its7171/cv-strategy</a> (thanks <a href="https://www.kaggle.com/its7171" target="_blank">@its7171</a>). The model was implemented in Tensorflow and trained on TPU with Colab Pro.<br>
Sequences are randomly cut and padded to have the same length and all parts are kept for training.<br>
The final version of my model has embeddings size of 128, model size of 512, 4 encoder layers and 4 decoder layers. <br>
It was trained with the sequence length of 1024 for about 36000 steps (<em>warmup</em> 4000 steps then cosine decay) and with batch size 64. Training took about 4-5 hours.<br>
On the submission kernel I had to reduce sequence length to 512 due to resource limit.</p>
<h1>Some observations</h1>
<ul>
<li>Input embeddings: concatenation is better than sum</li>
<li>Longer sequence <code>(</code>for both training and inference<code>)</code> improves the performance</li>
<li>Model size also matters: bigger model size generally improves the performance but going beyond size of 512 and 4 layers does not improve much. </li>
</ul>
<h1>Why not ensemble</h1>
<p>I didn't have much time toward the end of the competition. When I still made improvement on my single model I made the choice of staying on that rather than spending time on making ensemble of smaller models. I'm not sure it was a good choice, but it got me this far so I'm still happy. </p>
<h1>Code</h1>
<p><a href="https://www.kaggle.com/letranduckinh/riiid-model-submission-4th-place-public-version" target="_blank">Here</a> is the submission kernel that I made public. You should find all my code source training log in the kernel. <br>
As you can see it scores 0.8180 on valid set, 0.815 on public LB and 0.817 on private LB.<br>
My top scored submission has the same model and training configuration but was trained on the whole training set, which did not improve much.</p>
<p><a href="https://github.com/dkletran/riiid-challenge-4th-place" target="_blank">Here</a> is the source code on github including all steps to reproduce the solution.</p>
<h3>Best regards to all</h3> |
Riiid Answer Correctness Prediction | 38th place solution: Single SAINT+ | 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: Riiid Answer Correctness Prediction
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>First of all, thank you to the host and Kaggle team for the competition. I think it is a very useful challenge for those who want to try transformer models outside of the nlp. I would also like to thank everyone who shared their ideas for this competition. I can say that it contributed to my learning journey in many ways.</p>
<p>Thank you to Tito and his great <a href="https://www.kaggle.com/its7171/lgbm-with-loop-feature-engineering" target="_blank">notebook</a> about loop for feature engineering<br>
Thank you to Mark and his great <a href="https://www.kaggle.com/markwijkhuizen/riiid-training-and-prediction-using-a-state" target="_blank">notebook</a> for the harmonic mean idea. </p>
<h2>Results</h2>
<p>My local train/val AUC: <strong>0.804</strong> / <strong>0.806</strong><br>
I already knew the difference between my public and private lb score, because of the private leak.<br>
As a CV strategy, I used a similar but not the same as tito.</p>
<h2>Model details</h2>
<p>The model structure is very much the same as <a href="https://arxiv.org/abs/2010.12042" target="_blank">SAINT+</a> paper, except below parameters.</p>
<ul>
<li>2 encoder - 2 decoder layers</li>
<li>256 embed dim</li>
<li>0.1 dropout for attention layers, 0.2 dropout for fully connected heads at the end of the encoder-decoder layers</li>
<li>100 seq length</li>
</ul>
<p><strong>Encoder embeddings (Known features)</strong></p>
<ul>
<li>Pos embedding (Categorical)</li>
<li>Question id embedding (Categorical)</li>
<li>Bundle id embedding (Categorical)</li>
<li>Part embedding (Categorical)</li>
<li>Question encoded tag embedding (New number for each unique value) (Categorical)</li>
<li>Question attempt embedding (Categorical)</li>
<li>Lag time embedding (current task timestamp - prev task timestamp) (Categorical)</li>
<li>Harmonic mean embedding (Continuous)</li>
</ul>
<p><strong>Decoder embeddings (Future features)</strong><br>
<em>All features shifted/adjusted</em></p>
<ul>
<li>Pos embedding - same embedding layer for encoder (Categorical)</li>
<li>Answer embedding (Categorical)</li>
<li>Elapsed time (Categorical)</li>
<li>Answer bundle id - same embedding layer for bundle id (Categorical)</li>
</ul>
<h2>Training:</h2>
<ul>
<li>25 epoch, train almost took 7-8 hours on GPU, inference 3-4 hours</li>
<li>Adam with 1e-3 lr for first 20 epoch, then 1e-4 last 5 epoch</li>
<li>128 batch size</li>
</ul>
<p>Notebook <a href="https://www.kaggle.com/fomdata/38th-solution-saint-model" target="_blank">link</a></p> |
Riiid Answer Correctness Prediction | [0.805 Private, 42nd place] LGB + 5 RAINT+ 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: Riiid Answer Correctness Prediction
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>This is the 2nd competition I have attended and the 1st competition I got top 50, share the final Model I used. Please free feel to comment.<br>
<strong>Ensemble</strong><br>
<strong>AUC</strong> Private: 0.805, Public: 0.803</p>
<pre><code>saint_models = [saint1, saint2, saint3, saint4, saint5]
saint_weights = [0.09, 0.091, 0.116, 0.168, 0.368]
lgb_w = 0.167
</code></pre>
<p>With <strong>fully optimized implementation</strong>, the online inference running time with these <strong>6</strong> models is about <strong>3</strong> hours(<strong>GPU</strong> on)</p>
<h2>LGBM</h2>
<p><strong>73 features</strong> AUC 0.787 in both public and private</p>
<pre><code> 0:{'name': 'prior_question_elapsed_time'}
1:{'name': 'prior_question_had_explanation', 'dim_type': 'categorical'}
2:{'name': 'ques_part', 'dim_type': 'categorical'}
3:{'name': 'user_ans_acc', 'depends': ['user_ans_corr_cnt', 'user_ans_cnt'], 'cal_func': 'div', 'desc': 'user questions answering accuracy'}
4:{'name': 'user_ans_cnt', 'desc': 'number of questions the user answered'}
5:{'name': 'user_ans_corr_cnt', 'desc': 'number of correct answers the user gave'}
6:{'name': 'user_ques_part_1_cnt', 'desc': 'number of answers the user answered that are part 1'}
7:{'name': 'user_ques_part_1_corr_cnt', 'desc': 'number of correct answers the user gave to the questions that are part 1'}
8:{'name': 'user_ques_part_1_acc', 'depends': ['user_ques_part_1_corr_cnt', 'user_ques_part_1_cnt'], 'cal_func': 'div'}
9:{'name': 'user_ques_part_2_cnt'}
10:{'name': 'user_ques_part_2_corr_cnt'}
11:{'name': 'user_ques_part_2_acc', 'depends': ['user_ques_part_2_corr_cnt', 'user_ques_part_2_cnt'], 'cal_func': 'div'}
12:{'name': 'user_ques_part_3_cnt'}
13:{'name': 'user_ques_part_3_corr_cnt'}
14:{'name': 'user_ques_part_3_acc', 'depends': ['user_ques_part_3_corr_cnt', 'user_ques_part_3_cnt'], 'cal_func': 'div'}
15:{'name': 'user_ques_part_4_cnt'}
16:{'name': 'user_ques_part_4_corr_cnt'}
17:{'name': 'user_ques_part_4_acc', 'depends': ['user_ques_part_4_corr_cnt', 'user_ques_part_4_cnt'], 'cal_func': 'div'}
18:{'name': 'user_ques_part_5_cnt'}
19:{'name': 'user_ques_part_5_corr_cnt'}
20:{'name': 'user_ques_part_5_acc', 'depends': ['user_ques_part_5_corr_cnt', 'user_ques_part_5_cnt'], 'cal_func': 'div'}
21:{'name': 'user_ques_part_6_cnt'}
22:{'name': 'user_ques_part_6_corr_cnt'}
23:{'name': 'user_ques_part_6_acc', 'depends': ['user_ques_part_6_corr_cnt', 'user_ques_part_6_cnt'], 'cal_func': 'div'}
24:{'name': 'user_ques_part_7_cnt'}
25:{'name': 'user_ques_part_7_corr_cnt'}
26:{'name': 'user_ques_part_7_acc', 'depends': ['user_ques_part_7_corr_cnt', 'user_ques_part_7_cnt'], 'cal_func': 'div'}
27:{'name': 'ques_acc'}
28:{'name': 'ques_cnt'}
29:{'name': 'ques_corr_cnt'}
30:{'name': 'ques_tags_len', 'dim_type': 'categorical'}
31:{'name': 'user_acc_ques_acc_hmean', 'depends': ['user_ans_acc', 'ques_acc'], 'cal_func': 'harmonic_mean'}
32:{'name': 'ques_part_acc'}
33:{'name': 'user_ques_part_1_acc_ques_part_acc_hmean', 'depends': ['user_ques_part_1_acc', 'ques_part_acc'], 'cal_func': 'harmonic_mean'}
34:{'name': 'user_ques_part_2_acc_ques_part_acc_hmean', 'depends': ['user_ques_part_2_acc', 'ques_part_acc'], 'cal_func': 'harmonic_mean'}
35:{'name': 'user_ques_part_3_acc_ques_part_acc_hmean', 'depends': ['user_ques_part_3_acc', 'ques_part_acc'], 'cal_func': 'harmonic_mean'}
36:{'name': 'user_ques_part_4_acc_ques_part_acc_hmean', 'depends': ['user_ques_part_4_acc', 'ques_part_acc'], 'cal_func': 'harmonic_mean'}
37:{'name': 'user_ques_part_5_acc_ques_part_acc_hmean', 'depends': ['user_ques_part_5_acc', 'ques_part_acc'], 'cal_func': 'harmonic_mean'}
38:{'name': 'user_ques_part_6_acc_ques_part_acc_hmean', 'depends': ['user_ques_part_6_acc', 'ques_part_acc'], 'cal_func': 'harmonic_mean'}
39:{'name': 'user_ques_part_7_acc_ques_part_acc_hmean', 'depends': ['user_ques_part_7_acc', 'ques_part_acc'], 'cal_func': 'harmonic_mean'}
40:{'name': 'user_last_incorr_till_now'}
41:{'name': 'user_last_corr_till_now'}
42:{'name': 'user_ts_diff_lag_1'}
43:{'name': 'user_ts_diff_lag_2'}
44:{'name': 'user_ts_diff_lag_3'}
45:{'name': 'user_last_10_corr_cnt'}
46:{'name': 'user_acc_mov_avg'}
47:{'name': 'user_elapsed_time_sum'}
48:{'name': 'user_viewed_explanations_sum'}
49:{'name': 'user_elapsed_time_avg', 'depends': ['user_elapsed_time_sum', 'user_ans_cnt'], 'cal_func': 'div'}
50:{'name': 'user_viewed_explanations_avg', 'depends': ['user_viewed_explanations_sum', 'user_ans_cnt'], 'cal_func': 'div'}
51:{'name': 'ques_tags_id', 'dim_type': 'categorical'}
52:{'name': 'ques_tags_acc'}
53:{'name': 'user_ques_tags_cnt'}
54:{'name': 'user_ques_tags_corr_cnt'}
55:{'name': 'user_ques_tags_acc', 'depends': ['user_ques_tags_corr_cnt', 'user_ques_tags_cnt'], 'cal_func': 'div'}
56:{'name': 'user_ques_tags_max_cnt'}
57:{'name': 'user_ques_tags_max_corr_cnt'}
58:{'name': 'user_ques_tags_max_acc', 'depends': ['user_ques_tags_max_corr_cnt', 'user_ques_tags_max_cnt'], 'cal_func': 'div'}
59:{'name': 'user_ques_tags_min_cnt'}
60:{'name': 'user_ques_tags_min_corr_cnt'}
61:{'name': 'user_ques_tags_min_acc', 'depends': ['user_ques_tags_min_corr_cnt', 'user_ques_tags_min_cnt'], 'cal_func': 'div'}
62:{'name': 'ques_prior_elapsed_time_avg'}
63:{'name': 'ques_prior_had_explan_avg'}
64:{'name': 'ques_prior_had_explan_acc'}
65:{'name': 'ques_prior_hadnot_explan_acc'}
66:{'name': 'ques_elapsed_time_avg'}
67:{'name': 'ques_elapsed_time_std'}
68:{'name': 'ques_explan_avg'}
69:{'name': 'ques_u_ans_std'}
70:{'name': 'ques_n_answers'}
71:{'name': 'user_lect_viewed'}
72:{'name': 'user_lect_viewed_over_ques_answered', 'depends': ['user_lect_viewed', 'user_ans_cnt'], 'cal_func': 'div'}
</code></pre>
<h2>RAINT+</h2>
<p><strong>1</strong> RAINT+ with 4 encoders/decoders<br>
encoder side inputs: questions, question parts, timestamp lags<br>
decoder side inputs: response, timestamp lags<br>
Private: 0.799, Public: 0.797</p>
<pre><code>saint1_cfg = SaintModelConfig(
n_enc=4,
n_dec=4,
enc_heads=8,
dec_heads=8,
seq_len=100,
n_dims=128,
n_ques=13523,
n_parts=7,
n_ets=301,
n_lts=154,
n_resp=2,
n_explains=2,
emb_add_fn="add",
dropout=0.2,
)
</code></pre>
<p><strong>2</strong> RAINT+ with 6 encoders/decoders<br>
encoder/decoder inputs are the same as the 1st one<br>
Concat the embedding of the inputs and * W (shape: N x 128)<br>
Private: 0.798, Public: 0.796</p>
<pre><code>saint2_cfg = SaintModelConfig(
n_enc=6,
n_dec=6,
enc_heads=8,
dec_heads=8,
seq_len=100,
n_dims=128,
n_ques=13523,
n_parts=7,
n_ets=301,
n_lts=154,
n_resp=2,
n_explains=2,
n_freqs=111,
n_corr_freqs=94,
emb_add_fn="cat",
dropout=0.2,
enc_extra_inputs=tuple(),
emb_with_bias=True
)
</code></pre>
<p><strong>3</strong> RAINT+ with 4 encoders/decoders<br>
Adding question frequency/correct frequency to encoder side, other parts the same as the 1st one</p>
<pre><code>saint3_cfg = SaintModelConfig(
n_enc=4,
n_dec=4,
enc_heads=8,
dec_heads=8,
seq_len=100,
n_dims=128,
n_ques=13523,
n_parts=7,
n_ets=301,
n_lts=154,
n_resp=2,
n_explains=2,
n_freqs=111,
n_corr_freqs=94,
emb_add_fn="add",
dropout=0.2,
enc_extra_inputs=("freqs", "corr_freqs")
)
</code></pre>
<p><strong>4</strong> RAINT+ with 4 encoders/decoders<br>
Adding tags_id to the encoder side, other parts the same as the 3rd one<br>
Private: 0.802, Public: 0.800</p>
<pre><code>saint4_cfg = SaintModelConfig(
n_enc=4,
n_dec=4,
enc_heads=8,
dec_heads=8,
seq_len=100,
n_dims=128,
n_ques=13523,
n_parts=7,
n_ets=301,
n_lts=154,
n_resp=2,
n_explains=2,
n_freqs=111,
n_corr_freqs=94,
emb_add_fn="add",
dropout=0.2,
enc_extra_inputs=("freqs", "corr_freqs", "tag_ids")
)
</code></pre>
<p><strong>5</strong> RAINT+ with 4 encoders/decoders<br>
Concatenating embedding outputs * W (shape: N x 128, bias=False), other parts are the same as the 4th one.<br>
Didn't submit alone.</p>
<pre><code>saint5_cfg = SaintModelConfig(
n_enc=4,
n_dec=4,
enc_heads=8,
dec_heads=8,
seq_len=100,
n_dims=128,
n_ques=13523,
n_parts=7,
n_ets=301,
n_lts=154,
n_resp=2,
n_explains=2,
n_freqs=111,
n_corr_freqs=94,
n_tag_ids=1520,
emb_add_fn="cat",
dropout=0.2,
enc_extra_inputs=("freqs", "corr_freqs", "tag_ids"),
emb_with_bias=False
)
</code></pre> |
Mechanisms of Action (MoA) Prediction | 5th place solution [Updated] | 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: Mechanisms of Action (MoA) Prediction
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thank you to my team mate Anna, all participants, Kaggle Admin, Laboratory for Innovation Science at Harvard who realized this exciting competition. I would like to briefly share our 5th place solution.</p>
<h2>Problem settings</h2>
<p>The most difficult problem in this competition seems to be that there are both seen and unseen drugs in the test set. This makes construction of the reliable validation difficult.</p>
<h2>Validation strategies and their properties</h2>
<p>In this competition, there are mainly two types of validation strategies used. One is traditional MultilabelStratifiedKFold, and the other is MultilabelStratifiedGroupKFold which is a group awared one (aka Chris's method). Seeing predictions by models based on these schemes, MultilabelStratifiedKFold seems to give more confident predictions for seen drugs, whereas MultilabelStratifiedGroupKFold gives more balanced and robust predictions which are supposed to be suitable for unseen drugs. I thought that both are useful in different ways.<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F570506%2F57b2c2c0ead74739285e3c32cca0cbd5%2FScreen%20Shot%200002-12-01%20at%209.22.30.png?generation=1606782173177185&alt=media" alt=""></p>
<h2>Our approach</h2>
<p>The setting where both seen and unseen labels are observed in the test set is similar to that in <br>
<a href="https://www.kaggle.com/c/bengaliai-cv19" target="_blank">Bengali.AI Handwritten Grapheme Classification</a>. So we decided to discriminate seen and unseen drugs by metric learning (L2 Softmax -> cosine similarity) and then blended models trained on each validation scheme based on the similarity. This separation of seen/unseen seems to be possible to some extent as shown in the figure below. This approach does not require something like pseudo-labelling & retraining. Simple forward processing is enough.<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F570506%2F0543298668876b7bcae89f4f82ae2d3e%2FSeen_Unseen.png?generation=1606782212125156&alt=media" alt=""></p>
<h2>Features</h2>
<p>Raw cell and genes<br>
PCA<br>
rankGauss<br>
PolynominalFeatures<br>
Simple statistics like mean, min, max, skew, kurt, (X_train>9).sum(axis=1)<br>
etc.</p>
<h2>Models</h2>
<ul>
<li>ResNet-like shallow NN</li>
<li>TabNet<br>
For especially models for unseen drugs, we used simple networks.</li>
</ul>
<h2>Reconstruction of drug_id [Updated]</h2>
<p>From the very beginning of the competition, I was validating my models based on a method nearly equivalent to Chris CV. For this purpose, I reconstructed drug_id by heuristic methods, including clustering and many manual adjustments. The official drug_id was published in the later stages of the competition, but many participants may have already overfitted. Once anyone has produced a good Public LB score, it's very hard to suspect that it's overfitting. The temptation and pleasure of running up LB is so intense.</p>
<p>Below are the CV results from both methods for the same model. My method worked almost as well as the Chris CV. I switched to Chris CV at the end of the competition because it performed a bit better. I think that Chris CV was good at handling drug_id with lots of observations and was similar to the actual splits.</p>
<table>
<thead>
<tr>
<th>Method</th>
<th>LocalCV</th>
<th>Private</th>
<th>Public</th>
</tr>
</thead>
<tbody>
<tr>
<td>reconstructed drug_id +my CV</td>
<td>0.017173034</td>
<td>0.01613</td>
<td>0.01826</td>
</tr>
<tr>
<td>official drug_id + Chris CV</td>
<td>0.016907018</td>
<td>0.01612</td>
<td>0.01825</td>
</tr>
</tbody>
</table>
<h2>Result</h2>
<p>Public: 0.01812 (14th)<br>
Private: 0.01602 (5th)</p> |
Riiid Answer Correctness Prediction | [LB 125th Position - .795] Pure Feature Engineering .(3M pkl files) Comp & 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: Riiid Answer Correctness Prediction
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>First of all, Thanks a lot Kaggle, Riiid and the everyone who participated! I have learnt a lot from you guys in just 3 months and really out of the box solution attempts and FEs! </p>
<p>And special thanks to my teammates! I have learnt a lot about different topics and FE ideas as well which i definitely couldn't come up on my own.</p>
<p>So coming to our solutions, it's a very simple ensemble of gbm models (~39/41 Features) and a NN (AKT). CV-LB was amazingly in sync, so no surprise there.</p>
<p>Features List -:</p>
<pre><code>['user_resid_rolling',
'sum_answered_correctly_user',
'count_user',
'content_attempt',
'lag_1',
'lag_2',
'lag_3',
'lag_4',
'lag_5',
'lag_sum_5',
'part',
'tags1',
'prior_question_had_explanation_enc',
'count_content',
'sum_answered_correctly_content',
'mean_answered_correctly_content',
'prior_question_elapsed_time',
'mean_explanation_content',
'mean_elapsed_content',
'theta_user_ct', # from elo
'theta_user_pt', # from elo
'theta_user_bd', # from elo
'content_id',
'last_lec_ts',
'diff_to_last_lec_ts',
'num_lects_watched',
'answer_1',
'answer_2',
'answer_3',
'answer_4',
'answer_5',
'answer_6',
'answer_7',
'last_7_answers_sum',
'correct_answer',
'n_tasks_performed',
'timestamp',
'prev_answer_content',
'diff_content_time',
'mean_answered_correctly_user',
'mean_user_resid_rolling']
</code></pre>
<p>Yes, we did have lecture features like <code>'last_lec_ts', 'diff_to_last_lec_ts', 'num_lects_watched',</code> and they definitely help us improve both, our CV and LB. Other interesting features that we had were not limited but deserve a mention "user_resid_rolling", "diff_content_time", "multiple elo features", "last_7_answers_sum".</p>
<p>"user_resid_rolling" -> </p>
<pre><code>train['content_mean'] = train.groupby('content_id')['answered_correctly'].transform('mean')
train['resid'] = train['answered_correctly'] - train['content_mean']
train['resid'] = train.groupby('user_id')['resid'].shift()
train['user_resid_rolling'] = train.groupby('user_id')['resid'].agg(['cumsum'])
train['user_resid_rolling'] = train['user_resid_rolling'].fillna(0)
train.drop(['resid', 'content_mean'], axis=1, inplace=True)
</code></pre>
<p>"last_lec_ts" & "diff_to_last_lec_ts" -> </p>
<pre><code>prev_u, lec_ts = -1, 0
last_lec_ts = []
for u, c_type, t in zip(train['user_id'], train['content_type_id'], train['timestamp']):
if u != prev_u:
lec_ts = 0
if c_type == True:
lec_ts = t
prev_u = u
last_lec_ts.append(lec_ts)
train['last_lec_ts'] = np.array(last_lec_ts)
train['diff_to_last_lec_ts'] = train['timestamp'] - train['last_lec_ts']
</code></pre>
<p>And the craziest of all FE and a cool FE, <strong>We saved ~.3M pkl files during runtime for the FE "diff_content_time",</strong> (do delete the dir after your inference is complete) (basically for every user difference b/w the TS b/w their current and last TS for a particular content_id)</p>
<pre><code>!mkdir pkld
dct = {}
dct[-1] = 0
prev_u = -1
res = np.zeros(3)
for u, cid, ctype, ts in tqdm(zip(train['user_id'], train['content_id'], train['content_type_id'], train['timestamp'])):
if prev_u != u:
pickle.dump(dct[prev_u], open('pkld/' + str(prev_u) + '.pkl', 'wb'), protocol=pickle.HIGHEST_PROTOCOL)
del dct[prev_u]
dct[u] = {}
if ctype == False:
dct[u][cid] = ts
prev_u = u
pickle.dump(dct[prev_u], open('pkld/' + str(prev_u) + '.pkl', 'wb'), protocol=pickle.HIGHEST_PROTOCOL) #########
del dct
</code></pre>
<p>There were a lot of FE ideas that were tried but didn't help us. To mention few, "tf-idf" on content_ids history of the user, rolling_windows using numba, FTRL's, and other hell lot of FE's ideas that gave marginal boost but we had a rule to add +.001 single-single features in place.</p>
<p>What we regret was definitely not having a SAINT like arch for sure. I messed up badly, should have simply used nn.Transformer rather than handling the encoder/decoder parts myself.</p>
<p>But until next time,</p>
<p>Happy Fair Kaggling & Keep Sharing A Ton!</p>
<p>cc <a href="https://www.kaggle.com/alexj21" target="_blank">@alexj21</a> <a href="https://www.kaggle.com/nikhilmishradev" target="_blank">@nikhilmishradev</a> <a href="https://www.kaggle.com/rohanrao" target="_blank">@rohanrao</a> [Alphabetical Order]. (Please add anything that i missed)<br>
Thanks a lot for the collaboration guys!</p> |
Riiid Answer Correctness Prediction | SAINT+ Model with code [Private 0.800 / 68th 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: Riiid Answer Correctness Prediction
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>I'd like to share our solution. All codes are available on <a href="https://github.com/marisakamozz/riiid" target="_blank">GitHub</a>. You can reproduce our submission with <a href="https://www.kaggle.com/marisakamozz/riiid-saint-solution" target="_blank">this notebook</a>.</p>
<p>I hope it will be helpful to you. Thank you.</p>
<h1>Model Summary</h1>
<ul>
<li><a href="https://arxiv.org/abs/2010.12042" target="_blank">SAINT+</a> based model</li>
<li>used train.csv only.</li>
<li>used questions only.</li>
</ul>
<p>We didn't use lectures, because lectures didn't improve validation score.</p>
<h2>Input</h2>
<p>Encoder input:</p>
<ul>
<li>positional embedding</li>
<li>question_id embedding</li>
<li>lag embedding (= timestamp - last timestamp)</li>
<li>user_count: number of questions the user has solved</li>
</ul>
<p>lag feature is categorized by 100 quantiles.<br>
user_count is categorized by <a href="https://www.kaggle.com/shuntarotanaka/riiid-the-first-30-questions-are-proficiency-test" target="_blank">proficiency test</a>.</p>
<p>Decoder input:</p>
<ul>
<li>positional embedding</li>
<li>answered_correctly</li>
<li>prior_question_elapsed_time</li>
<li>prior_question_had_explanation</li>
</ul>
<p>prior_question_elapsed_time and prior_question_had_explanation are shifted -1.<br>
prior_question_elapsed_time is categorized by 100 quantiles.</p>
<h2>Model Architecture</h2>
<p>Embedding Layer + Tranformer + Feed Forward Layer (with residual connection)</p>
<p>Weights of embedding layers are sampled from a normal distribution with a standard deviation of 0.01.</p>
<p>Transformer architecture:</p>
<ul>
<li>sequence length: 150</li>
<li>number of dimensions: 128</li>
<li>number of encoder layers: 3</li>
<li>number of decoder layers: 3 (self-attention) + 3 (encoder-attention)</li>
<li>number of heads: 8</li>
</ul>
<h2>Training</h2>
<ul>
<li>batch size: 256</li>
<li>optimizer: Adam</li>
<li>training time is almost 20 hours on 1 K80 GPU machine.</li>
<li>early stopping by 1% unseen user's auc score. (but it didn't work well.)</li>
</ul> |
NFL 1st and Future - Impact Detection | 2nd Place Solution: Helmet Detection + 3d Impact Detection + Post Processing | 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: NFL 1st and Future - Impact Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks to both the organisers of this competition and to all of the other competitors - well done to everyone who worked hard over the holiday period!</p>
<p><a href="https://www.kaggle.com/ilu000" target="_blank">@ilu000</a> and <a href="https://www.kaggle.com/robikscube" target="_blank">@robikscube</a> are now competition GMs! Well deserved - congratulations!</p>
<p>Here's the solution from the team <a href="https://www.kaggle.com/christofhenkel" target="_blank">@christofhenkel</a>, <a href="https://www.kaggle.com/ilu000" target="_blank">@ilu000</a>, <a href="https://www.kaggle.com/philippsinger" target="_blank">@philippsinger</a>, <a href="https://www.kaggle.com/robikscube" target="_blank">@robikscube</a>, <a href="https://www.kaggle.com/fergusoci" target="_blank">@fergusoci</a></p>
<h1>Brief Summary</h1>
<p>Our solution is a two stage approach. Our first stage is a YOLOv5 model which detects helmets in each frame of the video. The Stage 2 ensemble consists of various 3D CNN models which use cropped helmet locations and +/- 4 images from frames surrounding the cropped location. Our stage 2 models predict targets by impact type. Finally, we apply post processing to our ensembled staged 2 predictions.</p>
<h1>Detailed Summary</h1>
<p>Below we give a detailed description of our solution:</p>
<h2>Validation strategy</h2>
<p>We used GroupKfold by GameID to create a 5Fold split of the data.</p>
<p>We trained various stage 1 models for helmet detection, both on our KFold splits and on the entire training set. We determined the maximum possible score of a stage 2 model based on our stage 2 bounding boxes would be 0.9868 (out of 1888 impacts, the stage one model predicted matching boxes for 1863 of those).</p>
<h2>Pipeline</h2>
<p>We approached the competition collaboratively, with each team member working off one central pipeline. We used the following:</p>
<ul>
<li>Github: Versioning and code sharing</li>
<li>Neptune: logging and visualisation</li>
<li>Kaggle API: dataset upload/ download</li>
<li>AWS: data storage</li>
<li>Push kaggle dataset github action: <a href="https://github.com/marketplace/actions/push-kaggle-dataset" target="_blank">https://github.com/marketplace/actions/push-kaggle-dataset</a> For automatically pushing github commits to kaggle.</li>
</ul>
<p>We are planning to release our code soon after some clean up.</p>
<h2>Architectures</h2>
<p>Our best stage 2 ensemble consisted of 6 different efficientnets + horizontal flip tta. We replaced the first 2d conv layers in the inverted residual blocks of efficientnet with 3d conv layers as <a href="https://www.kaggle.com/davletag" target="_blank">@davletag</a> did in the <a href="https://www.kaggle.com/c/deepfake-detection-challenge/discussion/158158" target="_blank">Deepfake competition</a>. Hat-tip <a href="https://www.kaggle.com/davletag" target="_blank">@davletag</a>, that also seemed to work well here.</p>
<p>At the last minute we trained 3D Resnext50 & 3D Resnext101 (pretrained on kinetics dataset from <a href="https://github.com/okankop/Efficient-3DCNNs)" target="_blank">https://github.com/okankop/Efficient-3DCNNs)</a>. Although initial results looked promising we lacked time to properly tune hyper-parameters and did not use it in our selected submissions.</p>
<h2>Training strategy/ schedule</h2>
<h3>Stage 1: Helmet detection</h3>
<p>During the competition we trained YOLOv5 per fold using our GroupKfold splits but also adding the extra images. Fortunately, YOLO works out-of-the box with DDP, by simply running torch.distributed.launch so we could speed up training a lot. We used the standard config with pretrained weights and applied put flags</p>
<p>--batch-size 128 <br>
--img-size 704 <br>
--epochs 50 <br>
--data dataset_fold0.yaml <br>
--weights yolov5x.pt <br>
--single-cls </p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F621560%2F364c7b679f147495cf18c959c61aefde%2FScreenshot%202021-01-05%20at%2019.49.09.png?generation=1609876230711342&alt=media" alt=""></p>
<p>For our final submission, we trained on the full data without a validation set. For inference we saw that using the built-in TTA flag and using an img-size of 1280 gives nice improvements of box predictions. We kept all boxes, which had a confidence level greater than 0.05 or 0.1 and went on with assigning labels. Since our stage1 model only detected helmets, i.e. is a single class detector, we need to assign impact/ non-impact labels after we generated the boxes. For that we took the GT boxes and assigned an impact to each predicted box that had an overlap of 0.35 IOU with an impact GT box. </p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F621560%2F5bb26ea6292c3709e100b422f60c9a5a%2FScreenshot%202021-01-05%20at%2019.51.19.png?generation=1609876316497380&alt=media" alt=""></p>
<h3>Stage 2: Impact detection from helmets</h3>
<p>Input data for our 3D models was a stack of 9 helmet detections from Stage 1: the central crop +- 4 frames on either side. The detection was padded so that we cropped 2x width and height of the original. Some of our models included the original box size as context.</p>
<p>We used the different impact types for the centre frame as our output variable (no impact, helmet, shoulder, body, ground impact) and optimized a softmax loss with class weights split 0.8:0.2 (non-impact : impact). We had approximately 1.1M detections from Stage 1 across all training videos, so we used the following sampling scheme during training:</p>
<p>At each epoch we selected all of the positive impact samples and a random sample of negative impact samples according to a specified ratio (we used 0.99:0.01 non-impact:impact). The negative impacts were sampled without replacement so that we saw as many diverse images as possible over the course of training. </p>
<p>Augmentations included: HorizontalFlip, CoarseDropout, GridMask, ShiftScaleRotate, RandomBrightnessContrast, Blur.</p>
<p>We trained 3D models with efficientnet-b3 and b5 backbones (2d conv layers converted to 3d as outlined previously), and various heads. Each model was trained with a cosine annealing scheduler and Adam optimizer for 30 epochs. Pytorch’s distributed data parallel (DDP) and saving a cache of 9x3 channel boxes to disk allowed us to speed up the training process significantly.</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F621560%2Fca5c1647b86bd73b3832db2927963c18%2FScreenshot%202021-01-05%20at%2019.52.25.png?generation=1609876379774000&alt=media" alt=""></p>
<h2>Post-processing</h2>
<p>As the metric was a bit special, and we did not find a good way to reflect it directly within a loss function, we had to rely on certain post-processing consisting of several steps outlined below:</p>
<ul>
<li><p>Filtering stage 1 boxes: For inference, we remove all boxes predicted by our stage 1 model that exhibit a confidence score below ~0.4. This not only speeds up our inference, but also quite significantly improves our stage 2 predictions. Note that removing those boxes also from training stage 2 does not have much impact.</p></li>
<li><p>Filtering early frames: We additionally filter out any frame earlier than 25 as there are usually no impacts detected, this has very minimal influence as our models only very, very rarely would predict impacts in those frames but further speeds up inference.</p></li>
<li><p>Video NMS: This was one of our most important aspects of PP, specifically with weaker models a bit earlier in the competition. The idea was to apply NMS with IOU threshold of 0.5 to all frames of a single video combined. This means that NMS filters out duplicate boxes in subsequent frames and only keeps the ones with highest stage 2 scores. This benefits the metric quite well, as it removes quite a lot of FPs. It got a little bit less important in our latest models that on their own were stronger, but is still an integral part of our pipeline.</p></li>
<li><p>TOPK filter: For each video, we only consider the top 19 predicted boxes based on their stage 2 score. This matches the average number of impacts in training videos and appeared to be a very solid solution to balance TPs, FPs, and FNs. </p></li>
<li><p>Final threshold: Additionally after topk filtering we remove any leftover prediction below a threshold of 0.15.</p></li>
</ul>
<p>We evaluated the parameter of these PP steps on CV, and they turned out to be very robust on private LB and also public LB (even though it was quite tiny).</p>
<h2>Blending</h2>
<p>Our original idea was to blend stage 2 models on different stage 1 models leading to different bounding boxes that makes blending not trivial. To that end, we experimented with WBF to blend the different boxes and assign scores to them. However, this not only extended our inference runtime due to multiple stage 1 models, but also did not lead to satisfying results. Ultimately, we settled on a simpler approach that only uses one single stage 1 model (fitted on full data) and then simply averages the scores of all stage 2 models on the same boxes. </p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F621560%2F67e11084163cd0980e6e504f52d33a55%2FScreenshot%202021-01-05%20at%2019.53.38.png?generation=1609876446208333&alt=media" alt=""></p>
<h1>What did not work</h1>
<ul>
<li>Determining teams’ helmets using KMeans clustering of RGB colors and adding as features.</li>
<li>Applying Video NMS to each team individually (based on the team clusters above).</li>
<li>Adding bounding boxes for all helmets as additional channels before feeding into stage 2 model.</li>
<li>Adding additional context such as: frame number, view, x/y coordinates of bbox center.</li>
<li>Adding more or less than +/-4 frames padding, or applying gaussian smoothed weights to the target.</li>
<li>Training on padded weights.</li>
<li>Dual-View siamese stage 2.</li>
<li>Syncing tracking data with the video - and then adding frame level features like player speed, direction, and relative distances, etc.</li>
<li>Different stage 1 models. None outperformed yolov5.</li>
<li>Imputing or removing stage 1 bounding boxes based on boxes in previous/post frames.</li>
<li>Attempting to track and label individual players throughout the entirety of the video.</li>
<li>Using SORT for improving stage1 boxes</li>
<li>CenterTrack as a single stage model</li>
<li>Learning coordinate transformation between views</li>
</ul>
<p>Thanks for reading. Questions welcome.</p> |
HuBMAP - Hacking the Kidney | 3rd place solution, the simplest way is the best way (full training/inference 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: HuBMAP - Hacking the Kidney
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Congrats to everyone who participated in this competition! It's been a roller coaster of emotions for me. Thanks to the organizers for hosting an interesting competition with meaningful data. I also would like to specially thank <a href="https://www.kaggle.com/iafoss" target="_blank">@iafoss</a> without his starter notebooks, I would never have been able to do anything here, since I've never worked on segmentation before. BTW, congrats on getting one step closer to gm! It seems like we have both been doing ok in this shakeup business</p>
<p>Near the end of the competition, I was getting really tilted by the labeling issues, thinking nothing could be done. But i didn't want to give up either, so I took the path of just doing the simplest things which I think would generalize as well as possible. Here I will discuss the most important details and also release all code used to produce the final result. </p>
<p>Full training code: <a href="https://github.com/Shujun-He/Hubmap-3rd-place-solution/" target="_blank">https://github.com/Shujun-He/Hubmap-3rd-place-solution/</a><br>
Inference code (forked from <a href="https://www.kaggle.com/iafoss" target="_blank">@iafoss</a>) <a href="https://www.kaggle.com/shujun717/hubmap-3rd-place-inference?scriptVersionId=62198789" target="_blank">https://www.kaggle.com/shujun717/hubmap-3rd-place-inference?scriptVersionId=62198789</a></p>
<h1>Preprocessing</h1>
<p>We used reduce=2, and sz=1024 in our final ensemble. The notebook we used was originally released by iafoss: <a href="https://www.kaggle.com/iafoss/256x256-images" target="_blank">https://www.kaggle.com/iafoss/256x256-images</a></p>
<h1>Augmentation</h1>
<p>We used cutout in all our training:</p>
<pre><code>def cutout(tensor,alpha=0.5):
x=int(alpha*tensor.shape[2])
y=int(alpha*tensor.shape[3])
center=np.random.randint(0,tensor.shape[2],size=(2))
#perm = torch.randperm(img.shape[0])
cut_tensor=tensor.clone()
cut_tensor[:,:,center[0]-x//2:center[0]+x//2,center[1]-y//2:center[1]+y//2]=0
return cut_tensor
</code></pre>
<p>In addition, we used the following albumentation augmentations:</p>
<pre><code>def get_aug(p=1.0):
return Compose([
HorizontalFlip(),
VerticalFlip(),
RandomRotate90(),
ShiftScaleRotate(shift_limit=0.0625, scale_limit=0.2, rotate_limit=15, p=0.9,
border_mode=cv2.BORDER_REFLECT),
OneOf([
ElasticTransform(p=.3),
GaussianBlur(p=.3),
GaussNoise(p=.3),
OpticalDistortion(p=0.3),
GridDistortion(p=.1),
IAAPiecewiseAffine(p=0.3),
], p=0.3),
OneOf([
HueSaturationValue(15,25,0),
CLAHE(clip_limit=2),
RandomBrightnessContrast(brightness_limit=0.3, contrast_limit=0.3),
], p=0.3),
], p=p)
</code></pre>
<h1>Models</h1>
<p>Starting from iafoss's starter notebooks and changing them to pure pytorch with heavier augmentation, I ensembled 2 sets of 5-fold models: one with resnext50 and one with resnext101. Effnets have never worked for me, and here that trend continues. Not much more could be said here tbh.</p>
<h1>Inference</h1>
<p>We used something we called expansion tiles but only during inference, which my teammate jj originally came up with in the PANDA competition. You can see how this is done in our inference notebook and also in the graphic below. The basic idea is to eliminate edge effects. To achieve this, for each tile we run the model on, we expand the tile by a certain number of pixels in all 4 directions, but only use the center region's predictions which do not have edges. Effectively there are no edge effects. For the threshold, I decided to simply use 0.5 to minimize any sort of bias the training data might have.</p>
<p><img src="https://raw.githubusercontent.com/Shujun-He/Hubmap-3rd-place-solution/main/expansion_tiles.PNG" alt=""></p>
<p>I wrote this very quickly since I'm eager to share my results/code, so lmk if you have any questions.</p> |
HuBMAP - Hacking the Kidney | 470th Position 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: HuBMAP - Hacking the Kidney
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Congratulations to all those who have landed themselves medals and prize money. Unfortunately, I could not get any. However, I have added the link to my code and submission notebook. </p>
<p>Feel free to have a look at the code and I would love to hear constructive criticism in the form of feedback.</p>
<p>Code: <a href="https://github.com/nauyan/HuBMAP-HackingtheKidney" target="_blank">https://github.com/nauyan/HuBMAP-HackingtheKidney</a></p> |
NFL 1st and Future - Impact Detection | 18th Solution : YoloV5 and filtering using tracking data | 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: NFL 1st and Future - Impact Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>My teammates (@mathurinache & <a href="https://www.kaggle.com/matthieuplante" target="_blank">@matthieuplante</a>) and I would like to thanks Kaggle and the hosts for the organisation of this competition. <br>
We would like also to thanks <a href="https://www.kaggle.com/its7171" target="_blank">@its7171</a> for the public baseline notebook he provided in the early stage of the competition.</p>
<p>We will describe our solution in an iterative way to see how, from this public baseline, we reached a private LB of 0.42+.</p>
<p><strong>Public baseline improvement</strong><br>
We take the idea shared by <a href="https://www.kaggle.com/its7171" target="_blank">@its7171</a> to extend impacts on a [-4, 4] range. But, instead of only training on the frames with impact(s), we added in our train set the frames corresponding to -5, +5 offsets. From our point of view, it helps the model to understand the boundaries between impact or no impact. Using EfficientDetB5 trained on imgsize of 512x512 with a simple 80/20 split, we get as CV/Public/private results : 0.18/0.22/0.18</p>
<p>Based on the previous model, adding post processing that will be describe in last section, we reached CV/Public/private results of 0.22/0.25/0.22</p>
<p>Moving, then, to yolov5 as based model and using original resolution for our 2 classes detection problem, we reached CV/Public/private results of 0.25/0.28/0.24.</p>
<p>Finally, doing some ensembling (that revealed to be bad for private LB) with 0.226 public notebook, we reached a public LB of 0.35+ but a private LB of 0.26+</p>
<p><strong>Using tracking data as a frame selector</strong><br>
Tracking data seems a nice playground for us to detect frames with impact as information such as speed and acceleration at player level was provided.</p>
<p>To work with this file, we decided to change a bit it structure from :<br>
[time, player info]</p>
<p>to :<br>
[time, player info, closest opponent info, global aggregates, impact]</p>
<p>Global aggregates are mean/std of player speed/acceleration/… at a given timestamp.<br>
We also take the care to remove any translation or rotation dependent features such as : x, y, direction, orientation. For direction and orientation, we add the scalar product between player and opponent values.<br>
Impact is obtained by reconciliation with the train csv file.</p>
<p>Then, we build a model based on a simple Transformer encoder architecture (6 attentions, 8 heads) with a linear head classifier that will process our new tracking data over 9 consecutive timesteps (9 is a parameter).</p>
<p>We performed a 5 folds training on this data, managing class imbalance by downsampling. Each fold provided more or less a F1 score of 0.4 for more or less 0.4 precision and recall. At first, this seemed poor, but because we are at player level, going back to frame level, we get the following results : recall of 0.7 for a precision of 0.1. Accepting to set an upper bound of 0.7 to our recall, we were now in a situation where 1 frame out of 10 contains at least an impact (original situation on train data was 3 out of 100).</p>
<p>Retraining our yolo based model using an 5 folds strategy (not using the same seed as the frame selector) and using this frame selector for filtering did not improved our result at first ! <br>
Indeed, as we changed our « prediction space », we needed to change also our validation space by limiting it to the scope of the frame selector.</p>
<p>This strategy gives us a CV/public/private scores of 0.3711/0.3749/0.3767</p>
<p>At last, we enhanced our train set adding the FP from our frame selector (guessing there are some hard samples in it) and we reached the following CV/Public/private of : 0.4117/0.3636/0.4220<br>
Little tweak attempts on postprocessing give us our best public LB of 0.4666 for a private score of 0.4244.</p>
<p><strong>Post processing</strong><br>
Several steps composed our post processing :<br>
1 - basic model confidence filter<br>
2 - 5-85% filter : exclude all frames below 5% or above 85% of the video<br>
3 - endzone - sideline constraint : keep only frames where there are predictions on sideline and endzone with at most 3 frames margin<br>
4 - NMS (using torch implementation) on a 9 frames sliding windows with a 0.2 iou threshold<br>
5 - box limit : take only the 4 most confident predictions per frame</p> |
HuBMAP - Hacking the Kidney | 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: HuBMAP - Hacking the Kidney
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>First of all, congratulations to the winners and thank you Kaggle and the host team for this tough competition! I entered this competition early and spent a lot of time until the data update. I could not keep my motivation for hand-labeling, so I left a month ago. Luckily I got the 1st place, so I would like to share my approach.</p>
<h1>Summary of my approach</h1>
<ul>
<li>single model Unet se_resnext101_32x4d (4folds)</li>
<li>some techniques from previous segmentation competitions (mainly from the cloud comp.) </li>
<li>balanced tile sampling for training (EDIT : masked area is balanced)</li>
<li>pseudo-label for the public test data and external data</li>
<li>a trick for avoiding the edge effect</li>
<li>My pipeline was developed with the old dataset (i.e., before the data update).</li>
</ul>
<h1>1. Data preparation</h1>
<p>make 1024x104 tiles + shifted 1024x1024 tiles (I shifted the tiles by (512,512))</p>
<h1>2. Validation</h1>
<p>I selected the validation data so that the same patient number is in the same group</p>
<pre><code>val_patient_numbers_list = [
[63921], # fold0
[68250], # fold1
[65631], # fold2
[67177], # fold3
]
</code></pre>
<h1>3. Balanced tile sampling for training</h1>
<p>First I binned the tile data with respect to the masked area (number of bins = 4 for masked tiles). Then I apply the following procedure for balanced sampling.</p>
<pre><code>n_sample = trn_df['is_masked'].value_counts().min()
trn_df_0 = trn_df[trn_df['is_masked']==False].sample(n_sample, replace=True)
trn_df_1 = trn_df[trn_df['is_masked']==True].sample(n_sample, replace=True)
n_bin = int(trn_df_1['binned'].value_counts().mean())
trn_df_list = []
for bin_size in trn_df_1['binned'].unique():
trn_df_list.append(trn_df_1[trn_df_1['binned']==bin_size].sample(n_bin, replace=True))
trn_df_1 = pd.concat(trn_df_list, axis=0)
trn_df_balanced = pd.concat([trn_df_1, trn_df_0], axis=0).reset_index(drop=True)
</code></pre>
<h1>4. Model</h1>
<p>U-Net SeResNext101 + CBAM + hypercolumns + deepsupervision<br>
In my case, larger model gave better CV and LB.<br>
I resized 1024x1024 to 320x320 for input tiles.<br>
here is the code snippet:</p>
<pre><code>class CenterBlock(nn.Module):
def __init__(self, in_channel, out_channel):
super().__init__()
self.conv = conv3x3(in_channel, out_channel).apply(init_weight)
def forward(self, inputs):
x = self.conv(inputs)
return x
class DecodeBlock(nn.Module):
def __init__(self, in_channel, out_channel, upsample):
super().__init__()
self.bn1 = nn.BatchNorm2d(in_channel).apply(init_weight)
self.upsample = nn.Sequential()
if upsample:
self.upsample.add_module('upsample',nn.Upsample(scale_factor=2, mode='nearest'))
self.conv3x3_1 = conv3x3(in_channel, in_channel).apply(init_weight)
self.bn2 = nn.BatchNorm2d(in_channel).apply(init_weight)
self.conv3x3_2 = conv3x3(in_channel, out_channel).apply(init_weight)
self.cbam = CBAM(out_channel, reduction=16)
self.conv1x1 = conv1x1(in_channel, out_channel).apply(init_weight)
def forward(self, inputs):
x = F.relu(self.bn1(inputs))
x = self.upsample(x)
x = self.conv3x3_1(x)
x = self.conv3x3_2(F.relu(self.bn2(x)))
x = self.cbam(x)
x += self.conv1x1(self.upsample(inputs)) #shortcut
return x
class UNET_SERESNEXT101(nn.Module):
def __init__(self, resolution, deepsupervision, clfhead, load_weights=True):
super().__init__()
h,w = resolution
self.deepsupervision = deepsupervision
self.clfhead = clfhead
#encoder
model_name = 'se_resnext101_32x4d'
seresnext101 = pretrainedmodels.__dict__[model_name](pretrained=None)
if load_weights:
seresnext101.load_state_dict(torch.load(f'{model_name}.pth'))
self.encoder0 = nn.Sequential(
seresnext101.layer0.conv1, #(*,3,h,w)->(*,64,h/2,w/2)
seresnext101.layer0.bn1,
seresnext101.layer0.relu1,
)
self.encoder1 = nn.Sequential(
seresnext101.layer0.pool, #->(*,64,h/4,w/4)
seresnext101.layer1 #->(*,256,h/4,w/4)
)
self.encoder2 = seresnext101.layer2 #->(*,512,h/8,w/8)
self.encoder3 = seresnext101.layer3 #->(*,1024,h/16,w/16)
self.encoder4 = seresnext101.layer4 #->(*,2048,h/32,w/32)
#center
self.center = CenterBlock(2048,512) #->(*,512,h/32,w/32)
#decoder
self.decoder4 = DecodeBlock(512+2048,64,upsample=True) #->(*,64,h/16,w/16)
self.decoder3 = DecodeBlock(64+1024,64, upsample=True) #->(*,64,h/8,w/8)
self.decoder2 = DecodeBlock(64+512,64, upsample=True) #->(*,64,h/4,w/4)
self.decoder1 = DecodeBlock(64+256,64, upsample=True) #->(*,64,h/2,w/2)
self.decoder0 = DecodeBlock(64,64, upsample=True) #->(*,64,h,w)
#upsample
self.upsample4 = nn.Upsample(scale_factor=16, mode='bilinear', align_corners=True)
self.upsample3 = nn.Upsample(scale_factor=8, mode='bilinear', align_corners=True)
self.upsample2 = nn.Upsample(scale_factor=4, mode='bilinear', align_corners=True)
self.upsample1 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
#deep supervision
self.deep4 = conv1x1(64,1).apply(init_weight)
self.deep3 = conv1x1(64,1).apply(init_weight)
self.deep2 = conv1x1(64,1).apply(init_weight)
self.deep1 = conv1x1(64,1).apply(init_weight)
#final conv
self.final_conv = nn.Sequential(
conv3x3(320,64).apply(init_weight),
nn.ELU(True),
conv1x1(64,1).apply(init_weight)
)
#clf head
self.avgpool = nn.AdaptiveAvgPool2d(1)
self.clf = nn.Sequential(
nn.BatchNorm1d(2048).apply(init_weight),
nn.Linear(2048,512).apply(init_weight),
nn.ELU(True),
nn.BatchNorm1d(512).apply(init_weight),
nn.Linear(512,1).apply(init_weight)
)
def forward(self, inputs):
#encoder
x0 = self.encoder0(inputs) #->(*,64,h/2,w/2)
x1 = self.encoder1(x0) #->(*,256,h/4,w/4)
x2 = self.encoder2(x1) #->(*,512,h/8,w/8)
x3 = self.encoder3(x2) #->(*,1024,h/16,w/16)
x4 = self.encoder4(x3) #->(*,2048,h/32,w/32)
#center
y5 = self.center(x4) #->(*,320,h/32,w/32)
#decoder
y4 = self.decoder4(torch.cat([x4,y5], dim=1)) #->(*,64,h/16,w/16)
y3 = self.decoder3(torch.cat([x3,y4], dim=1)) #->(*,64,h/8,w/8)
y2 = self.decoder2(torch.cat([x2,y3], dim=1)) #->(*,64,h/4,w/4)
y1 = self.decoder1(torch.cat([x1,y2], dim=1)) #->(*,64,h/2,w/2)
y0 = self.decoder0(y1) #->(*,64,h,w)
#hypercolumns
y4 = self.upsample4(y4) #->(*,64,h,w)
y3 = self.upsample3(y3) #->(*,64,h,w)
y2 = self.upsample2(y2) #->(*,64,h,w)
y1 = self.upsample1(y1) #->(*,64,h,w)
hypercol = torch.cat([y0,y1,y2,y3,y4], dim=1)
#final conv
logits = self.final_conv(hypercol) #->(*,1,h,w)
#clf head
logits_clf = self.clf(self.avgpool(x4).squeeze(-1).squeeze(-1)) #->(*,1)
if self.clfhead:
if self.deepsupervision:
s4 = self.deep4(y4)
s3 = self.deep3(y3)
s2 = self.deep2(y2)
s1 = self.deep1(y1)
logits_deeps = [s4,s3,s2,s1]
return logits, logits_deeps, logits_clf
else:
return logits, logits_clf
else:
if self.deepsupervision:
s4 = self.deep4(y4)
s3 = self.deep3(y3)
s2 = self.deep2(y2)
s1 = self.deep1(y1)
logits_deeps = [s4,s3,s2,s1]
return logits, logits_deeps
else:
return logits
</code></pre>
<h1>5. Loss</h1>
<p>I used bce loss + lovasz-hinge loss, on top oh that I used deep supervision with bce loss + lovasz-hinge loss (for only non-empty masks) multiplied by 0.1. For classification head, I used bce loss</p>
<h1>6. External data and Pseudo-label</h1>
<p>I generated pseudo-labels for (EDIT) train data, public test data, the hubmap-portal (<a href="https://portal.hubmapconsortium.org/search?entity_type[0]=Dataset" target="_blank">https://portal.hubmapconsortium.org/search?entity_type[0]=Dataset</a>)<br>
and dataset_a_dib (<a href="https://data.mendeley.com/datasets/k7nvtgn2x6/3)" target="_blank">https://data.mendeley.com/datasets/k7nvtgn2x6/3)</a>. For the data d488c759a, I used Carno Zhao's pseudo-label (thanks <a href="https://www.kaggle.com/carnozhao" target="_blank">@carnozhao</a> !) for one of my final model and my model's pseudo-label for the other one. I checked my private scores and found that these models' performances are not so different. But my 1st place model is the former one with Carno Zhao's pseudo-label. I think it's not the hand-labeling but the indirectly ensemble effect that boosted my score since my model is single and diversity should contribute.</p>
<h1>7. A trick for inference</h1>
<p>I found that avoiding edge effect consistently boosts CV and LB. My trick is to use only the center part of tiles for prediction (I notice that 3rd place solution by <a href="https://www.kaggle.com/shujun717" target="_blank">@shujun717</a> used the same idea). I found that using smaller part as prediction gave better CV and LB, but it is time-consuming. So I end up with using 512x512 center part from original 1024x1024 as prediction. I needed x4 time for inference, but using classification head prediction was helpful to save inference time.</p>
<h1>8. LB scores</h1>
<p>public LB=0.936 / private LB=0.951</p>
<h1>9. Some thoughts</h1>
<p>I used what I learned from the previous competitions and I used the same model architecture for most of my experiments. This saved my time and I focused on the data preparation and how to avoid the edge effect. I think I did something different from the other competitors but I'm not sure these were the keys in the final position since I've not experimented a lot for the new dataset.</p>
<p>EDIT<br>
training code : <a href="https://github.com/tikutikutiku" target="_blank">https://github.com/tikutikutiku</a><br>
inference code : <a href="https://www.kaggle.com/tikutiku/hubmap-tilespadded-inference-v2?scriptVersionId=59475269" target="_blank">https://www.kaggle.com/tikutiku/hubmap-tilespadded-inference-v2?scriptVersionId=59475269</a></p> |
NFL 1st and Future - Impact Detection | 7-th place solution from AlphaGoal Team [2.5D CenterNet, 3D CNN] | 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: NFL 1st and Future - Impact Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h1>Intro</h1>
<p>Hi there. It was an exciting competition, thanks to the new domain of video analysis. Before I jump into technical details, a brief team intro:</p>
<ul>
<li><a href="https://www.linkedin.com/in/anastasiya-karpovich/" target="_blank">Anastasiya Karpovich</a> </li>
<li><a href="https://www.linkedin.com/in/tatigabru/" target="_blank">Tatiana Gabruseva, PhD</a> </li>
<li><a href="https://www.linkedin.com/in/cvtalks/" target="_blank">Eugen Khvedchenya</a></li>
</ul>
<p>For me, it was a great experience to solve this in a team. Since most activities happened during Christmas & NY holidays, we did our best to find the proper balance between life & Kaggling :) The help of my teammates was invaluable, and I'm grateful for being part of this team. <a href="https://www.kaggle.com/user189546" target="_blank">@user189546</a> <a href="https://www.kaggle.com/blondinka" target="_blank">@blondinka</a> great job, it seems we earned some new GMs & Master badges :)</p>
<h1>Approach</h1>
<p>There were a number of ways to approach this challenge, and here's our way to the gold zone:</p>
<p>We used three stages: helmet detection, impact classification, and post-processing.</p>
<p>The data were split into four folds making sure that both views, Endzone and Sideline, of the same video go to the same fold to avoid data-leak. Each fold has 15 plays (30 videos), which I believe is the same as the size of the test.</p>
<h2>TL;DR:</h2>
<ul>
<li>4 models of CenterNet for detection </li>
<li>1 model of 3D CNN for classification</li>
<li>Postprocessing</li>
</ul>
<h2>Helmet detection</h2>
<p>We experimented with CenterNet and EfficientDet detectors. And our final detection pipeline is what I call 2.5D CenterNet. The model's input was a short clip of 8 consecutive frames, which were passed through the encoder individually (like you would do in siamese networks), then intermediate concatenated and fed through UNet-like decoder to produce output heatmap & impacts map for 8 frames. We found this approach requires much less memory than regular 3D-CenterNet. </p>
<p>We experimented with different encoders, and DenseNet-based encoders worked the best in terms of Helmet F1 detection and Impact F1 detection scores. EfficientNets worked slightly worse, and ResNet-s performed the worst. On average, F1 score for helmets was around 0.93-0.94, and impact F1 was about 0.43 per fold.</p>
<p>For augmentations, we used albumentations library: <a href="https://github.com/albumentations-team/albumentations" target="_blank">https://github.com/albumentations-team/albumentations</a> </p>
<p>Combined 4 folds with TTA for CenterNet detector gave f1 0.95 with densenet121 backbone and medium-hard augmentations. 2.5D CenterNet ensemble reached the gold zone by itself, but we decided to push forward.</p>
<h2>Impact Classification:</h2>
<p>We used several approaches for the classification of the impact. Most of them did not work well enough.</p>
<ol>
<li>Second-level model using 1D CNN on top of the predictions from helmet detection model -- gave around f1 = 0.32 with post-processing (1 fold, no TTA)</li>
<li>EfficientDet pre-trained on 1 class for helmet detection and tuned for 2 classes, with medium augmentations and sampling → gave f1 around 0.33 with post-processing (1 fold, no TTA)</li>
<li>Mix of the first two approaches -- f1 = 0.34 on LB (1 fold, no TTA)</li>
<li>Siamese networks in videos </li>
<li>3D CNN classifier on top of the 2D helmets predictions -- this approach gave the best results -- f1 0.57 after post-processing</li>
</ol>
<p>For 3D CNN classification, we trained only one fold of 3D ResNet50, which, stacked together with predictions of CenterNet, boosted our score by +0.05 or so on the LB. </p>
<h2>Post Processing</h2>
<p>For post-processing we needed to suppress duplicates. We tracked the helmets using IoU, and selected the frame with the maximum impact probability score.<br>
We also tried to use the center of the boxes to track the euclidean distance as a criterion for similar results. </p>
<p>In the beginning, we removed impacts from the first 30 frames and the last frames, but as the model became more accurate, it did not make a difference.</p> |
NFL 1st and Future - Impact Detection | 15th place solution: single stage object tracking | 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: NFL 1st and Future - Impact Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>FIrst of all, thanks to Kaggle and host for having such a interesting competition. And also congrats to all the winners. I believe it was one of the toughest competition since there were so many talented kagglers while total number of competitor was relatively small.</p>
<p>Here I'll write up a short summary of my solution and also where I failed.</p>
<h1>TLDR;</h1>
<ul>
<li>No ensemble single stage model</li>
<li>FairMOT as baseline for helmet tracking</li>
<li>Additional impact detection branch and team feature branch</li>
<li>A bunch of postprocess with track id, team and position</li>
</ul>
<h1>Baseline</h1>
<p>At first sight this task seems the best application of object tracking because we need to aggregate timeseries information due to metric design. So I chose <a href="https://arxiv.org/abs/2004.01888" target="_blank">FairMOT</a> as my baseline because it is the SoTA of the MOT benchmark. In short, FairMOT is object tracking framework which is CenterNet with metric learning based id feature branch. Additional to helmet tracking, my model also predict impact probability for each impact types and also team feature to distinguish opponent helmet. So in total, my model's outputs are following:</p>
<ul>
<li>Helmet image coords and bbox wh and confidence (N * 5)</li>
<li>Id feature (N * 128)</li>
<li>Team feature (N * 128)</li>
<li>Impact probability (N * 6)</li>
</ul>
<p>where N is number of helmets.</p>
<p>As a small trick, I added same tracking label for same player in both view, so my model should output same id feature for same player in both view. While tracking I associated helmets in both view. Additionally I devide helmets in 2 groups, or teams, in the view. I simply use kmeans to clustering, but it works very well. After tracking, My model's outputs are following (in addition to above):</p>
<ul>
<li>Tracking id (N,)</li>
<li>Matched tracking id in another view (N,)</li>
<li>team class (0 or 1) (N,)</li>
</ul>
<p>Other small details of training:</p>
<ul>
<li>backbone: HRNet32</li>
<li>image size: (708, 1280)</li>
<li>num epochs: 20 for Endzone, 35 for Sideline</li>
<li>extend impact label to +- 4 frames</li>
</ul>
<h1>Post process</h1>
<p>Even though my model predict impact probability for all impact type, in my best submission I used only prediction for impact between helmets. And my postprocess procedure heavily rely on the hypothesis in which helmet impact happens between the pair of helmets from different team.<br>
My post process is consists of following steps:</p>
<ol>
<li>Calculate maximum iou with opponent helmet</li>
<li>Take maximum of impact probability between the pair of highest iou helmets</li>
<li>Calculate minimum pixel distance with opponent helmet and normalize it by mean box size in frame</li>
<li>filter by helmet detection confidence threshold</li>
<li>filter by distance threshold</li>
<li>filter by impact probability threshold</li>
<li>maxpooling nms in time axis for same id</li>
<li>remove solo helmets which has no pair helmets in near frames</li>
</ol>
<p>As you can see there are a lot of hyper parameters. I optimized these thresholds with optuna for Endzone and Sideline separately. <br>
By doing so my cv was about 0.42 for Endzone and 0.53 for Sideline, and 0.45 in total. CV and LB correlation was not so bad, my final score was actually 0.45 both on public and private.</p>
<h1>Where I failed?</h1>
<p>Obviously I missed to aggregate timeseries information, such as 3d model or 2 stage model which is most of other solutions have. Instead of that, I spent most of time in last month to aggregate relationship between instances in same frame and other view. I believe there shuold be some breakthrough but I couldn't make it works. What I tried were:</p>
<ul>
<li>Making use of other view prediction. (ex. if there is no prediction in other view, filter out more)</li>
<li>Making use of matching id even though it has best matching accuracy among the method I tried.</li>
<li>Homography estimation and optimization between End and Side or image and sensor tracking position.</li>
<li>Training and matching with <a href="https://github.com/magicleap/SuperGluePretrainedNetwork" target="_blank">superglue</a>. I used id feature as descriptor and center points as keypoint. I added superglue on top of FairMOT and trained simultaneously. It works somehow but simple linear sum assignment was better than this.</li>
</ul>
<p>I'd like to release code, but it's so messy now. If I success to clean it up, I'll update.</p> |
HuBMAP - Hacking the Kidney | 46th 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: HuBMAP - Hacking the Kidney
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h2>46th Place Solution</h2>
<p>I would like to thank the organizers and management for organizing the competition.<br>
It was a fun way to deepen my knowledge.<br>
Also, if you are going to make this more of a competition, I would like to see a fuller description of the data generation process.<br>
We would also like to thank those who provided us with easy-to-understand kernels.</p>
<hr>
<h2>Pre processing:</h2>
<ul>
<li>resize tileimage size to (256, 256)</li>
<li>pseudo label</li>
<li>using d48_handlabel(Check the discussion.)</li>
</ul>
<h2>Augmentations:</h2>
<p>I used albumentations.</p>
<ul>
<li>HorizontalFlip</li>
<li>VerticalFlip</li>
<li>ShiftScaleRotate, GridDistortion</li>
<li>Blur, MedianBlur, GaussianBlur</li>
<li>CLAHE, RandomBrightnessContrast, HueSaturationValue, IAASharpen</li>
</ul>
<h2>Post processing:</h2>
<ul>
<li>TTA(HorizontalFlip、VerticalFlip)</li>
</ul>
<h2>Model-1:</h2>
<ul>
<li>efficientnetb0 Unet</li>
<li>image size : 256x256</li>
<li>bce_dice(bce_weight:0.75)</li>
<li>5FOLD</li>
</ul>
<h2>Model-2:</h2>
<ul>
<li>efficientnetb0 link</li>
<li>image size : 256x256</li>
<li>bce_dice(bce_weight:0.75)</li>
<li>5FOLD</li>
</ul>
<h2>Model-3:</h2>
<ul>
<li>seresnext50 Unet</li>
<li>image size : 256x256</li>
<li>bce_dice(bce_weight:0.75)</li>
<li>5FOLD</li>
</ul>
<h2>Model-4:</h2>
<ul>
<li>efficientnetb0 FPN</li>
<li>image size : 256x256</li>
<li>bce_dice(bce_weight:0.75)</li>
<li>5FOLD</li>
</ul>
<h2>sub1:</h2>
<ul>
<li>1/4(Model-1+Model-2+Model-3+Model-4)</li>
</ul>
<p>I look forward to seeing you at another competition!</p> |
HuBMAP - Hacking the Kidney | 17th 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: HuBMAP - Hacking the Kidney
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Congratulations to the winners and all participants who finished this competition.<br>
A number of problems arose during the competition, and the competition was held for six months. I have to admit that it was quite a challenge for me to keep participating until the end.<br>
My ranking was not so great, but I would like to share it with you.</p>
<hr>
<p>The resolution is not very good, so you may not be able to see the fine details, but the model I created is shown in the following figure.<br>
<img src="https://f.easyuploader.app/20210511095415_66516e4b.jpg" alt=""></p>
<p>I would like to explain the main points.</p>
<p><strong>1. Cutting out patches</strong><br>
Early in the competition, I recognized through my experiments that the difference in image size (original size to be cut out and image size after downscaling) might affect the score. Therefore, I chose several image sizes that were large enough to ensure a sufficient batch size for training, and eventually ensembled 2 models for 352 x 4 and 512 x 2 image sizes. <br>
Also, I did not include the black and white regions, which are not very informative regions, in the training patches, referring to <a href="https://www.kaggle.com/iafoss" target="_blank">@iafoss</a> kernel. <br>
If we simply shifted the image by augmentation for the patch, we would have to do some kind of interpolation such as reflection for the missing regions. Since my experimental results showed that this was not a good idea, I shifted the image by a quarter of the patch size when cutting out the patches from the WSIs.</p>
<p><strong>2. Preprocessing / Augmentation</strong><br>
The images were simply normalized by 255, and then I trained the models on 5 folds, where each fold consists of 3 WSIs.<br>
I don't know about the private WSIs, but at least some of the public images were darker than the training WSIs, or had some kind of dirt on them, so I applied a very strong augmentation as shown below.</p>
<ul>
<li>Horizontal/Vertical Flip (p=0.5)</li>
<li>RandomRotate90 (p=0.5)</li>
<li>Rotate (-40/+40, reflect101, p=0.5)</li>
<li>ShiftScaleRotate (scale: -0.2/0.1, p=0.5)</li>
<li>OneOf (p=0.5)<br>
RandomBrightnessContrast (B: 0.5, C: 0.1)<br>
HueSaturationValue (H: +-20, S: +-100, V: +-80)</li>
<li>One of (p=0.5)<br>
Cutout (holes: 100, size: 1/64, white RGB)<br>
GaussianNoise</li>
<li>One of (p=0.5)<br>
ElasticTransform<br>
GridDistortion (steps: 5, limit: 0.3)<br>
OpticalDistortion (distort: 0.5, shift: 0.0)</li>
</ul>
<p>As a result, I think that the evaluation of the model with 5 folds by WSI and this strong augmentation contributed to the stable correlation between local CV and LB.</p>
<p><strong>3. Training</strong><br>
My training was very simple. <br>
I used BCE + Adam to train ImageNet Pretrained EfficientNetB3 backbone U-Net. As mentioned in some discussions, the complexity of the model did not seem to have any effect, probably because it is a rather simple task. I also tried some losses such as Focal loss and Combo loss, but there was no noticeable gain, probably because I excluded the black and white parts beforehand. In addition, I don't use losses based on discrete metrics such as Dice loss for ensembles, so I thought that BCE would be sufficient for this project when there was no gain from focal loss. <br>
Also, since I used the psuedo label in the latter half like many of the participants, I trained the image size combinations (group A and group B in the model pipeline figure) alternately to avoid overtraining. I used the psuedo label of the model trained in group A for training group B to avoid the model from becoming overly dependent on the public data. However, since the psuedo label was almost meaningless in private score, I think it was almost a meaningless attempt.<br>
(I used the d48 hand label at the end of the competition, but I did not do any hand labeling by myself. I think that the d48 hand label actually contributed nothing to the improvement of the private score.)</p>
<p>The following graph shows the correlation between the local CV and the public LB, and since the public LB is in increments of 0.001, I think the correlation is actually greater than what can be seen in the graph. There are three clusters, starting from the bottom one: no psuedo at all, psuedo without d48 hand label, and psuedo based on d48 hand label.<br>
<img src="https://f.easyuploader.app/20210511104838_62546152.jpg" alt=""></p>
<p><strong>4-5. Prediction + Tiling predicted patches</strong><br>
I think the prediction was the same method as many of you.</p>
<ul>
<li>TTA: Raw, HorizontalFlip, VerticalFlip</li>
<li>Overlapping by 1/16 image size for tiling</li>
<li>Naive averaging for ensemble (folds and models)</li>
<li>Threshold optimization with train images (th: 0.40 for public LB, 0.44-0.48 for local CV)</li>
</ul>
<p>In my experiments, I found that there was no significant difference in the scores if the overlap was 1/16 or more, so I decided to use that value to save inference time.<br>
The only regret I have is that I set the threshold in the direction of better public score. As I will show later, if I had set the threshold to the theoretical value determined by the train data, I would have been sure to get the gold medal.</p>
<p><strong>6. Submission</strong></p>
<ul>
<li>Approximately 8 hours running (5 folds, 3 TTA, 2 models)</li>
<li>Good correlation between local CV and public LB<br>
(Alghough there are deviations…, maybe due to the notorious <code>d48...</code> image)</li>
<li>Local CV: 0.9429<br>
Public LB: 0.927<br>
Private LB: 0.947</li>
</ul>
<p><strong>Finally…</strong><br>
I think this competition was about how much you can believe in your Local CV. If there is a domain shift between the training data and the test data, the <code>trust CV</code> is not always correct, so I don't think the participants who did the training with more public are wrong. It would be nice if the host would mention the presence or absence of domain shift at least a little in advance, but there is a degree to which this is the case, and as long as the number of data is finite, it may be a permanent problem in data science.</p>
<p>By the way, my sbumission in descending order of private score was as follows. It would have been better if I had used the correct threshold value, but it was a good lesson for me that I didn't trust all my locals.<br>
<img src="https://f.easyuploader.app/20210511105807_7a4f4f78.jpg" alt=""></p>
<p>See you at the next competition!</p> |
Rainforest Connection Species Audio Detection | 10th-place solution - Agnostic loss for semi-supervised 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: Rainforest Connection Species Audio Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thank you to the organisers, Kaggle, and to everyone who shared ideas and code for this competition. I learned a lot, as I'm sure many of you have, and I thought I would break down my approach since I know many competitors couldn't find a way to use the False Positive labels. I'm thrilled to have secured my first gold (and solo gold) in a competition, so it's the least I could do!</p>
<h3>Summary</h3>
<p>On a high-level, my approach was as follows:</p>
<ul>
<li>train models using existing labels</li>
<li>generate pseudo-labels on train/test</li>
<li>isolate the frames which had a very high/low prob across an ensemble of models</li>
<li>conservatively threshold these and use as new TP/FP values for the relevant class</li>
<li>repeat</li>
</ul>
<p>This gradually increased the amount of data I had to work with, until I had at least 2 frames from each recording with an identified TP and/or FP. The growing data diversity allowed successive models to generalise better.</p>
<h3>What Worked</h3>
<p><strong>Fixed Windows</strong></p>
<p>I used a window of 5 seconds centred on the TP/FP. For predicting on test, I used overlapping windows with a step of 2.5 seconds. This ensured that train/test had identical preprocessing for their inputs. The maximum value was taken for each class across all of these windows. For some submissions, I used the average of the top 3 predictions but this didn't seem to notably change the LB score.</p>
<p><strong>Agnostic Loss</strong></p>
<p>Perhaps a better term already exists for this, but this was what I called my method for using both the TPs and FPs in a semi-supervised fashion. The problem we face with unlabelled data is that any spectrogram can contain multiple classes, so setting the target as 0 for everything apart from the <em>given</em> label will penalise true positives for other classes. We can only know for sure that one class is present or absent, and the loss needs to reflect this. So I excluded all non-definite targets from the loss calculation. In the target tensor, a TP is 1 while an FP is 0. Unlabelled classes are given as 0.5. These values are then excluded from the loss calculation. So if we had 5 classes (we have 24, but I'm saving room here) and this time window contained a TP for class 0 and an FP for class 3:</p>
<pre><code>y = torch.Tensor([1., 0.5, 0.5, 0., 0.5])
</code></pre>
<p>And in the loss calculation:</p>
<pre><code>preds = model(inputs)
preds[targets==0.5] = 0
loss = BCEWithLogitsLoss(preds, targets)
loss.backward()
</code></pre>
<p>Thus the model is 'agnostic' to the majority of the potential labels. This allows the model to build a guided feature representation of the different classes without being inadvertently given false negatives. This approach gave me substantially better LB scores.</p>
<p>The figure of 0.5 is arbitrary and could've been any value apart from 0 or 1: the salient point is that the loss resulting from unlabelled classes is always constant. Note that this kind of inplace operation is incompatible with <code>nn.Sigmoid</code> or its functional equivalent when performing backprop so you need to use the raw logits via <code>torch.nn.BCEWithLogitsLoss()</code>.</p>
<p><strong>ResNeSt</strong></p>
<p>I found EfficientNet to be surprisingly poor in this competition, and all of my best scores came from using variants of ResNeSt (<a href="https://github.com/zhanghang1989/ResNeSt" target="_blank">https://github.com/zhanghang1989/ResNeSt</a>) paper available <a href="https://arxiv.org/abs/2004.08955" target="_blank">here</a>.</p>
<p>For 3-channel input I used the <code>librosa</code> mel-spectrogram with power 1, power 2 and the <code>delta</code> function to capture temporal information. With some models I experimented with a single power-1 spectrogram, delta and delta-delta features instead. While quicker to preprocess, I noticed no impact on scores.</p>
<p>I also incorporated it into the SED architecture as the encoder. This showed very promising metrics during training, and while sadly I didn't have time to run a fully-convergent example its inclusion still helped my score. In future competitions this could be a very useful model. ResNeSt itself only takes a 3-channel input and has no inbuilt function to extract features, so I had to rejig it to work properly: I'll be uploading a script with that model shortly in case anyone is interested.</p>
<p><strong>Augmentations</strong></p>
<p>From Hidehisa Arai's excellent kernel <a href="https://www.kaggle.com/hidehisaarai1213/rfcx-audio-data-augmentation-japanese-english" target="_blank">here</a>, I selected <code>GaussianNoiseSNR()</code>, <code>PinkNoiseSNR()</code>, <code>TimeShift()</code> and <code>VolumeControl()</code>. I was wary of augmentation methods that blank out time windows or frequency bands like <a href="https://arxiv.org/abs/1904.08779" target="_blank">SpecAugment</a>. Some of the sounds occur in a very narrow frequency range (e.g. species 21) or in a very narrow time window (e.g. species 9) and I didn't want to make 'empty', positive samples that would coerce the model into learning spurious features. I also added some trivial augmentations of my own:</p>
<ul>
<li>swapping the first and last half of the audio vector</li>
<li>adding a random constant before spectrogram normalisation (occluding the relevant features)</li>
<li>'jiggling' the time window around the centre of <code>t_mid</code>, at a maximum of 1 second offset in either direction</li>
</ul>
<p><strong>Eliminating species 19</strong></p>
<p>A minor point, but this class was so rare that setting all of its predictions to zero usually improved the LB score by 0.001. There were many unrelated sounds that would presumably cause the model to produce false positives. My best submission didn't do this however; it was a simple blend of models including ResNeSt-50, ResNeSt-101, EfficientNet-b1 and the SED architecture described above. I used weighted averaging roughly in proportion to the individual models' performance.</p>
<h3>What didn't work</h3>
<ul>
<li>Using separate models for different frequency ranges (these models never gained an adequate feature representation, and produced many false positives).</li>
<li>EfficientNet alone gave poor results, but helped as part of an ensemble.</li>
<li>Larger models (ResNeSt101, EfficientNet b3) didn't improve scores.</li>
<li>TP-only training.</li>
<li>Models that worked on all windows for a single clip - these were slow and produced inferior results.</li>
</ul>
<p>Otherwise I was quite lucky - I thought about my methodology for a while and most of what I tried worked well on the first attempt. If I'd had more time, I would have liked to try:</p>
<ul>
<li>automatically labelling some species as an FP of a similar class (e.g species 9 & 17)</li>
<li>probing the LB for class distribution (I suspect you could get +0.9 by only predicting the most common half of the classes and ignoring everything else) - I realised the importance of this too close to the deadline</li>
<li>experimenting with different encoders for the SED architecture.</li>
<li>using a smaller window size (<=3 seconds) for greater fidelity. </li>
</ul>
<p>The overall class prediction histograms for my final submission were as follows:</p>
<p><img src="https://i.imgur.com/GmJ9BkI.png" alt=""></p>
<p>Some classes gave me particular trouble. I used my own, simple scoring metric during training that recorded the proportion of positive cases that were predicted above a certain threshold. I never satisfactorily made a model that could detect the rarer classes like 6, 19 or 20 in a reliable fashion.</p>
<p>Overall I had an interesting time exploring how to work with the application of CNNs to spectrograms, and with large amounts of unlabelled data. In the next audio competition, perhaps I'll aim a little higher! I'm looking forward to seeing how those who scored > 0.97 managed to achieve their results.</p>
<p>If you have any questions I'll do my best to answer them!</p> |
Rainforest Connection Species Audio Detection | 27th place simple solution (0.932 public, 0.940 private) - dl_pipeline | 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: Rainforest Connection Species Audio Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p><strong>In summary:</strong></p>
<ul>
<li>Best single model (0.925 public lb): densenet121 features + fastai head</li>
<li>Loss function: cross entropy</li>
<li>Sampling: 128x1024 crops around true positive samples</li>
<li>Spectrogram parameters: n mels 128, hop length 640, sample rate 32000</li>
<li>Augmentations: clipping distortion, pitch shift and mixup</li>
<li>Inference: Predict on crops with a small width (e.g. 128x128 instead of 128x1024 used for training) and calculate the max probability for each of the 24 classes.</li>
</ul>
<p><strong>Introductory monologue</strong><br>
First and foremost, this was an interesting competition and a good learning opportunity as it is often the case in Kaggle! One “problem” of this competition is that the test data was labeled with a different method and no samples of labeled test data were provided. This makes it difficult to get a sense of validation score and increases the danger of overfiting the public test results. In fact, I almost gave up on this competition when I realized this was the case. But eventually I decided to get back to it and work on a simple solution and on a python library – <strong>dl_pipeline</strong> ( <a href="https://github.com/mnpinto/dl_pipeline" target="_blank">https://github.com/mnpinto/dl_pipeline</a>) – that I will use as a general framework for future kaggle competitions in general. Initially, the idea for dl_pipeline was just to keep my code more organized and more reusable but I figured that maybe there’s also some value in sharing it. </p>
<p><strong>Data preprocessing</strong><br>
Save all wave files in npy files with sample rate of 32000 Hz to save time.</p>
<pre><code>def audio2npy(file, path_save:Path, sample_rate=32_000):
path_save.mkdir(exist_ok=True, parents=True)
wave, _ = librosa.load(file, sr=sample_rate)
np.save(path_save/f'{file.stem}.npy', wave)
</code></pre>
<p>I didn't convert the audio to spectrograms right away since I still want the ability to use audio augmentation on the waveforms.</p>
<p><strong>Augmentations and Spectrograms</strong></p>
<ul>
<li>First I create crops on the waveform including the true positive labels with a number of samples calculated so that the spectrogram will have a width of 1024. </li>
</ul>
<p><strong>Note:</strong> Cropping before applying the augmentations is much faster than the other way around.</p>
<ul>
<li>Then for the waveform augmentations I used the <strong>audiomentations</strong> library (<a href="https://github.com/iver56/audiomentations)" target="_blank">https://github.com/iver56/audiomentations)</a>. I ended up using just the following augmentations as based on public lb I didn't find that others were helping, although this would require a proper validation to take any conclusions. </li>
</ul>
<pre><code>def audio_augment(sample_rate, p=0.25):
return Pipeline([
ClippingDistortion(sample_rate, max_percentile_threshold=10, p=p),
PitchShift(sample_rate, min_semitones=-8, max_semitones=8, p=p),
])
</code></pre>
<p><strong>Note:</strong> Some augmentations are much slower, for example, pitch shift and time stretch. When using those augmentations the probability of use makes a big difference in how long the training takes. </p>
<ul>
<li>Then I searched the fastest way to convert the audio to spectrograms in the GPU and I ended up using <strong>nnAudio</strong> (<a href="https://github.com/KinWaiCheuk/nnAudio)" target="_blank">https://github.com/KinWaiCheuk/nnAudio)</a>. Again, converting to spectrogram after the waveform is cropped is a nice gain in processing time.</li>
</ul>
<p><strong>Model</strong><br>
I tried several models but the one that got me a better result in the public leaderboard was densenet121 and the second-best ResNeSt50. One particularity is that I use for all the models the fastai head with strong dropout.</p>
<p>The fastai head (using <code>create_head(num_features*2, num_classes, ps=0.8)</code>).</p>
<pre><code>(1): Sequential(
(0): AdaptiveConcatPool2d(
(ap): AdaptiveAvgPool2d(output_size=1)
(mp): AdaptiveMaxPool2d(output_size=1)
)
(1): Flatten(full=False)
(2): BatchNorm1d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(3): Dropout(p=0.4, inplace=False)
(4): Linear(in_features=2048, out_features=512, bias=False)
(5): ReLU(inplace=True)
(6): BatchNorm1d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(7): Dropout(p=0.8, inplace=False)
(8): Linear(in_features=512, out_features=24, bias=False)
)
</code></pre>
<p><strong>Training</strong><br>
I guess code speaks more than words, particularly for those familiar with fastai:</p>
<pre><code>bs = 32
learn = Learner(dls, model, loss_func=cross_entropy, metrics=[accuracy, lrap], cbs=cbs)
learn.to_fp16(clip=0.5);
learn.fit_one_cycle(30, 1e-3, wd=3e-2, div_final=10, div=10)
</code></pre>
<p>So in English, this is a one cycle learning rate schedule with <strong>30 epochs</strong> starting with lr=1e-4, increasing to 1e-3 and then decreasing back to 1e-4 following cosine anealing schedule. The <strong>loss function</strong> is the good old cross-entropy. Also, a <strong>weight decay</strong> of 3e-2 was used, a <strong>gradient clip</strong> of 0.5 and the train was done with <strong>mixed-precision</strong> so that my GTX 1080 can handle a <strong>batch size</strong> of 32 with 128x1024 image size.</p>
<p>One training epoch takes about 1 minute on my GTX 1080, I guess it's not bad considering that I'm doing waveform augmentations on CPU that even with p=0.25 take some time.</p>
<p><strong>Inference</strong><br>
This is the fun part because it was almost by mistake that I realised that making inference with smaller tiles is way better. I presume that this is the case because I'm training with cross-entropy for a single label problem but the test data is labelled with multiple labels. By using smaller crops the predictions are more multilabel friendly. The reason I've been using cross-entropy instead of binary cross-entropy and sigmoid for the typical multilabel problem is that for me the convergence was much faster using the cross-entropy approach and with better results. Maybe I made a mistake somewhere I don't know, I didn't investigate it in much detail.</p>
<ul>
<li><p>Run predictions on crops of the spectrogram with a width of 64, 128 and 256 (remember training was done with 1024), calculate the max probability for each class for each case (64, 128, 256) and the average of the 3 cases. The average of the 3 gave me public lb 0.928 on my best single model that I describe above, compared to 0.925 for just the 128 width inference.</p></li>
<li><p>The final solution with public lb 0.932 and private lb 0.940 is an ensemble of a few training interations with some modifications. (I will update this tomorrow with more information).</p></li>
</ul>
<p><strong>dl_pipeline</strong><br>
And again the code for this solution is now public on this repo: <a href="https://github.com/mnpinto/dl_pipeline" target="_blank">https://github.com/mnpinto/dl_pipeline</a></p>
<p>The following code should correspond to the best single model solution but I need to check if I didn't mess up anything when cleaning the code:</p>
<pre><code>#!/bin/bash
arch='densenet121'
model_name='model_0'
sample_rate=32000
n_mels=128
hop_length=640
for fold in 0 1 2 3 4
do
echo "Training $model for fold $fold"
kaggle_rainforest2021 --fold $fold --model_name $model_name \
--model $arch --sample_rate $sample_rate --n_mels $n_mels \
--hop_length $hop_length --bs 32 --head_ps 0.8 \
--tile_width 1024 --mixup true >> log.train
done
for tw in 64 128 256
do
echo "Generate predictions for $model with tile_width of $tw"
kaggle_rainforest2021 --run_test true --model_name $model_name \
--model $arch --sample_rate $sample_rate --n_mels $n_mels \
--hop_length $hop_length --tile_width $tw \
--save_preds true >> log.predict
done
</code></pre>
<hr>
<p>Thanks for reading!</p> |
Rainforest Connection Species Audio Detection | 17th 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: Rainforest Connection Species Audio Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Congratulations to all the winners and gold getters, I guess those teams that broke the 0.950 wall have found the essence of this competition, which we couldn't. <br>
<br><br>
Firstly, thanks to the host for holding quite an interesting competition. Partly labeled classification is a challenging task, which made this competition more interesting than a simple bioacoustics audio tagging competition.<br>
<br><br>
Our solution is a ranking average of image classification models and SED models. <a href="https://www.kaggle.com/yasufuminakama" target="_blank">Y.Nakama</a>, <a href="https://www.kaggle.com/kaerunantoka" target="_blank">kaerururu</a>, and I worked a lot on SED models but couldn't break 0.90 until we merge with <a href="https://www.kaggle.com/thiraiwa" target="_blank">Taku Hiraiwa</a>. His model was based on image classification similar to <a href="https://www.kaggle.com/c/rfcx-species-audio-detection/discussion/220304" target="_blank">@cpmpml's model</a>. We found that quite good , so we focused on improving image classification models in the remained days.</p>
<h2>Image classification models</h2>
<p>It was <a href="https://www.kaggle.com/thiraiwa" target="_blank">Taku Hiraiwa</a>'s idea to only use the <em>annotated</em> part of the train data. To do so, we crop the image patches from log-melspectrogram of train data based on the <code>t_min</code>, <code>t_max</code>, <code>f_min</code>, <code>f_max</code> information of train_tp.csv and train_fp.csv, and resized the patch to fixed shape (say, 320 x 320 or so). The cropping is performed on the fly through training, so the part we crop out is randomized along with time axis.<br>
With these image patches we trained EfficientNet models, and monitored F1 score with threshold 0.5. <br>
Here's the other details of image classification models.</p>
<ul>
<li>image size: varies from (244, 244) to (456, 456) between models</li>
<li>backbone: EfficientNetB0 - B5 (used <a href="https://rwightman.github.io/pytorch-image-models/" target="_blank"><code>timm</code></a> and used <code>tf_efficientnet_b<0-5>_ns</code> weights).</li>
<li>augmentation: GaussianNoise, Gain, PitchShift of <a href="https://github.com/iver56/audiomentations" target="_blank">audiomentations</a> on raw waveform. Also HorizontalFlip also had positive impact on LB slightly, so we used (but don't know why it worked).</li>
<li>AdamW optimizer with linear warmup scheduler</li>
<li>BCEFocalLoss<br>
<br><br>
In the end, we trained a stacking model that takes the output of models below which achieve public 0.942:</li>
</ul>
<ol>
<li><code>tf_efficientnet_b0_ns</code> image size 244</li>
<li><code>tf_efficientnet_b0_ns</code> image size 320</li>
<li><code>tf_efficientnet_b0_ns</code> image size 456</li>
<li><code>tf_efficientnet_b1_ns</code> image size 456</li>
<li><code>tf_efficientnet_b2_ns</code> image size 456</li>
<li><code>tf_efficientnet_b3_ns</code> image size 456</li>
<li><code>tf_efficientnet_b4_ns</code> image size 456</li>
<li><code>tf_efficientnet_b5_ns</code> image size 456</li>
</ol>
<h2>SED models</h2>
<p>All of our SED models use the head architecture introduced in <a href="https://github.com/qiuqiangkong/audioset_tagging_cnn" target="_blank">PANNs repository</a>. The CNN encoder is either EfficientNet or ResNeSt, and they are trained with weak/strong supervision. We tried a lot of things on this, but couldn't find factors that consistently work well - which means the LB scores varied quite randomly w.r.t CV score.<br>
Our best SED model is rank average of 11 models(public: 0.901, privte: 0.911) below - each of them differs slightly so we describe the difference briefly.</p>
<h3>2 x kaerururu's model (public: 0.882, 0.873)</h3>
<ul>
<li>Based on public starter SED (EffnB0) notebook (<a href="https://www.kaggle.com/gopidurgaprasad/rfcx-sed-model-stater" target="_blank">https://www.kaggle.com/gopidurgaprasad/rfcx-sed-model-stater</a>)</li>
<li>3ch input</li>
<li>10sec clip</li>
<li>waveform mixup</li>
<li>some augmentation (audiomentations)</li>
<li>pseudo-labeled datasets (add labels on tp data)</li>
<li>trained with tp and fp dataset (1st training)</li>
<li>trained with pseudo-labeled tp (2nd training)</li>
<li>tta=10</li>
</ul>
<h3>5 x arai's model (public: 0.879,0.880, 0.868, 0.874, 0.870)</h3>
<ul>
<li>Based on Birdcall's challenge 6th place (<a href="https://github.com/koukyo1994/kaggle-birdcall-6th-place" target="_blank">https://github.com/koukyo1994/kaggle-birdcall-6th-place</a>)</li>
<li>ResNeSt50 encoder or EfficientNetB3 encoder</li>
<li>AddPinkNoiseSNR / VolumeControl / PitchShift from <a href="https://www.kaggle.com/hidehisaarai1213/rfcx-audio-data-augmentation-japanese-english" target="_blank">My Notebook</a></li>
<li>tp only</li>
</ul>
<h3>4 x Y.Nakama's model (public: 0.871, 0.863, 0.866, 0.870)</h3>
<ul>
<li>Based on Birdcall's challenge 6th place (<a href="https://github.com/koukyo1994/kaggle-birdcall-6th-place" target="_blank">https://github.com/koukyo1994/kaggle-birdcall-6th-place</a>)</li>
<li>ResNeSt50 encoder or ResNet200D encoder</li>
<li>mixup & some augmentations</li>
<li>2nd stage training<ul>
<li>1st stage: weighted loss for framewise_logit & logit</li>
<li>2nd stage: loss for logit</li></ul></li>
<li>tp only</li>
</ul> |
Rainforest Connection Species Audio Detection | 43rd 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: Rainforest Connection Species Audio Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>First of all, many thanks to Kaggler.<br>
I got a lot of ideas from Kaggler in the discussion. And it was fun.</p>
<p>My solution summary is below.</p>
<ul>
<li>The high resolution of spectrogram</li>
<li>Post-processing with moving average</li>
<li>Teacher-student model for missing labels</li>
</ul>
<h1>1st stage: SED</h1>
<p>I started from basic experiment with <a href="https://www.kaggle.com/c/rfcx-species-audio-detection/discussion/211007" target="_blank">SED</a>. Why SED? Because I think SED is strong in the multi label task. </p>
<p>I used log mel-spectrogram as the input of SED. Basic experiment involves data augmentation (Gaussian noise, SpecAugment and MixUP), backbone model choice and adjusting resolution of log mel-spectrogram. As a result, below condition was the best for me.</p>
<ul>
<li>No noise injection</li>
<li>MixUp</li>
<li>The best model architecture is EfficientNet</li>
<li><strong>The higher the resolution</strong> of log mel-spectrogram, the better the result.</li>
</ul>
<h3>The resolution</h3>
<p>The most important one is the resolution. Recently, in Kaggle computer vision solution, the higher the resolution of the image, the better the result. In spectrogram, the same phenomenon may happen. In mel-spectrogram, the resolution can be changed by adjusting "hop_size" and "mel_bins". Following result is changing the resolution with ResNest50(single model).</p>
<table>
<thead>
<tr>
<th>Resolution(Width-Height)</th>
<th>public LB</th>
</tr>
</thead>
<tbody>
<tr>
<td>1501-64(PANNs default)</td>
<td>0.692</td>
</tr>
<tr>
<td>3001-128</td>
<td>0.805</td>
</tr>
<tr>
<td>6001-64</td>
<td>0.725</td>
</tr>
<tr>
<td>1501-256</td>
<td>0.761</td>
</tr>
<tr>
<td>751-512</td>
<td><strong>0.823</strong></td>
</tr>
<tr>
<td>1501-512</td>
<td>0.821</td>
</tr>
</tbody>
</table>
<p>The resolution was critical! According to experimental result, good resolution was "high" and similar to the square. 751-512 looks good. As a result, I chose 858-850. This configuration is as follows.</p>
<pre><code>model_config = {
"sample_rate": 48000,
"window_size": 1024,
"hop_size": 560,
"mel_bins": 850,
"fmin": 50,
"fmax": 14000,
"classes_num": 24
}
</code></pre>
<h3>Post-processing</h3>
<p>I used <a href="https://www.kaggle.com/c/rfcx-species-audio-detection/discussion/211007" target="_blank">Framewise output</a> for submission. It contains time and classes information. But there is a lot of false positive information in framewise output. Because they are not processing by a long time information. Therefore <strong>a short event of framewise output should be deleted.</strong> I prepared post-processing for framewise output. It is a moving average.</p>
<p><img src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/264781/2d0ad5b8-f046-64da-a98a-96f0ae79ba2e.png" alt="image.png"></p>
<p>By taking a moving average in the time direction for each class, we can delete short events. This idea is based on <a href="http://dcase.community/documents/challenge2020/technical_reports/DCASE2020_Chan_6.pdf" target="_blank">the paper</a>[1]. The sample code is as follows.</p>
<pre><code>def post_processing(data): # data.shape = (24, 600) # (classes, time)
result = []
for i in range(len(data)):
result.append(cv2.blur(data[i],(1,31)))
return result
</code></pre>
<p>I improved LB by using moving average. The following result is comparing post-processing with EfficientNetB3(single model).</p>
<table>
<thead>
<tr>
<th></th>
<th>public LB</th>
</tr>
</thead>
<tbody>
<tr>
<td>w/o post-processing</td>
<td>0.785</td>
</tr>
<tr>
<td>w/ post-processing</td>
<td><strong>0.840</strong></td>
</tr>
</tbody>
</table>
<h3>Summary</h3>
<ul>
<li>MixUp(alpha=0.1)</li>
<li>Epoch 30</li>
<li>Adam(lr=0.001) + CosineAnnealing(T=10)</li>
<li>Batchsize 6</li>
<li>Use only tp label</li>
<li>Get random tp clip 10 sec</li>
<li>The resolution of log mel-spectrogram: 858-850</li>
<li>Loss function: BCE</li>
<li><a href="https://www.kaggle.com/c/rfcx-species-audio-detection/discussion/211007" target="_blank">Weak label training</a></li>
<li>Post-processing: moving average</li>
</ul>
<p>Then I got <strong>0.916 public LB</strong> with EfficientNetB0(5-folds average ensemble).</p>
<h1>2nd stage: missing labels and the ensemble</h1>
<p>I reported <a href="https://www.kaggle.com/c/rfcx-species-audio-detection/discussion/208830#1139171" target="_blank">discovering missing labels and re-train</a>. And It didn't work. After that, I thought about missing labels again. My answer is that the model is not correct for discovering missing labels. There are a lot of missing labels around tp. Therefore the model is not correct. </p>
<p><img src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/264781/0e6009db-c1cf-7297-3ac4-df92dd3420c5.png" alt="train.png"></p>
<p>To solve this issue, I used teacher-student model. </p>
<p><img src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/264781/79d8e1c8-6814-68c6-0a9d-d41d830fcdfb.png" alt="geretation.png"></p>
<p>1st generation is similar to 1st stage. I gradually increased model prediction ratio. By using teacher-student model, I could discover missing labels. Specially, in strong label training, teacher-student model was effective. Following result is teacher-student model score with EfficientNetB0.</p>
<p><img src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/264781/ddded273-c2b1-92c1-3272-1e19377a5b77.png" alt="image.png"></p>
<p>"MixUp rate" is probabilistic MixUp. This method is based on <a href="https://arxiv.org/abs/2102.01243" target="_blank">the paper</a>[2]. </p>
<p>Finally, I made the ensemble of 1st stage model and 2nd stage model. Ensemble procedure is simple average. Then I got <strong>0.924 public LB.</strong></p>
<h1>References</h1>
<p>[1] Teck Kai Chan, Cheng Siong Chin1 and Ye Li, "SEMI-SUPERVISED NMF-CNN FOR SOUND EVENT DETECTION".<br>
[2] Yuan Gong, Yu-An Chung, and James Glass, "PSLA: Improving Audio Event Classification with<br>
Pretraining, Sampling, Labeling, and Aggregation".</p>
<h1>Appendix: the resolution and EfficientNet</h1>
<p>Finally, I show interesting result. It is relationship between EfficientNet and the resolution. The following result is public LB(5-folds average ensemble).</p>
<table>
<thead>
<tr>
<th>Resolution(W-H)</th>
<th>751-512</th>
<th>751-751</th>
<th>858-850</th>
</tr>
</thead>
<tbody>
<tr>
<td>EfficientNetB0</td>
<td>0.893</td>
<td>0.904</td>
<td><strong>0.916</strong></td>
</tr>
<tr>
<td>EfficientNetB3</td>
<td><strong>0.913</strong></td>
<td>0.912</td>
<td>0.900</td>
</tr>
</tbody>
</table>
<p>In B0, the higher resolution, the better result. But B3 was vice versa. Usually, the larger EfficientNet, the better at <a href="https://www.kaggle.com/c/siim-isic-melanoma-classification/discussion/154683" target="_blank">high resolution</a> it is. But the above is reverse. Why?</p>
<p>Maybe <strong>domain shift</strong>(train: noisy sound -> test: clean sound) is concerned. B3 has learned about <strong>train domain features</strong>(noisy sound). On the other hand, B0 has less representational ability than B3. Therefore B0 has learned the <strong>common features</strong> of the train and test domain with high resolution. Without domain shift, B3 would have also shown good results with high resolution.</p> |
HuBMAP - Hacking the Kidney | single model gold medal(private 948) 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: HuBMAP - Hacking the Kidney
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>It's hard to say it's a happy journey. <br>
We missed the private 948 solution submitted last night.😄<br>
<img src="https://i.loli.net/2021/05/11/Zfyk6rX7MHCRdv4.png" alt="微信截图_20210511090244.png"><br>
And I found that an experiment with lb912 got private 948, which I trained a month ago.<br>
<img src="https://i.loli.net/2021/05/11/Em2K3QYlXrOTwjs.png" alt="微信截图_20210511090219.png"><br>
I share the train, inference and tiles-making code of exp007 here.<br>
train: <a href="https://www.kaggle.com/tiandaye/hubmap-exp007-train?scriptVersionId=62523292" target="_blank">https://www.kaggle.com/tiandaye/hubmap-exp007-train?scriptVersionId=62523292</a><br>
inference: <a href="https://www.kaggle.com/tiandaye/hubmap-exp007-5folds?scriptVersionId=58430396" target="_blank">https://www.kaggle.com/tiandaye/hubmap-exp007-5folds?scriptVersionId=58430396</a><br>
tiles making: <a href="https://www.kaggle.com/tiandaye/make-tiles" target="_blank">https://www.kaggle.com/tiandaye/make-tiles</a></p>
<p>Unet with encoder='timm-efficientnet-b4' , weights='noisy-student', trained with label smooth and no PL.</p> |
Rainforest Connection Species Audio Detection | #6 Solution 🐼Tropic Thunder🐼 🚫 No hand labels🚫 | 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: Rainforest Connection Species Audio Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>It was a great competition. I'll document our journey primarily from my perspective, my teammates <a href="https://www.kaggle.com/jpison" target="_blank">@jpison</a> <a href="https://www.kaggle.com/amezet" target="_blank">@amezet</a> <a href="https://www.kaggle.com/pavelgonchar" target="_blank">@pavelgonchar</a> may chime in to add extra color… </p>
<p>Our solution is rank ensemble of two types of models, primarily 97% using the architecture described below, and 3% an ensemble of SED models. The architecture below was made in the last 7 days… I made my first (pretty bad) sub 8 days ago, and I joined team just before team merge deadline and all the ideas were done/implemented in ~7 days…</p>
<p>A single 5-fold model achieves 0.961 private, 0.956 public; details:</p>
<p><strong>Input representation.</strong> This is probably the key, we take each TP or FP and after spectrogram (not MEL, b/c MEL was intended to model human audition and the rainforrest species have not evolved like our human audition) crop it time and frequency wise with fixed size on a per-class basis. E.g. for class 0: minimum freq is 5906.25 Hz and max is 8250 Hz, and time-wise we take the longest of time length of TPs, i.e. for class 0: 1.29s. </p>
<p>With the above sample the spectrogram to yield an image, e.g.:<br>
<img src="https://i.imgur.com/bTw0aeQ.png" alt=""></p>
<p>The GT for that TP would be: </p>
<p><code>tensor([nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, 1., nan, nan, nan,nan, nan, nan, nan, nan, nan, nan, nan]))</code></p>
<p>As other competitors, we expand the classes from 24 to 26 b/c to split species that have two songs. </p>
<p>Other sample:</p>
<p><img src="https://i.imgur.com/JST401j.png" alt=""></p>
<p><code>tensor([nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, 1., nan, nan, nan, nan, nan,nan, nan, nan, nan, nan, nan, nan, nan]))</code></p>
<p>Note the image size is the same, so time and frequency are effectively strectched wrt to what the net will see, but I believe this is fine as long as the net has enough receptive field (which they have). </p>
<p>The reason of doing it this way is that we need to inject the time and frequency restrictions as inductive bias somehow, and this looks like an nice way.</p>
<p><strong>Model architecture.</strong> This is just an image classifier outputing 26 logits, that's it. The only whistle is to add relative positional information in the freq axis (à la <a href="https://arxiv.org/abs/1807.03247" target="_blank">coordconv</a>), so model is embarrasingly simple:</p>
<pre><code>class TropicModel(Module):
def __init__(self):
self.trunk = timm.create_model(a.arch,pretrained=True,num_classes=n_species,in_chans=1+a.coord)
self.do = nn.Dropout2d(a.do)
def forward(self,x):
bs,_,freq_bins,time_bins = x.size()
coord = torch.linspace(-1,1,freq_bins,dtype=x.dtype,device=x.device).view(1,1,-1,1).expand(bs,1,-1,time_bins)
if a.coord: x = torch.cat((x,coord),dim=1)
x = self.do(x)
return self.trunk(x)
</code></pre>
<p><strong>Loss function.</strong> Just masked Focal loss. Actually this was a mistake b/c Focal loss was a renmant of a dead test and I (accidentally) left it there, where I thought (until I checked code now to write writeup) that BCE was being used. Since we are doing balancing BCE should work better.</p>
<p><strong>Mixover.</strong> Inspired by mixup, mixover takes a bunch of (unbalanced) TP and FPs (which strictly speaking are TNs) and creates combinations of them so that the resulting labels can be supervised (1+NaN=1, 0+NaN=NaN,0+0=0) making sure linear interpolation is not destructive (beta,alpha=4; clip to 0.2,0.8); then it samples from the resulted mixed items computing class distribution so that resulting samples are balanced. Code is a bit tricky, but still:</p>
<pre><code>class MixOver(MixHandler):
"Inspired by implementation of https://arxiv.org/abs/1710.09412"
def __init__(self, alpha=): super().__init__(alpha)
def before_batch(self):
ny_dims,nx_dims = len(self.y.size()),len(self.x.size())
bs=find_bs(self.xb)
all_combinations = L(itertools.combinations(range(find_bs(self.xb)), 2))
lam = self.distrib.sample((len(all_combinations),)).squeeze().to(self.x.device).clip(0.2,0.8)
lam = torch.stack([lam, 1-lam], 1)
self.lam = lam.max(1)[0]
comb = all_combinations
yb0,yb1 = L(self.yb).itemgot(comb.itemgot(0))[0],L(self.yb).itemgot(comb.itemgot(1))[0]
yb_one = torch.full_like(yb0,np.nan)
yb_one[yb0>0.5] = yb0[yb0>0.5]
yb_one[yb1>0.5] = yb1[yb1>0.5]
yb_two = torch.clip(yb0+yb1,0,1.)
yb_com = yb_one.clone()
yb_com[~torch.isnan(yb_two)] = yb_two[~torch.isnan(yb_two)]
n_ones_or_zeros=(~torch.isnan(yb_com)).sum()
ones=torch.sum(yb_com>=0.5,dim=1)
zeros=torch.sum(yb_com<0.5,dim=1)
p_ones = (n_ones_or_zeros/(2*( ones.sum())))/ones
p_zeros= (n_ones_or_zeros/(2*(zeros.sum())))/zeros
p_zeros[torch.isinf(p_zeros)],p_ones[torch.isinf(p_ones)]=0,0
p=(p_ones+p_zeros).cpu().numpy()/(p_ones+p_zeros).sum().item()
shuffle=torch.from_numpy(np.random.choice(yb_com.size(0),size=bs,replace=True,p=p)).to(self.x.device)
comb = all_combinations[shuffle]
xb0,xb1 = tuple(L(self.xb).itemgot(comb.itemgot(0))),tuple(L(self.xb).itemgot(comb.itemgot(1)))
self.learn.xb = tuple(L(xb0,xb1).map_zip(torch.lerp,weight=unsqueeze(self.lam[shuffle], n=nx_dims-1)))
self.learn.yb = (yb_com[shuffle],)
</code></pre>
<p><strong>Augmentations.</strong> Time jitter (10% of time length), white noise (3 dB).</p>
<p><strong>External data.</strong> We used <a href="https://www.kaggle.com/rohanrao/xeno-canto-bird-recordings-extended-a-m" target="_blank">Xeno Canto A-M and N-Z</a> recording and since they have 264 species we made the wild assumption that if we have 24 species and they have 10X randomly sampling would give you a "right" label (TN) 90% of the time… the goal was to add jungle/rainforest diversity at the expense of a small noisy labels which were accounted for labeling these weak labels as 0.1 (vs 0).</p>
<p><strong>Pseudolabeling.</strong> We also pseudolabeled using OOF models the non labeled parts of training data to mine more TPs, and manually balanced the resulting pseudo-label TPs. </p>
<p><strong>Code.</strong> Pytorch, Fastai.</p>
<p><strong>Final thoughts.</strong> It was a very fun competition and I am very glad of achieving a gold medal with a very short time, I want to thank Kaggle, sponsor and competitors for the competition and discussions; and of course my teammates <a href="https://www.kaggle.com/jpison" target="_blank">@jpison</a> <a href="https://www.kaggle.com/amezet" target="_blank">@amezet</a> <a href="https://www.kaggle.com/pavelgonchar" target="_blank">@pavelgonchar</a> for inviting me giving me the small nudge I needed to join 😉</p>
<p>Edit: I've added no hand labels to the title because this competition was VERY unique in that Kaggle effectively allowed hand labeling and that's very unusual. (Re: hand labeling vs external data, it was also very uncommon not having to disclose which external data you used during competition).</p> |
Rainforest Connection Species Audio Detection | 11th place, The 0.931 Magic Explained: Image 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: Rainforest Connection Species Audio Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>First of all, thanks to the host, for providing yet another very interesting audio challenge. The fact that it was only partly labelled was a significant difference with previous bird song competition.</p>
<p>Second, congrats to all those who managed to pass the 0.95 bar on public LB. I couldn't, and, as I write this before competition deadline, I don't know why. I tried a lot of things, and it looks like my approach has some fundamental limit.</p>
<p>Yet it was good enough to produce a first submission at 0.931, placing directly at 3rd spot while the competition had started two months earlier.</p>
<p>This looked great to me. In hindsight, if my first sub had been weaker, then I would not have stick to its model and would have explored other models probably, like SED or Transformers.</p>
<p>Anyway, no need to complain, I learned a lot of stuff along the way, like how to efficiently implement teacher student training of all sorts. I hope this knowledge will be useful in the future.</p>
<p>Back to the topic, my approach was extremely simple: each row of train data, TP or FP, gives us a label for a crop in the (log mel) spectrogram of the corresponding recording. If time is x axis and frequency the y axis, as is generally the case, then t_min, t_max gives bounds on x axis, and f_min, f_max gives bounds on the y axis.</p>
<p>We then have a 26 multi label classification problem (24 species but two species have 2 song types. I treated each species/song type as a different class). This is easily handled with BCE Loss.</p>
<p>The only little caveat is that we are given 26 classes (species + song type) but we get only one class label, 0 or 1 per image. We only have to mask the loss for other classes and that's it!</p>
<p>I didn't know it when I did it, but a similar way has been used by some of the host of the competition, in this paper (not the one shared in the forum): <a href="https://www.sciencedirect.com/science/article/abs/pii/S0003682X20304795" target="_blank">https://www.sciencedirect.com/science/article/abs/pii/S0003682X20304795</a></p>
<p>The other caveat is that the competition metric works with a label for every class. Which we don't have in train data. However the competition metric is very similar to a roc auc score per recording: when a pair of predictions is in the wrong order, i.e. a positive label has a prediction lower than another negative label prediction, then the metric is lowered. As a proxy I decided to use roc-auc on my multi label classification problem. Correlation with public LB is noisy, but it was good enough to let me make progress without submitting for a while.</p>
<p>What worked best for me was to not resize the crops. It means my model had to learn from sometimes tiny images. To make it work by batch I pad all images to 4 seconds on the x axis. Crops longer than that were resized on the x axis. Shorter ones were padded with 0. One thing that helped was to add a positional encoding on the frequency axis. Indeed, CNNs are good at learning translation independent representations, and here we don't want the model to be frequency independent. I simply added a linear gradient on the frequency axis to all my crops.</p>
<p>For the rest my model is exactly what I used and shared in the previous bird song competition: <a href="https://www.kaggle.com/c/birdsong-recognition/discussion/183219" target="_blank">https://www.kaggle.com/c/birdsong-recognition/discussion/183219</a> Just using the code I shared there was almost good enough to get 0.931. The only differences are that I add noise as in the first solution in that competition. I also did not use a no call class here, nor secondary labels.</p>
<p>For prediction I predict on slidding crops of each test recording and take the overall max prediction. This is slow as I need to do each of the 26 classes separately. This is also maybe where I lost against others: my model cannot learn long range temporal patterns, nor class interactions.</p>
<p>With the above I entered high with an Efficient B0 model, and moved to 0.945 in few submissions with Efficientnet B3 . Then I got stuck for the remainder of the competition. </p>
<p>I was convinced that semi supervised learning was the key, and I implemented all sorts of methods, from Google (noisy student), Facebook, others (mean student). They all improved weaker models but could not improve my best models.</p>
<p>In the last days I looked for external data with the hope that it would make a difference. Curating all this and identifying which species correspond to the species_id we have took some time and I only submitted models trained with it today. They are in same range as previous ones unfortunately. with a bit more time I am sure it could improve score, but I doubt it would be significant..</p>
<p>For matching species to species id I used my best model and predicted the external data. It would be interesting to see if I got this mapping right. Here is what I converged to :</p>
<p>0 E. gryllus<br>
1 Leutherodactylus brittoni<br>
2 Leptodactylu albilabris<br>
3 E. coqui<br>
4 E. hedricki<br>
5 Setophaga angelae<br>
6 Melanerpes portoricensis<br>
7 Coereba flaveola<br>
8 E. locustus<br>
9 Margarops fuscatus<br>
10 Loxigilla portoricensis<br>
11 Vireo altiloquus<br>
12 E. portoricensis<br>
13 Megascops nudipes<br>
14 E. richmondi<br>
15 Patagioenas squamosa<br>
16 Eleutherodactylus antillensis<br>
17 Turdus plumbeus<br>
18 E. unicolor<br>
19 Coccyzus vieilloti<br>
20 Todus mexicanus<br>
21 E wightmanae<br>
22 Nesospingus speculiferus<br>
23 Spindalis portoricensis</p>
<p>The picture in the paper shared in the forum helped to disambiguate few cases: <a href="https://reader.elsevier.com/reader/sd/pii/S1574954120300637" target="_blank">https://reader.elsevier.com/reader/sd/pii/S1574954120300637</a> The paper also gives the list of species. My final selected subs did not include models trained on external data, given they were not improving.</p>
<p>This concludes my experience in this competition. I am looking forward to see how so many teams passed me during the competition. There is certainly a lot to be learned.</p>
<p>Edit. I am very pleased to get a solo gold in a deep learning competition., This is a first for me, and it was my goal here.</p>
<p>Edit 2: The models I trained last day with external data are actually better than the ones without. The best one has a private LB of 0.950 (5 folds). However, they are way better on private LB but not on public LB. Selecting them would have been an act of faith. And late submission show they are not good enough to change my rank. No regrets then.</p>
<p>Edit 3 Using Chris Deotte post processing. my best selected sub gets 0.7390 on private LB. It means that PP was what I missed and that my modeling approach was good enough probably. I'll definitely look at test prediction distribution from now on!</p> |
Rainforest Connection Species Audio Detection | [completed] rank 19th solution in 13 days - LB 0.937/0.939 (public/private) 5 fold 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: Rainforest Connection Species Audio Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>[summary]</p>
<ul>
<li><p>Design a sliding window conv classifier net. Trained with tp and fp annotations (no pesudo label) on resnet34, this architechiture achieved LB 0.937/0.939 (public/private) in 5 fold model. A single fold model gives 0.881/0.888 (public/private). The first max pooling resnet34 is removed to make the stride of the backbone 16 (instead of 32)</p></li>
<li><p>Final submission is LB 0.945/0.943 (public rank 15/private rank 19) is an ensemble of this network with different CNN backbone.</p></li>
</ul>
<hr>
<p>I am grateful for Kaggle and the host Rainforest Connection (RFCx) for organizing the competition. </p>
<p>As a Z by HP & NVidia global datascience ambassador under <a href="https://datascience.hp.com/us/en.html.HP" target="_blank">https://datascience.hp.com/us/en.html.HP</a> & Nvidia has kindly provided a Z8 datascience workstation for my use in this competition. Without this powerful workstation, it would not be possible for me to develop my idea from scratch within 13 days. </p>
<p>Because I can finish experiments at a very great speed (z8 has ax quadro rtx 8000, NVlink 96GB), I gain a lot of insights into model training and model design when the experimental feedback is almost instantaneous. I want to share these insights with the kaggle community. </p>
<p>Hence I started another thread to guide and supervise kagglers who wants to improve their training skills. This is targeted to bring them from sliver to gold levels. You can refer to:<br>
<a href="https://www.kaggle.com/c/rfcx-species-audio-detection/discussion/220379" target="_blank">https://www.kaggle.com/c/rfcx-species-audio-detection/discussion/220379</a><br>
<a href="https://www.kaggle.com/c/hpa-single-cell-image-classification/discussion/217238" target="_blank">https://www.kaggle.com/c/hpa-single-cell-image-classification/discussion/217238</a></p>
<hr>
<p>data preprocessing</p>
<ul>
<li>log mel spectrogram with modified PCEN denoising (per- channel energy normalization). A 10sec clip has melspec of size 128x938<br>
n_fft = 2048<br>
win_length = 2048<br>
hop_length = 512 <br>
num_freq = 128</li>
</ul>
<hr>
<p>augmentation</p>
<ul>
<li>I haven't tried much augmentation yet. For TP annotation, random shift by 0.02 sec. For FP annotation, random shift width of the annotation and then random flip, mixup, cut and paste of the original annotation and its shift version.</li>
<li>Augmentation is done in the temporal time domain because of my code. (this is not the best solution)</li>
<li>It can be observed that if I increased the FP augmentation, the bce loss of the validation FP decreases and the public LB score improved.</li>
<li>heavy dropout in model</li>
</ul>
<hr>
<p>model and loss</p>
<ul>
<li>please see the below images</li>
<li>during training, I monitor the separate log loss of validation TP and FP. I also use the LRAP assumpting one label (i.e. top-1 correctness). This is to decide when to early stop or decrease learning rate. These are not the best approach.</li>
</ul>
<p><img src="https://i.ibb.co/txpjSWk/Selection-041.png" alt=""><br>
<img src="https://i.ibb.co/C9fQh7P/Selection-042.png" alt=""><br>
<img src="https://i.ibb.co/wymW9fB/Selection-040.png" alt=""><br>
<img src="https://i.ibb.co/9hhCfrw/Selection-039.png" alt=""></p>
<p>daily progress:<br>
<img src="https://i.ibb.co/7kGcfpj/Selection-050.png" alt=""><br>
I enter the competition are reading CPMP post, saying that he has 0.930 LB in the first submission. WOW! Reading between the lines, it means:</p>
<ol>
<li>the public kernels are doing it "wrong". It could be the problem setting, the network architecture, the data, or some magic features. there is something very fundamental that can do better than the public kernel.</li>
<li>0.930 is quite high score (in the gold region). With 2 more week to the deadline, I decided to give it a try. if I solved this unobvious puzzle, i may end up in the gold region as well.</li>
<li>the first step is to go through the public kernel (some PANN SED) and the baseline image classifier. I want to see what most people are doing (and could be improved)</li>
<li>after working for a week, I realize that there are two major "potential flaws":<ul>
<li>treating it as a multi-instance learning SED. Well, MIL could be a solution, but the problem is that we don't have bag label (clip label). Most MIL required bag level label, but lack instance level label (segment label).Here we have the opposite.</li>
<li>not using FP in train. Most public kernel use only TP as train only. </li></ul></li>
<li>hence I start to design my own network architecture. The first step is an efficient way to do crop classification based on mean annotation box. Hence I design the slide window network.</li>
<li>The next step is to use TP+FP in training</li>
<li>The last step is to use pesudo labels, but I don't have time to complete this. But I do have some initial experimental results on this. Top-1 (max over time) pesudo labels is about 95% accurate for LB score of 0.94. This is good enough for distillation.</li>
<li>Because pesudo labeling requires many probing to prevent error propagation, I could not do it because I don't have sufficient slots in the last days. Worst still, there is no train data at clip level at all. This makes local testing impossible.</li>
</ol>
<p>I was able to train 5-fold efficientB0 and resnet50 in the last day. Because of the large GPU card of the HP workstation I am using, I can train large models with large batch size. When I compared training the same model with smaller batch size on my old machines, I find that the results are different and inferior, even if I use gradient accumulation.</p>
<p>I strongly feel that we have reached a new era. I think this is also why the latest RTX3090 has larger GPU memory than the previous cards. The future is the transformers …. meaning more GPU memory. That's is how fast deep learning are moving!</p> |
Rainforest Connection Species Audio Detection | 33rd place solution - SED 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: Rainforest Connection Species Audio Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Congrats all the winners.<br>
I would like to thank the organizers for hosting a fun competition.</p>
<p>Our team's solution is an ensemble of seven models.<br>
The ensemble includes three SED models and four not-SED models.<br>
I will discuss the single model with the best score among them. (Public: 0.919/Private: 0.927)</p>
<h3>Model</h3>
<p>My model is based on the SED model described in <a href="https://www.kaggle.com/shinmura0" target="_blank">@shinmura0</a>'s discussion.<br>
<a href="https://www.kaggle.com/c/rfcx-species-audio-detection/discussion/211007" target="_blank">https://www.kaggle.com/c/rfcx-species-audio-detection/discussion/211007</a></p>
<ul>
<li>Feature Extractor:EfficientNet-B3</li>
<li>Loss Function:BCELoss</li>
<li>Optimizer:SGD</li>
<li>Scheduler:CosineAnnealingLR</li>
<li>LR:0.15</li>
<li>Data Augmentation:denoise</li>
<li>CV: 4Fold multilabel-stratifiedkfold</li>
</ul>
<p>My model is characterized by a very large learning rate, and as I reduced the learning rate from 0.15, the accuracy decreased.<br>
This is contrary to my experience.</p>
<p>I thought that data expansion would be very effective, and I tried various data expansions, but most of them did not work.</p>
<p>The only data enhancement that worked was the denoising that <a href="https://www.kaggle.com/takamichitoda" target="_blank">@takamichitoda</a> introduced in the discussion.<br>
In the discussion, he de-noises all the data, but it worked when extended with p=0.1.<br>
<a href="https://www.kaggle.com/c/rfcx-species-audio-detection/discussion/214019" target="_blank">https://www.kaggle.com/c/rfcx-species-audio-detection/discussion/214019</a></p>
<h3>Training data</h3>
<p>The training data was randomly cropped from a meruspectrogram at 60/9 seconds.<br>
I experimented with crop sizes ranging from 60/2 seconds to 60/20 seconds, and found that 60/9 and 60/10 gave good results.<br>
Most of the discussions used a 60/10 second crop, but I think a smaller size would have reduced the probability of including missing labels.</p>
<h3>Validation/Test data</h3>
<p>For the validation and test data, I used the same 60/9 seconds as the training date.</p>
<p>I create a total of 17 images by sliding the size of 60/9 seconds by half.<br>
Make a prediction for each of the 17 images, and use the max value of the probability of occurrence of each label as the prediction value.</p>
<p><img src="https://i.imgur.com/XBc6x3R.png" alt=""></p>
<p>The validation was very time consuming, as we needed to infer 17 images to validate 1 clip.</p>
<h3>Didn't work.</h3>
<p>Pseudo labels (train/test, soft label/hard label)<br>
Prediction model for class3<br>
-> The accuracy of 3 was extremely low, so I tried to create a model specific to 3, but it didn't work.</p> |
Cassava Leaf Disease Classification | Private LB 36th place/Public LB 1138th 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: Cassava Leaf Disease Classification
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Wow what a competition! We jumped from our public leaderboard position of 1138th place to the private position of 36th place, giving us a silver medal. Our solution is quite simple, we didn't utilize any techniques to deal with noise. Did I mention our submissions finished just minutes before the deadline?</p>
<h1>Solution:</h1>
<p>The components of our silver medal solution:</p>
<ol>
<li>EfficientNet-B7</li>
<li>EfficientNet-B3a from timm library</li>
<li>SE-ResNext50</li>
</ol>
<p><strong>EfficientNet-B7:</strong><br>
This is basically the same as <a href="https://www.kaggle.com/abhishek/tez-faster-and-easier-training-for-leaf-detection" target="_blank">this kernel</a> but with an EfficientNet-B7 model, 20 epochs, and image size of 512x512. 5-fold CV of:<br>
This model was submitted with a 3x TTA of the following augmentations:</p>
<pre><code> RandomResizedCrop,
Transpose(p=0.5),
HorizontalFlip(p=0.5),
VerticalFlip(p=0.5),
RandomBrightnessContrast(
brightness_limit=(-0.1,0.1),
contrast_limit=(-0.1, 0.1),
p=0.5
),
</code></pre>
<p>We will note that during the private submissions leak (~1.5 months ago), we noticed this model leaderboard submission was 9th place. </p>
<p><strong>EfficientNet-B3a:</strong></p>
<p>Training for this model was inspired by the training procedure in <a href="https://www.kaggle.com/keremt/progressive-label-correction-paper-implementation" target="_blank">this kernel</a> (but without label correction). Basically, the EfficientNet-B3a (a version of EfficientNet-B3 with weights trained by Ross Wightman) with the model body frozen and the fastai model head unfrozen was <br>
trained for 3 epochs. Following this, the whole model was unfrozen and trained for 10 epochs. 512x512 images were used, batch size of 32. The augmentations used were as follows:</p>
<pre><code> Dihedral(p=0.5),
Rotate(p=0.5, max_deg=45),
RandomErasing(p=0.5, sl=0.05, sh=0.05, min_aspect=1., max_count=15),
Brightness(p=0.5, max_lighting=0.3, batch=False),
Hue(p=0.5, max_hue=0.1, batch=False),
Saturation(p=0.5, max_lighting=0.1, batch=False),
RandomResizedCropGPU(size, min_scale=0.4),
CutMix()
</code></pre>
<p>Label smoothing loss function with Ranger optimizer was used. The CutMix+label smoothing was quite helpful, and we noticed a significant CV boost because of this. The model with the best validation loss was saved. This resulted in a model with a 5-fold CV of: 0.8914<br>
The model was submitted with 5x TTA with the training augmentations (<code>learn.tta(n=5,beta=0)</code>).</p>
<p><strong>SE-ResNext50:</strong></p>
<p>I just changed the model from the previous pipeline to SE-ResNext50. A 5-fold CV of: 0.8938</p>
<p>These three models were ensembled and submitted. </p>
<p>Public LB: 0.898<br>
Private LB: 0.900</p>
<p>We also had another SE-ResNext50 model with different augmentations, LR schedule, etc. along with stochastic weight averaging during the end of training. This was submitted with the EfficientNet-B3a and the EfficientNet-B7 as an ensemble, and this got Public LB: 0.897, Private LB: 0.901 (potential gold territory), but this was not selected unfortunately. However, we are grateful that we even managed to make a 1135 rank jump!</p>
<p><strong>A few of the other things we tried:</strong><br>
- Tried Bi-tempered logistic loss, observed no CV improvement<br>
- Tried progressive label correction, observed no CV improvement<br>
- Tried pseudolabeling on the test set, it was a last minute idea and public LB was 0.139 so likely an error in implementation</p>
<p><strong>Reflections:</strong><br>
- This competition was quite interesting, even though the dataset was quite messy and filled with errors<br>
- Even with many errors, the model training was robust, leading to decent performance on the CV and private leaderboard<br>
- While we all started out quite enthusiastic regarding this competition, other tasks/duties took higher priority for many of us, and only a couple of us dedicated significant time to it. I wonder what the situation would be if all team members could dedicate more time to the competition. Would we reach an even higher place? Or would we overfit to the leaderboard? </p>
<p>Thanks to my great teammates, especially <a href="https://www.kaggle.com/tanulsingh077" target="_blank">@tanulsingh077</a> and <a href="https://www.kaggle.com/abhishek" target="_blank">@abhishek</a>!</p> |
Cassava Leaf Disease Classification | Diversity is all we 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: Cassava Leaf Disease Classification
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Congrats to all. Learned a lot from this community.</p>
<p>I am really happy to team up with my teammates <a href="https://www.kaggle.com/ludovick" target="_blank">@ludovick</a> and <a href="https://www.kaggle.com/tonyxu" target="_blank">@tonyxu</a> who have strong engineering capabilities and are thus able to put any ideas into practice. Our final solutions consist of 4 models. Unfortunately, same as most teams, we missed selecting a sub that can beat 3rd place in Private LB. We three have totally different training processes, which I think helps us to stay gold zone on both public LB and private LB. The diversity makes us win.</p>
<h1>Models</h1>
<ul>
<li>Shirok’s effb5_ns with 8xTTA</li>
<li>toxu’s vit_base_patch16_384 with 8xTTA</li>
<li>Yimin’s effb5_ns with 8xTTA</li>
<li>Yimin’s seresnext50 with no TTA</li>
<li>Same weight for ensemble.</li>
<li>Without any one of these models, we cannot win.</li>
<li>The oof corrcoef is as below:<br>
[[1. , 0.79848116, 0.81904038, 0.81931724],<br>
[0.79848116, 1. , 0.80287945, 0.79185962],<br>
[0.81904038, 0.80287945, 1. , 0.82176191],<br>
[0.81931724, 0.79185962, 0.82176191, 1. ]]</li>
</ul>
<h1>Diversity</h1>
<h2>Teammates’ part</h2>
<p>As I know, Shirok used tf TPU for training b5, and toxu used skd softlabel for vit. Welcome them to add more details at this part if would like.</p>
<h2>In my part</h2>
<h3>Dataset</h3>
<ul>
<li>2019+2020 dataset</li>
<li>Removed some duplicates searched by <a href="https://www.kaggle.com/zzy990106/duplicate-images-in-two-competitions" target="_blank">https://www.kaggle.com/zzy990106/duplicate-images-in-two-competitions</a> and <a href="https://www.kaggle.com/graf10a/cldc-image-duplicates-with-dbscan" target="_blank">https://www.kaggle.com/graf10a/cldc-image-duplicates-with-dbscan</a>. Thanks again for sharing useful kernels that can be used anywhere.</li>
<li>Tried Pseudo Label on 2019 test data and extraimage data (removed duplicates). Got better CV but worse LB. Probably because of data leak. I used the avg. probs of 5 folds, which may bring in leak info. between folds. Due to time limit, never chose it after.</li>
<li>Tried self knowledge distillation softlabel. Improved 0.003 on CV but decreased 0.001-0.002 on LB. Did not choose it as the final sub. -0.0015 around compared with hard label on private LB.</li>
<li>Hard Label</li>
<li>Stratified 5 folds</li>
<li>Batch size 32</li>
<li>Image size 512 x 512</li>
</ul>
<h3>Training AUG</h3>
<p>Random Rotate<br>
ShiftScaleRotate<br>
HueSaturationValue<br>
RandomBrightnessContrast<br>
Flip, transpose<br>
GuaussNoise<br>
Blur<br>
Distortion<br>
Cutout</p>
<h3>Loss</h3>
<p>Bi-tempered</p>
<h3>TTA</h3>
<p>You must be curious about why I did not use TTA for se50 but used TTA for b5. I was stuck at 0.900 (se50), 0.902 (b5), and 0.902 (ensembles using both 8xTTA) before I checked out this <a href="https://www.kaggle.com/japandata509/ensemble-resnext50-32x4d-efficientnet-0-903" target="_blank">notebook</a>. I was also curious about why Kaito did not use TTA for a model but used it for another model. Then I tried to inference my oof with and without various TTAs. And I found that TTA always decreased my cv score of se50 and increased the cv score of b5. The same situation happened on LB. Here is my previous <a href="https://www.kaggle.com/c/cassava-leaf-disease-classification/discussion/214559" target="_blank">discussion</a> regarding this. After using the similar strategy, I climbed up to 0.905 on LB. So, I just trusted the cv and LB at that moment, although the private LB shows the contrary result regarding se50. But our ensembles took almost 8 hrs to run submit, so it actually did not allow another model with TTA. It was the fate. Anyway, I was probably wrong with insights about TTA at my that discussion.</p>
<h2>ensemble</h2>
<p>My se50+b5 scored 0.905 on public LB, and Shirok’s b5 + toxu’s vit scored 0.906. After merge, we got 0.908. After finetuning each single model, we finally got 0.910 which stand 2nd place on public LB. Our ensemble is somehow robust. It keeps scoring 0.901-0.902 on private LB where the gold zone is. I attribute it to the diversity of our models (to be proved).</p>
<h1>Trust CV or LB?</h1>
<p>Unlike the Riiid, I have totally no idea about this comp. The dataset (both train and test) is noisy, and I do not think that test data split is balanced. Our CV is range from 0.905-0.906 on 2020 dataset. It is not aligned with LB for us. Anyone can share your scores may help to determine. Anyway, trusting cv is always the better way. Make sure there is no leak in your cv.</p>
<h1>Additional</h1>
<p>The Class Activation Map (CAM) can somewhat help to track your model performance. Introduced by toxu, inspired by the winner in cvpr2020-plant-pathology. I used it for error analysis to determine if the model cares about the right position of the image. I made a simple <a href="https://www.kaggle.com/woshifym/cld-class-activation-mapping-cam-wip" target="_blank">notebook</a> to show how it works. Hope you would enjoy it.</p>
<h1>Others</h1>
<p>Forgive my messy formatting.<br>
Will update if I think of something missing…</p> |
Cassava Leaf Disease Classification | 18th 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: Cassava Leaf Disease Classification
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>I would like to give thanks to all participants who shared their wealth of knowledge and wisdom for this competition thru notebook and discussion sharing.</p>
<p>My submitted solution consist of simple average of 3 models namely: 5 folds gluon_seresnext101_32x4d, tf_efficientnet_b4_ns and seresnext50_32x4d. </p>
<p>The following are the final scores of my model:</p>
<p>gluon_seresnext101_32x4d<br>
CV: 0.9012; Public LB: 0.9011; Private LB: 0.8993</p>
<p>tf_efficientnet_b4_ns<br>
CV: 0.9013; Public LB: 0.9011; Private LB: 0.8970</p>
<p>seresnext50_32x4d<br>
CV: 0.9007; Public LB: 0.8978, Private LB: 0.8987</p>
<p>Simple Average<br>
Public LB: 0.905; Private LB: 0.9013</p>
<p>Training Methodology<br>
The parameters used during stages of model training:</p>
<p>1st stage<br>
image size: 320x320 or 384x384<br>
10 epochs<br>
learning rate: 1e-4<br>
train set: 2019 + 2020 data<br>
validation set: 2020<br>
scheduler: GradualWarmupScheduler<br>
criterion: TaylorCrossEntropyLoss with label smoothing=0.2<br>
optimizer: SAM + Adam<br>
augmentation: RandomResizedCrop, Transpose, HorizontalFlip, VerticalFlip, ShiftScaleRotate, Cutout</p>
<p>2nd stage<br>
image size: 512x512<br>
25-40 epochs<br>
learning rate: 1e-4<br>
train set: 2020 data<br>
validation set: 2020 data<br>
scheduler: GradualWarmupScheduler<br>
criterion: Combo Loss (see notebook in detail)<br>
optimizer: SAM + AdamP<br>
augmentation: RandomResizedCrop, Transpose, HorizontalFlip, VerticalFlip, ShiftScaleRotate, Cutout + Cutmix</p>
<p>Finetune stage<br>
5 epochs<br>
learning rate: 1e-5<br>
train set: 2020 data<br>
validation set: 2020 data<br>
scheduler: no scheduler<br>
criterion: Combo Loss (see notebook in detail)<br>
optimizer: SAM + AdamP<br>
augmentation: hard albumentation-based augmentations</p>
<p>You may check this notebook for reference:<br>
<a href="https://www.kaggle.com/projdev/base-notebook-cassava-leaf-disease-classification" target="_blank">https://www.kaggle.com/projdev/base-notebook-cassava-leaf-disease-classification</a></p>
<p>I believe that the combination of SAM + AdamP optimizer provides the model robustness in terms of prediction generalization and the key to survive in competition shake-up.</p>
<p>A possible improvement for my model score is using SAM + SGDP and add FocalCosineLoss in Combo loss and find the right learning rate as it converges quickly. Unfortunately, I have no available GPU resources to re-train my model as SAM optimizer double the training time and I spent too much time on finding the right parameters for my model training.</p>
<p>Once again, thank you very much.</p> |
Cassava Leaf Disease Classification | 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: Cassava Leaf Disease Classification
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thank you for all kagglers and organizers for this competition.I learned a lot from the competition.</p>
<h1>Data</h1>
<ul>
<li>training and validating on 2020 data using stratified 5-fold CV</li>
</ul>
<h1>Model</h1>
<ul>
<li>EfficientNet B6 with Noisy Student</li>
<li>ResNeSt50</li>
<li>Vision Transformer(base patch16)</li>
</ul>
<p>my best single model is EfficientNet B6 , it can get 0.903 in public lb and 0.8946 in private lb.</p>
<h1>Augmentation</h1>
<ul>
<li>HorizontalFlip, Transpose, VerticalFlip</li>
<li>HueSaturationValue</li>
<li>CoarseDropout</li>
<li>RandomBrightnessContrast</li>
<li>ShiftScaleRotate</li>
<li>RGBShift</li>
<li>Cutmix</li>
<li>Fmix</li>
<li>Snapmix</li>
<li>ISDA(implicit semantic data augmentation)<br>
<a href="https://arxiv.org/abs/2007.10538" target="_blank">https://arxiv.org/abs/2007.10538</a></li>
</ul>
<p>The combination of cutmix and fmix can boost the cv,but the snapmix makes the training unstable, maybe some hyperparameters need careful tuning.I had not try the ISDA because of the time, but I think it may bring a suprising effect.</p>
<h1>Loss</h1>
<ul>
<li>LabelSmoothing</li>
<li>FocalLoss</li>
<li>FocalCosineLoss</li>
<li>BiTemperedLoss</li>
<li>ClassBlancedLoss(only training)<br>
<a href="https://arxiv.org/abs/1901.05555" target="_blank">https://arxiv.org/abs/1901.05555</a></li>
</ul>
<p>LabelSmoothing(0.1 or 0.2) gave the best performance relative to other loss functions</p>
<h1>Training</h1>
<ul>
<li>Optimizer:Adam, AdamW, AdamP, Ranger</li>
<li>lr_scheduler:CosineAnnealingWarmRestarts</li>
</ul>
<h1>Inference</h1>
<ul>
<li>8xTTA(transpose, flip)</li>
<li>ensemble(just average)</li>
</ul>
<p>The most important thing I learned in this competition is never give up, because no one knows the result until the end.<br>
Finally, I hope everyone can get the gold medal in the next competition. Thanks my leader YuBo and my girl friend MingJun. </p> |
Cassava Leaf Disease Classification | [?th] The lost 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: Cassava Leaf Disease Classification
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h1>The lost solution</h1>
<p>Hello! Time to share our solution for this competition. Why did we call it lost? Because it's 900+ place on the noisy public LB and… and we don't know what to expect from the private part. We didn't know our private place while writing this report. Our team just wants to share an example of advanced solution based on training with denoised data and huge ensemble method. So, if we landed low on the private LB when you're reading this, it means that we've got a noisy private set and our ideas haven't worked. Otherwise, if we're high enough on the LB it means that the private part is clear and we handled noise successfully. Since we're going all-in and taking two denoised solutions as the final submissions, we wanna believe that private data won't contain as much noise as the public set does. Let's review our solution by steps.</p>
<p>Let's start from the most interesting part.</p>
<h2>Knowledge distillation</h2>
<p>We did a really soft knowledge distillation. We hadn't time to do a lot of experiments, so we had only one take to relable the dataset. We explored the forum and found out that there are at least 500 diseased images which are labeled as healthy. Other types of mistakes weren't frequently mentioned. So we decided to make knowledge distillation soft targets only for 500 samples. We trained 5 folds of SWSL ResNeXt 101 8D and predicted labels for all images from each validation part and for each label. Then we saved the predictions and confidences for each image and chose a threshold for confidence, which was used to find ~500 samples where extremely confident predictions didn't match ground truth labels. Then we trained Efficient Net B4 with obtained labels and got the CV boost from 0.899 to 0.915. Relabeled data was used in validation part as well.</p>
<h2>External data</h2>
<h5>2019 data</h5>
<p>We used <a href="https://www.kaggle.com/tahsin/cassava-leaf-disease-merged" target="_blank">2019 data with removed duplicates</a> for training. We used it only for training and didn't put it in the validation part. We've also applied soft relabling for it.</p>
<h5>Mendeley Leaves</h5>
<p>We also used <a href="https://www.kaggle.com/nroman/mendeley-leaves" target="_blank">Mendeley Leaves</a> for training. This dataset contains images of other plants. The dataset is not fully labeled. The first part of the all images are labeled just as healthy and the rest of them are labeled just as diseased. So the second part had to be pseudo-labeled to be able to use it for training. We used 5 folds of SWSL ResNeXt 101 8D for this task. We predicted labels for each diseased image and checked model confidence for each one. I used a 0.55 confidence threshold - the same was calculated for relabeling ~500 samples in the source train set. (It’s NOT ranged from 0 to 1, it has much more amplitude including negative values.). Finally, we get 2767 / 4334 samples, including the healthy ones. The external data images weren’t used in the validation and placed only in the training part.</p>
<h2>TTA</h2>
<p>We used simple technique for our TTA: average of the default image and horizontally flipped image. There are two reasons of selecting such a small number of transforms for TTA: time limit - well-structured ensemble usually performs better than TTA, double TTA is the most stable variant in this competition according to our experiments - averaged and weighted 4x or 16x TTA aren't that good to be considered for our solution, LB scores might differ with them in range [-0.007, +0.007]. </p>
<h2>Augmetations</h2>
<p>Successful:</p>
<ul>
<li>Horizontal Flip</li>
<li>Vertical Flip</li>
<li>Blur</li>
<li>360 rotates </li>
<li>RandomBrigtnessContrast </li>
<li>ShiftScaleRotate</li>
<li>HueSaturationValue</li>
<li>CutMix</li>
<li>MixUp</li>
<li>FMix </li>
</ul>
<p>25% probability for each of past three augmentations.</p>
<p>Unsuccessful:</p>
<ul>
<li>ElasticTransform</li>
<li>Grid Distortion</li>
<li>RandomSunFlare</li>
<li>GaussNoise</li>
<li>Coarse dropout</li>
<li>Optical Distortion</li>
</ul>
<p>During warm up stage only horizontal flip was used.</p>
<h2>Training</h2>
<ul>
<li>optimizer - Ranger</li>
<li>learning rate - 0.003</li>
<li>epoch - 30</li>
<li>warm up epochs - 3</li>
<li>early stopping - 8</li>
<li>Loss Function - Cross Entropy loss with label smoothing (0.2 smoothing before using knowledge distillation and 0.1 after it)</li>
<li>Progressive image size, start_size=256, final_size=512, size_step=32. Size starts increasing after the warm up stage finishes.</li>
<li>pretrained - True</li>
<li>Frozen BatchNorm layers</li>
<li>scheduler - CosineBatchDecayScheduler with gradual warm up (custom impelementation)</li>
</ul>
<p>Initially, we tried to impelement Cosine Decay Scheduler that steps every batch and has wide range of customization ways, but finally we created the custom scheduler we used here. Here is the code and a plotted learning rate:</p>
<pre><code>import math
from torch.optim.lr_scheduler import _LRScheduler
class CosineBatchDecayScheduler(_LRScheduler):
"""
Custom scheduler with calculating learning rate according batchsize
based on Cosine Decay scheduler. Designed to use scheduler.step() every batch.
"""
def __init__(self, optimizer, steps, epochs, batchsize=128, decay=128, startepoch=1, minlr=1e-8, last_epoch=-1):
"""
Args:
optimizer (torch.optim.Optimizer): PyTorch Optimizer
steps (int): total number of steps
epochs (int): total number of epochs
batchsize (int): current training batchsize. Default: 128
decay (int): batchsize based on which the learning rate will be calculated. Default: 128
startepoch (int): number of epoch when the scheduler turns on. Default: 1
minlr (float): the lower threshold of learning rate. Default: 1e-8
last_epoch (int): The index of last epoch. Default: -1.
"""
decay = decay * math.sqrt(batchsize)
self.stepsize = batchsize / decay
self.startstep = steps / epochs * (startepoch - 1) * self.stepsize
self.minlr = minlr
self.steps = steps
self.stepnum = 0
super(CosineBatchDecayScheduler, self).__init__(optimizer, last_epoch)
def get_lr(self):
"""Formula for calculating the learning rate."""
self.stepnum += self.stepsize
if self.stepnum < self.startstep:
return [baselr for baselr in self.base_lrs]
return [max(self.minlr, 1/2 * (1 + math.cos(self.stepnum * math.pi / self.steps)) * self.optimizer.param_groups[0]['lr']) for t in range(len(self.base_lrs))]
</code></pre>
<p><img src="https://i.ibb.co/bBCtNtB/image.png" alt=""></p>
<p>Mixed precision training with gradient accumulation (iters_to_accumulate=8) ==> big boost on CV</p>
<h2>Models</h2>
<ul>
<li>SWSL ResNeXt 101 8D</li>
<li>SWSL ResNeXt 50</li>
<li>Efficient Net B4</li>
<li>Efficient Net B4 NS</li>
<li>Inception V4</li>
<li>DenseNet 161</li>
</ul>
<p>Here are the table representing perfomance of these and some others models:<br>
<img src="https://i.ibb.co/XpFT5VP/table.jpg" alt=""></p>
<h2>Final ensembles</h2>
<p>We submitted two different ensemble approaches with the same 6 models (5 folds each one). </p>
<p>1) Simple Averaging Ensemble<br>
<strong>2019 Private LB: 0.92712; 2020 Public LB: 0.898; 2020 Private LB: 0.896</strong></p>
<p>2) MaxProb Ensemble<br>
Max Probability (or Max Confidence) ensemble allows us to choose the dominating model in the prediction process. In this case, if several models predict different labels, we take the prediction from a model with the biggest confidence.<br>
<strong>2019 Private LB: 0.93197; 2020 Public LB: 0.893; 2020 Private LB: 0.897</strong></p>
<p>Here is the scheme of our ensembles:<br>
<img src="https://i.ibb.co/SBZjRyW/image.png" alt=""></p>
<p>You can find our full report (33 pages) about this competition <a href="https://docs.google.com/document/d/1TNTfrDrhYSAAgL_L6gIX5stw1Lfm76XJ-QY7yS4UfTc/edit?usp=sharing" target="_blank">here</a>. Each step, score and submit are described there.</p>
<p>Thank you to my team, the organizers and all the participants! We had a great time and learned a lot. In a few days, we will publish our code, but in the meantime, you can check the base version of <a href="https://www.kaggle.com/vadimtimakin/fast-automated-clean-pytorch-pipeline-train" target="_blank">my pipeline</a>. See you in the next competitions!</p>
<p><em>Don't deal with the noise…</em></p> |
Cassava Leaf Disease Classification | Top %8 solution - (with unselected top %4) | 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: Cassava Leaf Disease Classification
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Hi everyone, </p>
<p>First of all, congrats to all the winners. It is a fantastic achievement. Also thanks to Kaggle and the competition host. This was quite an interesting challenge with multiple aspects. The noise and the class imbalance were hard to tackle. </p>
<p>Our team consists of two people (me and my great teammate <a href="https://www.kaggle.com/emirkocak" target="_blank">@emirkocak</a>). We finished the competition in the top %8. But like many other teams, we had a higher private LB submission which we did not select :) Here, we will summarize both of our solutions:</p>
<p><strong>Our final submission (Top %8 - private: 0.8984):</strong></p>
<p>We started this competition by visualizing and exploring the data. At first glance, it was somewhat confusing because of the wrong labels. With this in mind, we passed to the modeling stage.</p>
<p>To set up a baseline score, we used this <a href="https://www.kaggle.com/yasufuminakama/cassava-resnext50-32x4d-starter-training/" target="_blank">notebook</a> (thanks a lot <a href="https://www.kaggle.com/yasufuminakama" target="_blank">@yasufuminakama</a> 🙏) and used the following augmentations. Here <code>HueSaturationValue</code> and <code>RandomBrightnessContrast</code> was optional. We experimented with the different versions of them.</p>
<pre><code>def get_train_transforms():
return albumentations.Compose([
# Optionally only resize
# albumentations.Resize(512, 512),
albumentations.RandomResizedCrop(
512, 512,
scale=(0.6, 1.0), ratio=(3/5, 5/3)),
albumentations.Transpose(),
albumentations.HorizontalFlip(),
albumentations.VerticalFlip(),
albumentations.ShiftScaleRotate(),
albumentations.HueSaturationValue(
hue_shift_limit=0.2,
sat_shift_limit=0.2,
val_shift_limit=0.2,
p=0.5
),
albumentations.RandomBrightnessContrast(
brightness_limit=(-0.1, 0.1),
contrast_limit=(-0.1, 0.1),
p=0.5
),
albumentations.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]),
albumentations.Cutout(num_holes=8, max_h_size=32, max_w_size=32, fill_value=0, p=0.5),
ToTensorV2(),
])
</code></pre>
<p><strong>Model Details:</strong></p>
<ul>
<li>Backbone: resnext50, efficient_net_b3, ViT</li>
<li>2019 data</li>
<li>Image size: <ul>
<li>(resnext50, efficient_net_b3): 512</li>
<li>(ViT): 384</li></ul></li>
<li>Folds: 5</li>
<li>Epoch: 10 (for each fold)</li>
<li>Optimizer: Adam(lr=0.001)</li>
<li>Scheduler: Cosine + Warmup (1 warmup + 9 cosine annealing)</li>
<li>TTA: 5 for resnext50 and ViT, 8 for the efficient_net_b3<ul>
<li>Here we applied both light and heavy tta. Heavy one performed better.</li></ul></li>
</ul>
<p><strong>Top %4 submission: (private: 0.8993)</strong></p>
<p>This submission looks pretty much the same as above but a little bit lighter. I guess "The Less is More" philosophy was correct here :)</p>
<ul>
<li>Backbone: resnext50, efficient_net_b1</li>
<li>Image size: 512</li>
<li>Folds: 5</li>
<li>Other parameters are the same</li>
<li>TTA: 5<ul>
<li>Opposite to the model above, here light TTA worked much better (only transpose and flip).</li></ul></li>
</ul>
<p><strong>Things did not work:</strong></p>
<ul>
<li>SnapMix and CutMix</li>
<li>Pseudo Labelling</li>
</ul>
<p>It was funny and challenging competition for both of us. We learned a lot. Congratulations to the top teams again. ✌️</p>
<p>Sinan & Emir</p> |
Riiid Answer Correctness Prediction | 21st Place Solution - Ensemble of 3 Saint++ Models | 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: Riiid Answer Correctness Prediction
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Hi all!<br>
After seeing everyone share their solution we have decided to also share ours in the same spirit.</p>
<p>We ran a modified SAINT+ that <strong>included lectures, tags and a couple of aggregate features.</strong></p>
<p>All our code is available on github ( <a href="https://github.com/gautierdag/riiid" target="_blank">https://github.com/gautierdag/riiid</a> ). We used Pytorch/Pytorch Lightning and Hydra.</p>
<p>Our single model public LB was 0.808, and we were able to push that to LB 0.810 (Final LB 0.813) through ensembling.</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F583548%2Fa19776338ca1ba57bd1260bf8e0ec678%2Friiid_model.png?generation=1610188697948445&alt=media" alt=""></p>
<h2>Modifications to original SAINT:</h2>
<ul>
<li><p><strong>Lectures</strong>: lectures were included and had a special trainable embedding vector instead of the answer embedding. The loss was not masked for lecture steps. We tested both with and without, and the difference wasn't crazy. The big benefit they offered was that they made everything much simpler to handle since we did not need to filter anything.</p></li>
<li><p><strong>Tags</strong>: Since questions had a maximum of six tags, we passed sequences of length 6 to a tag embedding layer and summed the output. Therefore our tag embeddings were learned for each tag but then sum across to obtain an embedding for all the tags in a question/lecture. The padding simply returned a 0 vector.</p></li>
<li><p><strong>Agg Feats</strong>: This is what gave us a healthy boost of 0.002 on public LB. By including 12 aggregate features in the decoder we were able to use some of our learnings in previous LGBM implementations. </p></li>
</ul>
<h4>Agg feats</h4>
<p>We used the following aggregate features:</p>
<ul>
<li>attempts: number of previous attempts on current question (clamped to 5 and normalized to 1)</li>
<li>mean_content_mean: average of all the average question accuracy (population wise) seen until this step by the user</li>
<li>mean_user_mean: average of user's accuracy until this step </li>
<li>parts_mean: seven dimensional (the average of the user's accuracy on each part)</li>
<li>m_user_session_mean: the average accuracy in the current user's session </li>
<li>session_number: the current session number (how many sessions up till now)</li>
</ul>
<p>Note: session is just a way of dividing up the questions if a difference in time between questions is greater than two hours.</p>
<h4>Float vs Categorical</h4>
<p>We switched to use a float representation of answers in the last few days. This seemed to have little effect on our LB auc unfortunately, but had an effect locally. The idea was that since we auto-regress on answers we would propagate the uncertainty that the model displayed into future predictions.</p>
<p>All aggs and time features are floats that are ran through a linear layer (without bias). They were all normalized to either [-1,1] or [0, 1].</p>
<p>All other embeddings are categorical.</p>
<h2>Training:</h2>
<p>What made a <strong>big</strong> difference early on was our sampling methodology. Unlike most approaches in public kernels, we did not take a user-centric approach to sample our training examples. Instead, we simply sampled based on row_id and would load in the previous window_size history for every row.</p>
<p>So for instance if we sampled row 55. Then we would find the user id that row 55 corresponds to, and load in their history up until that row. The size of the window would then be the min(window_size, len(history_until_row_55)).</p>
<p>We used Adam with 0.001 learning rate, early stopping and lr decay based on val_auc during training.</p>
<h2>Validation</h2>
<p>For validation, we kept a holdout set of 2.5mil (like the test set) and generated randomly with a certain proportion guaranteed of new users. We used only 250,000 rows to actually validate on during training.</p>
<p>For every row in validation, we would pick a random number of inference steps between 1 and 10. We would then infer over these steps, not allowing the model to see the true answers and having to use its own.</p>
<h2>Inference</h2>
<p>During inference, when predicting multiple questions for a single user, we fed back the previous prediction of our model as answers in the model. This auto-regression was helpful in propagating uncertainty and helped the auc.</p>
<p>I saw a writeup that said that this was not possible to do because it constrains you to batch size = 1. That is wrong, you can actually do this for a whole batch in parallel and it's a little tricky with indexes but it is doable. You simply have to keep track of each sequence lengths and how many steps you are predicting for each.</p>
<p>Unfortunately since some of our aggs are also based on user answers, these do not get updated until the next batch because they are calculated on CPU and not updated in that inference loop.</p>
<h2>Parameters</h2>
<p>We ensemble three models.</p>
<p>First model:</p>
<ul>
<li>64 emb_dim</li>
<li>4/6 encoder/decoder layers</li>
<li>256 feed foward in Transformer</li>
<li>4 Heads</li>
<li>100 window size</li>
</ul>
<p>Second model:</p>
<ul>
<li>64 emb_dim</li>
<li>4/6 encoder/decoder layers</li>
<li>256 feed foward in Transformer</li>
<li>4 Heads</li>
<li>200 window size (expanded by finetuning on 200)</li>
</ul>
<p>Third model:</p>
<ul>
<li>256 emb_dim</li>
<li>2/2 encoder/decoder layers</li>
<li>512 feed foward in Transformer</li>
<li>4 Heads</li>
<li>256 window size</li>
</ul>
<h2>Hardware</h2>
<p>We rented three machines but we could have probably gotten farther with using a larger single machine:</p>
<ul>
<li>3 X 1 Tesla V100(16gb VRAM)</li>
</ul>
<h2>Other things we tried</h2>
<ul>
<li>Noam lr schedule (super slow to converge)</li>
<li>Linear attention / Reformer / Linformer (spent way to much time on this)</li>
<li>Local Attention</li>
<li>Additional Aggs in output layer and a myriad of other aggs</li>
<li>Concatenating Embeds instead of summing</li>
<li>A lot of different configurations of num_layers / dims / .. etc</li>
<li>Custom attention based on bundle </li>
<li>Ensembling with LGBM</li>
<li>Predicting time taken to answer question as well as answer in Loss</li>
<li>K Beam decoding (predicting in parallel K possible paths of answers and taking the one that maximized joint probability of sequence)</li>
<li>Running average of agg features (different windows or averaging over time)</li>
<li>Causal 1D convolutions before the Transformer</li>
<li>Increasing window size during training</li>
<li>…</li>
</ul>
<p>Finally, thanks to <a href="https://www.kaggle.com/eeeedev" target="_blank">@eeeedev</a> for the adventure!</p> |
Cassava Leaf Disease Classification | 123rd place (Silver) 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: Cassava Leaf Disease Classification
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Hey Dear Kagglers :)</p>
<p>First of all, congratulations to all winners and participants!<br>
And many thanks to all contributors for their amazing kernels and topics!</p>
<p>Wanted to put my 2 cents in - so you can find a brief overview of my solution below:</p>
<h3>General approach</h3>
<p>I noticed the CV results was quite unstable overall - I was observing very significant discrepancies in validation and LB scores between the different folds of the same models (mostly because it is not easy to stratify the noise (probably :) ) ). When blending 2-3 best epochs from each fold it was kind of stabilizing - but it was not a very efficient way to do so in my opinion (especially considering the submission time limitations of the code competitions). I discovered though, I was able to produce better/equivalent results by blending the 3-4 best epochs of a model trained on the full set (stabilizing the models "horizontally" in a way). This also allowed me to include way more (diverse) models in my submissions. <br>
And so I did:</p>
<ul>
<li>Final models were trained on the FULL data.</li>
<li>Still used CV for validation/evaluation purposes only.</li>
</ul>
<p>Was this the best approach? Well on one side I perfectly survived the shakeup. On the other - I failed to identify my best submission (which would have been in the money/gold medal zone: <a href="https://www.kaggle.com/gpamoukoff/private-lb-0-902-blend-effnet-b3-b4-vit-resnext50)" target="_blank">https://www.kaggle.com/gpamoukoff/private-lb-0-902-blend-effnet-b3-b4-vit-resnext50)</a>.</p>
<h3>Models</h3>
<p>Trained with the aim to be as diverse as possible:</p>
<ul>
<li>effnet b3/b4, vit, xception, resnext50 architectures</li>
<li>Label Smoothing</li>
<li>Various loss functions: CE, Symmetric CE, Taylor CE</li>
<li>Various schedulers: Gradual Warmup/CosineAnnealingWarmRestarts</li>
<li>Augmentation: played mostly around crops/cutmix apart from the standard techniques.</li>
<li>Data:<ul>
<li>only 2020</li>
<li>pretrain on 2019, train on 2020</li>
<li>train on both (one pass)</li></ul></li>
</ul>
<h3>Ensemble:</h3>
<p>Hierarchical blend:</p>
<ul>
<li>Blended different epoch/best of kind models first</li>
<li>Then blended the already blended “super” models</li>
<li>Used CV to optimise the weights</li>
</ul>
<p>In short - could have been way better. Next time. Keep walking…</p> |
Cassava Leaf Disease Classification | 3rd 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: Cassava Leaf Disease Classification
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h2>Acknowledgements</h2>
<p>Thanks to Kaggle and hosts for holding this competition.<br>
This is my first gold medal and I finally became Competition Master :)</p>
<h1>Summary</h1>
<p>[update 2021.03.02]<br>
I made a mistake, vit_base_patch16_384's final layer is not multi-drop but simple linear.<br>
I found a bug during the verification process.</p>
<p>My final submission is ensemble of three ViT models; summarized below.<br>
<a href="https://postimg.cc/sQddZFXM" target="_blank"><img src="https://i.postimg.cc/HsjCzjjw/summary.png" alt="summary.png"></a></p>
<h1>Model</h1>
<h3>vit_base_patch16_384</h3>
<ul>
<li>img_size = 384 x 384</li>
<li>5x TTA </li>
<li>Public : 0.9059</li>
<li>Private : 0.9028</li>
</ul>
<p>This is my best single model</p>
<h3>vit_base_patch16_224 - A</h3>
<ul>
<li>img_size = 448 x 448</li>
<li>5x TTA </li>
<li>weight calculation pattern A</li>
<li>Public : 0.9030</li>
<li>Private : 0.8990</li>
</ul>
<p>To adapt vit_base_patch_224(expected image size is 224 x 224) for 448 x 448 image,<br>
after augmentation, divide it into four parts and input each image into the model. And then, they are adapted the weighted average using calculated weights at attention layer, and finally output prediction using Multi-Dropout Linear.<br>
</p>
<h3>vit_base_patch16_224 - B</h3>
<ul>
<li>img_size = 448 x 448</li>
<li>5x TTA </li>
<li>weight calculation pattern B</li>
<li>label smoothing, alpha=0.01</li>
<li>Public : 0.9034</li>
<li>Private : 0.8952<br>
</li>
</ul>
<h3>Weighted Averaging</h3>
<ul>
<li>Public : 0.9075</li>
<li>Private : 0.9028</li>
</ul>
<p>Tried a bunch of pretrained models but ViT model works the best at Public LB. <br>
The bigger the image size, the better cv score, but I thought it is overfitting. So I dropped efficient-net and se-resnext, etc with large image size in the early stages.</p>
<h2>Some Settings</h2>
<ul>
<li>5fold StratifiedKFold</li>
<li>Using 2020 & 2019 data</li>
</ul>
<h3>Augmentation</h3>
<p>I tried some types of augmentations, but finally adopted simple one.<br>
The reason why is the same of chose not large size image, overfitting.</p>
<pre><code>if aug_ver == "base":
return Compose([
RandomResizedCrop(img_size, img_size),
Transpose(p=0.5),
HorizontalFlip(p=0.5),
VerticalFlip(p=0.5),
ShiftScaleRotate(p=0.5),
Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
ToTensorV2(),
])
</code></pre>
<h3>LR Scheduler</h3>
<ul>
<li>LambdaLR</li>
</ul>
<pre><code>self.scheduler = LambdaLR(
self.optimizer, lr_lambda=lambda epoch: 1.0 / (1.0 + epoch)
)
</code></pre>
<p><img src="https://i.postimg.cc/Twv8mmCW/2021-02-21-9-29-45.png" alt="lr.png"></p>
<h3>Scores</h3>
<p><img src="https://i.postimg.cc/hvhFzmdT/2021-02-21-23-00-39.png" alt="scores.png"></p>
<p>training code<br>
<a href="https://github.com/TomYanabe/Cassava-Leaf-Disease-Classification" target="_blank">https://github.com/TomYanabe/Cassava-Leaf-Disease-Classification</a></p>
<p>Thank you for reading :)</p> |
Cassava Leaf Disease Classification | [Public 272nd / Private 37th] 1 week 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: Cassava Leaf Disease Classification
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>First of all, congrats to all the participants who got medals, and thanks to the host and kaggle team.</p>
<p>There is little difference in the scores of most participants. I'm really looking forward to the 1st place solution :)</p>
<h3>Brief Summary</h3>
<ul>
<li>training 10 image classification models and ensembling them by 1D-CNN, 2D-CNN, and weight optimization</li>
<li>using merged dataset(2019 + 2020) for training but only 2020 for validation</li>
<li>using Cross Entropy Loss with label Smoothing (alpha=0.3)</li>
<li>as the result, simple averaging(I didn't select as final submission) is better than stacking 😇<ul>
<li>stacking(Public: 0.9014, Private: 0.9008): <a href="https://www.kaggle.com/ttahara/infer-cassava-ens10" target="_blank">https://www.kaggle.com/ttahara/infer-cassava-ens10</a></li>
<li>averaging(Public: 0.9018, Private 0.9014): <a href="https://www.kaggle.com/ttahara/infer-cassava-ens09" target="_blank">https://www.kaggle.com/ttahara/infer-cassava-ens09</a></li></ul></li>
</ul>
<h3>Details</h3>
<h4>Data</h4>
<p>I used <a href="https://www.kaggle.com/tahsin/cassava-leaf-disease-merged" target="_blank">publicly shared merged training dataset(2019 + 2020)</a>. Thank you <a href="https://www.kaggle.com/tahsin" target="_blank">@tahsin</a> for sharing it.</p>
<h4>Image Classification Models</h4>
<p>I used the following 10 models provided in <a href="https://github.com/rwightman/pytorch-image-models" target="_blank">timm</a>. </p>
<ul>
<li><p>small models: ResNet50D, ResNeXt50_32x4d, ECA-ResNet50D, ResNeSt50_fast_1s4x24d, RegNetY032</p></li>
<li><p>big models: ResNet100D, ResNeXt101_32x4d, ECA-ResNet101D, ResNeSt101, RegNetY080 </p></li>
</ul>
<h4>Training</h4>
<h5>cross validation</h5>
<ul>
<li>spliting merged training dataset by Stratified K-fold manner(K=5)</li>
<li>using 2019 and 2020 data for training but only 2020 for validation</li>
</ul>
<h5>data augmentation</h5>
<p>Transpose -> HorizontalFlip -> VerticalFlip -> <br>
ShiftScaleRotate -> RandomResizedCrop -><br>
HueSaturationValue -> RandomBrightnessContrast -> <br>
OneOf(RandomErase, CoarseDropout, Cutout) -><br>
Normalize -> ToTensorV2</p>
<h5>other settings</h5>
<ul>
<li>image size: 512x512x3</li>
<li>max epoch : 10</li>
<li>batch size: 64(small models), 32(big models)</li>
<li>loss: CrossEntropy with LabelSmoothing<ul>
<li>smoothing alpha: <strong>0.3</strong></li></ul></li>
<li>optimizer: AdamW<ul>
<li>weight decay: 1.0e-02</li>
<li>learning rate: 5e-04(small models), 2.5e-04(big models)</li></ul></li>
<li>scheduler: CosineAnnealingWarmRestarts<ul>
<li>T_0: 10</li>
<li>T_mult: 1</li></ul></li>
</ul>
<h5>Ensemble</h5>
<ul>
<li>training 1D-CNN and 2D-CNN using image classification models' outputs as inputs<ul>
<li>for more details, see my past topic in MoA competition: <br>
<a href="https://www.kaggle.com/c/lish-moa/discussion/204685" target="_blank">https://www.kaggle.com/c/lish-moa/discussion/204685</a></li></ul></li>
<li>applying weight optimization to image classification models' outputs</li>
<li>finally averaging these three models' outputs</li>
</ul>
<p>Unfortunately, however, simple averaging has better private score(0.9014) than this stacking(0.9008). I missed a gold medal 😇</p>
<p><br></p>
<p>That's all. Thanks you reading 😉</p> |
Cassava Leaf Disease Classification | simple (public 3rd and private 29th) 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: Cassava Leaf Disease Classification
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p><strong>Acknowledgements</strong><br>
Thanks to Kaggle for organizing this competition.<br>
I learned a tremendous amount of tricks in this competition and it would not have been able if it wasn’t for all this generous sharing of top solutions and extremely talented teammates ( <a href="https://www.kaggle.com/cdeotte" target="_blank">@cdeotte</a> <a href="https://www.kaggle.com/hanson0910" target="_blank">@hanson0910</a> and <a href="https://www.kaggle.com/zlanan" target="_blank">@zlanan</a> ) i was lucky to have along the way. thanks to my well collaborative team mates. <strong>Together we learned a lot</strong> 💪</p>
<p><strong>We did not have any magic there, only diverse models with highest CV</strong></p>
<p>our aim was to design an ensemble using top pytorch + tensorflow models with different image size,different TTA and diverse models (it worked well on public lb and also on private)</p>
<p>our 32nd place submission uses,</p>
<p><strong>model 1 -> nf-resnet50:</strong><br>
[0.897, 0.903, 0.899. 0.8932, 0.8946]</p>
<p><strong>model 2 ->ResNext50(image size 512):</strong><br>
[0.891, 0.897, 0.892, 0.886, 0.892]</p>
<p><strong>model 3 -> 0.8913 vit. + 0.886 +0.884 +0.883 noisy tf B4. Intentionally trained three relatively low CV noisy tf B4 but works, quite strange.</strong></p>
<p><strong>model 4 and 5 -></strong><br>
(tf_efficientnet_b4_ns + Vit-B16) with 2019 years of data, so CV has no reference value but it's around 0.9</p>
<p><strong>model 6 -></strong><br>
not sure what the CV is for 512 image size efficientnet-b0 <strong>(tensorflow model)</strong> but public lb was 0.895 </p>
<p><strong>model 7 -></strong></p>
<p>tf_efficientnet_b4_ns_fold_0_8: cv 0.8914<br>
tf_efficientnet_b4_ns_fold_0_5: cv 0.8932</p>
<p>only 1 fold of vit base from this notebook : <a href="https://www.kaggle.com/mobassir/vit-pytorch-xla-tpu-for-leaf-disease" target="_blank">ViT - Pytorch xla (TPU) for leaf disease</a></p>
<p>vit_base_patch16_384_fold_4: cv0.89175</p>
<p>only 2 fold of vit large from this notebook : <a href="https://www.kaggle.com/mobassir/faster-pytorch-tpu-baseline-for-cld-cv-0-9" target="_blank">Faster Pytorch TPU baseline for CLD(cv 0.9)</a></p>
<p>vit_large_patch16_384_fold_2: cv 0.89568<br>
vit_large_patch16_384_fold_1: cv 0.89826</p>
<p>used following tta (3 step):</p>
<pre><code>def get_inference_transforms(image_size = image_size):
return Compose([
RandomResizedCrop(image_size, image_size),
Transpose(p=0.5),
HorizontalFlip(p=0.5),
VerticalFlip(p=0.5),
HueSaturationValue(hue_shift_limit=0.2, sat_shift_limit=0.2, val_shift_limit=0.2, p=0.5),
RandomBrightnessContrast(brightness_limit=(-0.1,0.1), contrast_limit=(-0.1, 0.1), p=0.5),
Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], max_pixel_value=255.0, p=1.0),
ToTensorV2(p=1.0),
], p=1.)
</code></pre>
<p>and for vit large : </p>
<pre><code>inference_transforms = albumentations.Compose([
#albumentations.RandomResizedCrop(image_size, image_size),
albumentations.Resize(image_size, image_size),
albumentations.Transpose(p=0.5),
albumentations.HorizontalFlip(p=0.5),
albumentations.VerticalFlip(p=0.5),
albumentations.HueSaturationValue(hue_shift_limit=0.2, sat_shift_limit=0.2, val_shift_limit=0.2, p=0.5),
albumentations.RandomBrightnessContrast(brightness_limit=(-0.1,0.1), contrast_limit=(-0.1, 0.1), p=0.5),
])
</code></pre>
<pre><code>
</code></pre>
<p><a href="https://www.kaggle.com/zlanan" target="_blank">@zlanan</a> found these as best augmentations : </p>
<pre><code> RandomResizedCrop(CFG['img_size'], CFG['img_size']),
Transpose(p=0.4),
HorizontalFlip(p=0.4),
VerticalFlip(p=0.4),
ShiftScaleRotate(p=0.3),
MedianBlur(blur_limit=7,always_apply=False, p=0.3),
IAAAdditiveGaussianNoise(scale=(0, 0.15*255),p=0.5),
HueSaturationValue(hue_shift_limit=0.2, sat_shift_limit=0.2, val_shift_limit=0.2, p=0.4),
RandomBrightnessContrast(brightness_limit=(-0.1,0.1), contrast_limit=(-0.1, 0.1), p=0.4),
Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], max_pixel_value=255.0, p=1.0),
CoarseDropout(p=1.0),
Cutout(p=0.4),
</code></pre>
<p>we blended all models that had cv close to 0.9 or more than that, with that we got public lb 0.8978 and <strong>private lb 0.9019</strong> <strong>(but couldn't select it because of low lb score)</strong></p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F974295%2F0c878fc4e2b2156904d2ff3ff3cbb05c%2FLocalCV_publicLB.jpeg?generation=1569486918078902&alt=media" alt=""></p>
<p><strong>Final note</strong></p>
<p>we did observe a rise on both LB with lighter TTA, but also a drop. we did observe a improve with different image size model but also a drop. we can not say anything is really useful, except <strong>avg ensemble.</strong></p>
<p>some of our early experiment results can be found here : <a href="https://docs.google.com/spreadsheets/d/1HSMuTrMmwB5-8GXeJ-h68xeOIEeffcRo2W6HcmfXCzs/edit#gid=0" target="_blank">https://docs.google.com/spreadsheets/d/1HSMuTrMmwB5-8GXeJ-h68xeOIEeffcRo2W6HcmfXCzs/edit#gid=0</a></p>
<p>thank you for reading</p> |
NFL 1st and Future - Impact Detection | 3rd Place Solution -- Simple 2-Stage Pipeline | 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: NFL 1st and Future - Impact Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks to the organizers and congrats to all the winners and my wonderful teammates! <a href="https://www.kaggle.com/boliu0" target="_blank">@boliu0</a> <a href="https://www.kaggle.com/garybios" target="_blank">@garybios</a><br>
The dataset of this competition is much more complicated than normal ones and full of places to explore.<br>
So I'd like to call it Multi-view Video Event Detection task, rather than simple Object Detection task, because:</p>
<ul>
<li>This data set contains time series information</li>
<li>This data set has multi-view for a same scene</li>
<li>Although the impact bbox is marked on the helmet, the marking must depend on the environment around the helmet<br>
In addition, the understanding of the metric is also extremely important for this competition.</li>
</ul>
<h1>Summary</h1>
<ul>
<li>Only use videos and images.</li>
<li>Use EfficientDet to generate candidate impact bboxes, crop them into small images.</li>
<li>Use binary image classfication model to classify helmet crops through 9 frames.</li>
<li>Adjust scores for each bbox by multi-view information (Post-processing).</li>
<li>Drop similar bbox through 9 frames (Post-processing).<br>
This is a illustration of our pipeline (except for post-processing):<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F448347%2Fb44aec006fc2f22e0b868e6f279fcf08%2Fimage.png?generation=1609816179094206&alt=media" alt=""></li>
</ul>
<h1>Generate Candidate BBoxes</h1>
<p>We train EfficientDet on 2 classes (helmet and impact) then take all bboxes with class == 'impact' and score > 0.17 as candidate bboxes.<br>
If a player has an impact, we regard all his bboxes within +-4 frames as positive bboxes, because the metric treats predictions within 4 frames as TP. Base on this rule, if a positive bbox appears in a frame, we will regard it as a positive frame<br>
While training EfficientDet, we use all positive frames and 50% of the negative frames (which mean no positive bbox in it) from all videos, and all the 10,000 static images.</p>
<h1>Binary Classification Model</h1>
<p>As shown in the illustration, we use binary classification models to further predict whether bboxes crops are impacts or not.<br>
For training binary models, we expand the height and width of the bbox in the videos to 3 times the original length, crop them from frames, and use this as the training data for the binary classification model.<br>
When cropping a specific bbox, we crop it through 9 frames (t-4, t-3, t-2, t-1, t, t+1, t+2, t+3, t+4), turn it into gray scale and stack together to get an input of shape (h, w, 9)<br>
It should be noted that the <code>9</code> here is a variable parameter.<br>
Through this method we can get around 900k helmet crops, which is consistent with the number of bboxes in this data set.<br>
But unlike training EfficientDet, when training binary models, we only regard the impact bbox and its +-1 frame corresponding bbox as positive, which is less than 6k.<br>
When predicting, we use the same cropping method for all the candidate bboxes and then infer these crops by binary models.<br>
Through the binary model, our single model local score jump from 0.3x to near 0.6 with our post-processing methods, which is the biggest highlight in our pipeline.</p>
<h1>Multi-View Post-Processing</h1>
<p>We found that when one view has an impact, there is a high probability that the other view has an impact within the +-1 frame range. Therefore, we tuned separated thresholds depending on the predictions in the other view. For instance, the threshold for a certain Endzone frame depends on whether there is a predicted bbox in the Sideline view within +-1 frame. If yes, the threshold is lower (say 0.25); if not, the threshold is higher (say 0.45).</p>
<h1>Drop Similar BBox</h1>
<p>According to the official metric, although the predicted bbox is counted as TP in the +-4 frame range, a label can only accept one predicted bbox. Therefore, we hope that an impact will only output one prediction bbox.<br>
So we designed a function to drop all but one "similar" bboxes within any 9 consecutive frames, keeping only the one with largest confidence. For this purpose, we define any cross-frame bbox to be similar when they have iou > 0.25</p>
<h1>Ensemble</h1>
<p>Finally we ensemble 7 EfficientDet Models and 18 Binary Models that achieved local score 0.64, public LB 0.66 and private LB 0.69</p>
<h1>Acknowledgement</h1>
<p>Special Thanks to Z by HP & NVIDIA for sponsoring me a Z8G4 Workstation with dual RTX6000 GPU and a ZBook with RTX5000 GPU.<br>
It's really fast and powerful enough for this harsh competition!</p> |
Cassava Leaf Disease Classification | Yippeee!!! First silver (tentatively)!!! | 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: Cassava Leaf Disease Classification
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Wooow!!! amazing feeling !! I may have just won my first silver!!</p>
<p>Thank you!! It's bee such a helpful community with feedback and learning!! feels awesome!!</p>
<p>was really worried since I could not get my 4 model ensemble to work in the last 4 days in spite of all my attempts to fix it…. and given the noisy dataset was totally unsure how it would go…<br>
having been shaken out by 400-500 ranks in private LB was very nervous!!</p>
<p>Even ended up having a gold level submission that I did not select!! but who cares!! Happy to be in the right side of the shakeup and win my first silver!!</p>
<p>Thank you for all the inputs and knowledge sharing throughout the competition!! Great to be part of such an amazing community!!</p> |
Riiid Answer Correctness Prediction | 37th place solution (Transformer part) | 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: Riiid Answer Correctness Prediction
<|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 oganizer and Kaggle for hosting the competition. In addition, thanks for <a href="https://www.kaggle.com/vk00st" target="_blank">@vk00st</a> inviting us to merge as a team, and other teammates <a href="https://www.kaggle.com/unkoff" target="_blank">@unkoff</a> <a href="https://www.kaggle.com/arvissu" target="_blank">@arvissu</a> <a href="https://www.kaggle.com/syxuming" target="_blank">@syxuming</a>, we have great team work.</p>
<p>I also want to thank <a href="https://www.kaggle.com/manikanthr5" target="_blank">@manikanthr5</a> <a href="https://www.kaggle.com/wangsg" target="_blank">@wangsg</a> <a href="https://www.kaggle.com/leadbest" target="_blank">@leadbest</a> great SAKT starter notebook. I can’t implement the Transformer model by myself without these.</p>
<p>I summarize the detail of our SAINT+ like model as follows.</p>
<h2>Input features</h2>
<ol>
<li>content_id</li>
<li>response (answered_correctly)</li>
<li>part</li>
<li>prior_question_elapsed_time</li>
<li>prior_question_had_explanation</li>
<li>lag_time1 - convert lag time to seconds. if lag_time1 >= 300 than 300.</li>
<li>lag_time2 - convert lag time to minutes. if lag_time2 >= 1440 than 300 (one day).</li>
<li>lag_time3 - convert lag time to days. if lag_time3 >= 365 than 365 (one year).</li>
</ol>
<p>Lag time split to different time format boosting score around 0.003.</p>
<h2>Distinguish zero padding</h2>
<ul>
<li>In order to distinguish zero padding and zero of <strong>content_id</strong>, I add one to <strong>content_id</strong> and <strong>prior_question_had_explanation</strong> and <strong>response</strong>. It will help model distinguish zero padding and features. It boost score around 0.003.</li>
</ul>
<pre><code>q_ = q_+1
pri_exp_ = pri_exp_+1
res_ = qa_+1
</code></pre>
<h3>Transformer</h3>
<h5>Encoder Input</h5>
<ul>
<li>question embedding</li>
<li>part embedding</li>
<li>position embedding</li>
<li>prior question had explanation embedding</li>
</ul>
<h5>Decoder Input</h5>
<ul>
<li>position embedding</li>
<li>reponse embedding</li>
<li>prior elapsed time embedding</li>
<li>lag_time1 categorical embedding</li>
<li>lag_time2 categorical embedding</li>
<li>lag_time3 categorical embedding</li>
<li>Note that I tried categorical and continuous embedding in prior elapsed time and lag time. The performance of categorical embedding is better than continuous embedding.</li>
</ul>
<h5>Parameter of Transformer</h5>
<ul>
<li>max sequence: 100</li>
<li>d model: 256 </li>
<li>number of layer of encoder: 2</li>
<li>number of layer of decoder: 2</li>
<li>batch size: 256</li>
<li>dropout: 0.1</li>
<li>learning rate: 5e-4 with AdamW</li>
</ul>
<h3>Blending</h3>
<ul>
<li>LGBM + Catboost + three Transformer</li>
<li>LGBM + two Transformer</li>
</ul>
<h3>Result</h3>
<ul>
<li>Finally, our team get LGBM public LB 0.794 and Transformer public LB 0.799.</li>
<li>Get public LB 0.804 with blending.</li>
</ul>
<h3>Sample code</h3>
<ul>
<li><a href="https://www.kaggle.com/m10515009/saint-is-all-you-need-training-private-0-801" target="_blank">Training</a></li>
<li><a href="https://www.kaggle.com/m10515009/saint-is-all-you-need-inference-private-0-801" target="_blank">Inference</a></li>
</ul> |
Cassava Leaf Disease Classification | First time Competition, 75th place solution silver region | 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: Cassava Leaf Disease Classification
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>This competition is indeed coming to an end. With 3 days remaining(as this post was made), lets overview important things that I found quite useful learning wise. This competition is my first competition, and set up a really good impression of kaggle for me. I believe that this competition is a great competition to not only learn, but to test your knowledge and discover new ideas.</p>
<p>Notebooks down below.</p>
<p>With over 3.k+ members attending, 4.8k competitors, with over 85.5k+ submissions…</p>
<p>Cassava 2019 tournament: A classification problem of this tournament back in 2019. Winning solutions for this classification are<br>
1st place: <a href="https://www.kaggle.com/c/cassava-disease/discussion/94114" target="_blank">https://www.kaggle.com/c/cassava-disease/discussion/94114</a><br>
2nd place: <a href="https://www.kaggle.com/c/cassava-disease/discussion/94112" target="_blank">https://www.kaggle.com/c/cassava-disease/discussion/94112</a><br>
3rd place: <a href="https://www.kaggle.com/c/cassava-disease/discussion/94102" target="_blank">https://www.kaggle.com/c/cassava-disease/discussion/94102</a></p>
<p>These notebooks came in really handy, as they provide useful ideas that we competitors can integrate in.</p>
<p>Some useful notebooks in this competition that benefitted me and many others.<br>
(Note: These are not all of the helpful notebooks that have helped me, but instead the notebooks I believe started me up the fastest.)</p>
<p><a href="https://www.kaggle.com/dimitreoliveira/cassava-leaf-disease-tpu-tensorflow-training" target="_blank">Dimitre's cassava leaf disease training</a><br>
<a href="https://www.kaggle.com/piantic/train-cassava-starter-using-various-loss-funcs" target="_blank">Heroseo's various loss functions</a><br>
<a href="https://www.kaggle.com/khyeh0719/pytorch-efficientnet-baseline-inference-tta" target="_blank">Kun Hao Yeh's inferencing notebook +training</a><br>
<a href="https://www.kaggle.com/yasufuminakama/cassava-resnext50-32x4d-starter-training" target="_blank">Y.Nakama's notebooks</a></p>
<h2>Step 1: Knowledge distillation</h2>
<p>My team and I realized that this dataset marginally have a lot of noisy labels, and so in order to address this problem.. We smoothed the labels and later combined knowledge distillation to feed into our model.</p>
<h2>Step 2:</h2>
<p>We realized that certain augmentations are really useful of course during training stage.<br>
With 8x TTA in inference giving us a <br>
<strong>Public LB 0.904</strong> and <strong>Private LB 0.900</strong><br>
While 5x TTA was a tad bit worse.</p>
<h2>Step 3:</h2>
<p>Center crop + hue saturation effected out PB LB, alongside with 5 folds for efficientnetB4.<br>
Because the training time was 8 hours max, all my teammates trained separate folds for each and later did the same to resnext for inference. You can check this out on the inference and training notebook down below.</p>
<h2>Efficientnet B4 + Resnext:</h2>
<p>Our best fit model with no distillation was:</p>
<table>
<thead>
<tr>
<th>Model</th>
<th>Distillation</th>
<th>Public LB</th>
<th>Private LB</th>
</tr>
</thead>
<tbody>
<tr>
<td>Efficientnet B4</td>
<td>No</td>
<td>0.899</td>
<td>-</td>
</tr>
<tr>
<td>Efficientnet B4</td>
<td>Yes</td>
<td>0.902~0.9003</td>
<td>0.9034</td>
</tr>
<tr>
<td>Efficientnet B4 + Resnext50</td>
<td>Yes</td>
<td>0.903~0.904</td>
<td>0.90036</td>
</tr>
</tbody>
</table>
<h2>Experimentations</h2>
<p><strong>Augs</strong>:</p>
<ul>
<li>Fmix</li>
<li>SnapMix</li>
<li>Training: Hue Saturation + Coarse dropout + Random Brightness</li>
<li>Inference: Standard TTA augs</li>
</ul>
<p><strong>TTA:</strong></p>
<ul>
<li>Light augs(only flips): 4~8x TTA </li>
<li>Standard augs: 5~8x TTA</li>
</ul>
<p><strong>Losses</strong>:</p>
<ul>
<li>Taylor crossentropy + smoothening(best)</li>
<li>Bi-tempered loss</li>
<li>Categorical crossentropy</li>
</ul>
<h2>Conclusion</h2>
<p>Lucky to not have a bad shakedown!<br>
We did try to implement NFnet, however we didn't have time when the weights were released so we bailed on that. Check it out as it is revolutionary!</p>
<p>Again, these are just a list of the things that came off the top of my head! First competition, and I don't know if it is finalized so I won't be uploading our notebook at the moment for solution. However, I will be uploading it tomorrow! Just making sure that the place my amazing team <a href="https://www.kaggle.com/teodorbogoeski" target="_blank">@teodorbogoeski</a> and <a href="https://www.kaggle.com/varungadre0910" target="_blank">@varungadre0910</a> are finalized! Still don't quite understand how kaggle really works but definitely interested in learning more! If this is finalized, we will be placed 75th on the first competition that my team and I have done! Learned lots from kaggle and this competition! Definitely going to do more… Thanks to many wonderful people who shared their ideas and knowledge in a meaningful manner for novices like me. </p>
<p>(Edit): Never mind, turns out I will release the notebooks now.</p>
<p>I will be planning to upload notebooks for various datasets… Just waiting for this to finalize just to be sure! Thank you kaggle!</p>
<p>Training: <a href="https://www.kaggle.com/andyjianzhou/cassava-training-fastai-efficnetnet-distill" target="_blank">Here</a></p>
<p>Inference: <a href="https://www.kaggle.com/andyjianzhou/cassava-inferencing-efficientnetb4-resnext50?scriptVersionId=54404877" target="_blank">Here</a></p>
<p>Thanks to my amazing teammates who built these models efficiently! Looking forward to next competitions! </p>
<p>Useless note: Did pretty bad on my unit final today but that's alright.. Machine Learning Forever!</p> |
Cassava Leaf Disease Classification | Public 13th / Private 184th 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: Cassava Leaf Disease Classification
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h3>1. Overview</h3>
<p>We selected two versions by increasing the variety of models and models with the highest score on the leaderboard.</p>
<p><strong>Submission1 (Variety Models)</strong></p>
<ul>
<li>Public LB : 904 Private LB : 899</li>
<li>Inference Code : <a href="https://www.kaggle.com/hihunjin/avengers-assemble-3-model10-tta2?scriptVersionId=54655767" target="_blank">https://www.kaggle.com/hihunjin/avengers-assemble-3-model10-tta2?scriptVersionId=54655767</a></li>
</ul>
<p><img src="https://github.com/choco9966/Cassava-Leaf-Disease-Classification/blob/main/image/submission1.png?raw=true" alt=""></p>
<p><strong>Submission2 (Highest LB)</strong> </p>
<ul>
<li>Public LB : 908 Private LB : 897</li>
<li>Inference Code : <a href="https://www.kaggle.com/chocozzz/sub4-effx3-regx3-tta-3?scriptVersionId=54655742" target="_blank">https://www.kaggle.com/chocozzz/sub4-effx3-regx3-tta-3?scriptVersionId=54655742</a></li>
</ul>
<p><img src="https://github.com/choco9966/Cassava-Leaf-Disease-Classification/blob/main/image/submission2.png?raw=true" alt="Submission2"></p>
<h3>2. Tricks or Magics</h3>
<ul>
<li>Augmentations : LB 899 to 900 with GridMask</li>
</ul>
<pre><code> def get_train_transforms():
return Compose([
RandomResizedCrop(CFG['img_size'], CFG['img_size']),
Transpose(p=0.5),
HorizontalFlip(p=0.5),
VerticalFlip(p=0.5),
ShiftScaleRotate(p=0.5),
HueSaturationValue(hue_shift_limit=0.2, sat_shift_limit=0.2, val_shift_limit=0.2, p=0.5),
RandomBrightnessContrast(brightness_limit=(-0.1,0.1), contrast_limit=(-0.1, 0.1), p=0.5),
Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], max_pixel_value=255.0, p=1.0),
CoarseDropout(p=0.5),
GridMask(num_grid=3, p=0.5), # 899 to 900
ToTensorV2(p=1.0),
], p=1.)
</code></pre>
<ul>
<li><p>Label Smoothing Loss : LB 900 to 901 </p>
<ul>
<li>alpha : 0.2 (When testing values between 0.05 and 0.3, 0.2 was the best score.)</li></ul></li>
<li><p>SWA : LB 901 to 902 </p></li>
<li><p>TTA Inference : LB 902 to 905 </p></li>
</ul>
<pre><code> def get_inference_transforms():
return Compose([
OneOf([
Resize(CFG['img_size'], CFG['img_size'], p=1.),
CenterCrop(CFG['img_size'], CFG['img_size'], p=1.),
RandomResizedCrop(CFG['img_size'], CFG['img_size'], p=1.)
], p=1.),
Transpose(p=0.5),
HorizontalFlip(p=0.5),
VerticalFlip(p=0.5),
Resize(CFG['img_size'], CFG['img_size']),
Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], max_pixel_value=255.0, p=1.0),
ToTensorV2(p=1.0),
], p=1.)
</code></pre>
<ul>
<li>only CenterCrop : 902 </li>
<li>using RandomResized + CenterCrop : 904</li>
<li>using Resize + CenterCrop + RandomResizedCrop : 905 </li>
<li>Optimizer : Adam to Adamp (EfficientNet has reduced performance)<ul>
<li>VIT : 901 to 902 </li>
<li>RegNetY40 : 904 to 905 </li>
<li>Eff : 905 to 904</li></ul></li>
</ul>
<p>Ensemble (Eff 905 / RegNetY 905 / VIT 902)</p>
<ul>
<li>EFF(2019+2020) + EFF(2020) + EFF(SEED 720) + RegNetY(2019+2020) + RegNetY(2020) + RegNetY(Distillation) : 908</li>
<li>EFF(2019+2020) + EFF(2020) + RegNetY(2019+2020) + RegNetY(2020) : 907</li>
<li>EFF + RegNetY : 907 </li>
<li>EFF + VIT : 906 </li>
<li>EFF + VIT + RegNetY : 906 </li>
</ul>
<h3>3. Trial and Error</h3>
<ul>
<li>Preprocessing : Noise Label Delete (using oof score), Clean Lab, Merging 2019 Dataset </li>
<li>Augmentation : Cutmix, Cutout, Fmix, , 5 Crop etc.</li>
<li>Loss : Bi-Tempered Logistic Loss, Focal Loss, Taylor Loss etc.</li>
<li>Models : NFNet, BotNet, DeiT, Distillation, Fixmatch </li>
<li>Optimizer : Adamw, Adamp (Sometimes it works for each model, and sometimes it doesn't) , RAdam, SAM </li>
<li>Ensemble : SEED Ensemble, VIT + RegNetY40 + EfficientNet etc. </li>
<li>Others : Batch Normalization Freeze, Hyper parameter Tuning (lr, gradient accum etc), Global Average Pooling to Concatenate Max Pooling and GAP etc. </li>
</ul>
<p>You can see our All Training code in the GitHub below. </p>
<ul>
<li>GitHub : <a href="https://github.com/choco9966/Cassava-Leaf-Disease-Classification" target="_blank">https://github.com/choco9966/Cassava-Leaf-Disease-Classification</a></li>
</ul>
<p>Lastly, I would like to say thank you to the team members who worked hard for 2 months.@Minyong Shin <a href="https://www.kaggle.com/bellwood" target="_blank">@bellwood</a> <a href="https://www.kaggle.com/hihunjin" target="_blank">@hihunjin</a> <a href="https://www.kaggle.com/cysohn" target="_blank">@cysohn</a> </p> |
NFL 1st and Future - Impact Detection | 5th place solution: one-stage I3D with additional 2D model for bbox centers | 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: NFL 1st and Future - Impact Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks to the organizers and congrats to all the winners!</p>
<p>My solution:</p>
<h2>Data preparation</h2>
<p>The videos were split into fragments of shape <strong>8х224х224х3</strong>. As positive examples I chose a frame with impact and four frames before it and three after it. Using a grid with a constant step I made patches of size 224x224. As negative examples I chose random sequences of frames, which had no impacts. Also, I saved bounding boxes' positions and sizes for each sequence of frames.</p>
<h2>Models</h2>
<p>From the very start, I used 3D CNN, namely <strong>I3D</strong> from <a href="https://github.com/facebookresearch/SlowFast" target="_blank">SlowFast</a>. The one change I made to it was adding the fourth channel in input, which was always equal one for the fifth frame (don't know whether it had any sense or not). This is the fifth frame that the model predicts bboxes for. Then I appended FPN from <a href="https://github.com/qubvel/segmentation_models.pytorch" target="_blank">pytorch_segmentation</a> with six output channels without upsampling.</p>
<p>The 3d feature maps from second to fifth blocks of the backbone net were converted to 2d feature maps using <code>F.adaptive_avg_pool3d</code> and then passed to FPN.</p>
<p>The FPN produced a grid of size 6x56x56. The first channel of the grid was responsible for the presence of a bbox in a particular cell of the grid. The next four channels were responsible for the position of the bbox inside a grid cell and the bbox size. The last channel predicted the presence of impact in a cell. All these predictions were made only for the fifth frame in the sequence of eight frames. Overall this grid resembles yolo output except for anchors.</p>
<h2>Training</h2>
<h3>1st stage. Training on 224x224 patches:</h3>
<p>Augmentations:</p>
<pre><code>A.Compose([
A.HorizontalFlip(p=0.5),
A.OneOf([
A.ColorJitter(p=1),
A.HueSaturationValue(40, 60, 40, p=1),
A.RGBShift(60, 60, 60, p=1),
A.RandomGamma((20, 200), p=1)
], p=0.8),
A.OneOf([
A.GaussianBlur(p=1),
A.GaussNoise((10.0, 50.0), p=1),
A.MedianBlur(blur_limit=5, p=1),
A.MotionBlur(p=1),
], p=0.6),
A.ShiftScaleRotate(shift_limit=0.1, scale_limit=0.1, rotate_limit=0,
border_mode=0, p=0.4),
# A.GridDistortion(p=0.2, border_mode=0),
])
</code></pre>
<h4>Loss functions</h4>
<p>I had several configurations of losses for training.<br>
<strong>HuberLoss</strong> was used as a loss for bboxes position and sizes. <strong>FocalBinaryLoss</strong> or <strong><code>nn.BCEWithLogitsLoss</code></strong> with different pos_weight parameter were used for predicting presence of bboxes and impacts.</p>
<h4>Schedule and optimizer</h4>
<p><strong>Adam</strong> with default parameters and multistage <strong>decreasing of lr in 10 times</strong> were used. There were ten epochs.</p>
<h4>Data for training</h4>
<p>For each epoch, I chose all the positive examples and <strong>positive_count*2</strong> negative examples. Starting from the second epoch <strong>hard negative mining</strong> was used. For this, I got predictions for all negative examples and chose those of them that had the impact confidence above some threshold (0.1). If there were not enough hard examples I added negative examples by choosing randomly.</p>
<h3>2nd stage. Training on the whole image</h3>
<p><strong>I froze backbone</strong> and trained only FPN on whole images of size <strong>8x3x720x1280</strong> for a couple of epochs. The augmentations and optimizer were the same as at stage 1.</p>
<p><strong>The ensemble of four such models</strong> got score <strong>0.48</strong> on my local validation.<br>
Then I noticed that the detection of helmet centers worked not well. It was often mistaken a shoulder protector (I don't know what exactly this thing is called) for a helmet and gave it more confidence than it gave for some helmets.<br>
I assumed that it was because the ground truth data for bbox centers contained only points and those points were not always located in the centers of helmets so it was difficult for a model to understand where it should output points. So instead of points in the centers of bboxes I decided to predict circles with diameters equal to the average between a bbox's width and height. These circles were fading towards their boundaries. As it is shown in the picture.</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1187467%2Fa304d9baca7da6f8ead634ce5fe030ea%2Fhelmet_circles.png?generation=1609958610819611&alt=media" alt=""></p>
<p>I trained standalone <strong>FPN with resnet34 as backbone</strong> on single 224x224x3 patches and these circles as ground truth. Also, I used <code>nn.BCEWithLogitsLoss</code> as a loss (yes, you can use it for a regression task). Using such a model for predicting bboxes' centers gave a significant boost to the score, up to <strong>0.58</strong> on local validation.</p>
<h2>Predicting</h2>
<p>There was an ensemble of <strong>four models based on I3D</strong>, which had been trained using different configurations, and an <strong>ensemble of two FPN-resnet34</strong> models for predicting bbox centers. The predictions from the models would be averaged. Including bbox positions and sizes.</p>
<p>For each frame in a video, I got four previous frames and three next and concatenated them into a sequence. Then I padded the image to 736x1280.</p>
<p>So the input for I3D models had the size of <strong>3x8x736x1280</strong> and output had the size of <strong>6x184x320</strong>. As input for FPN-resnet34 models I used one current frame and the output of these models was <strong>1х736х1280</strong>, which was downsampled to 184x320. Also for predicting helmet centers I used <strong>TTA</strong> <strong>scaling an image to [0.75, 1.0, 1.25, 1.5]</strong> and averaging predicted values with weights [0.3, 1.0, 0.3, 0.15] accordingly.<br>
Using predictions from FPN-resnet34 models for bbox centers and predictions from I3D for bbox sizes and impacts I made a list of helmets that had scores above <strong>0.4</strong>. Then I applied <strong>non-maximum suppression</strong> with parameter <strong>0.25</strong> to that list to get the final list of bboxes for a frame. Those bboxes that had in their center confidence of impact above <strong>0.45</strong> were marked as positive.</p>
<p>Then I applied suppression of positive bboxes of the same helmet on neighboring frames.</p>
<p>There were two ways. The first was to simply apply <strong>nms</strong> to <strong>+/-4</strong> frames with iou above <strong>0.3</strong>. Except that I used not helmet confidence but <strong>impact confidence</strong> as maximum values.</p>
<p>The second was slightly more complicated. I got one bbox with maximum impact confidence in the whole video sequence and designated this bbox as the current bbox. Then I looked for bboxes in neighboring frames in both directions that had maximum iou with this current bbox. If iou was above some thresholds I suppressed the bbox in the neighboring frame and designated this new bbox as the current bbox. Then I looked for bboxes with maximum iou in next/previous frame for this new bbox. And so on up to 4 frames in both directions. If there were no bboxes with iou above the threshold I discontinued propagating suppression.</p>
<p>Both approaches worked the same.</p>
<h2>Post-processing</h2>
<p>I used the two side view. If there was an impact in one view and there were no impacts in the other view and confidence of the impact was below <strong>0.55</strong> I removed this prediction of impact from the final submission.</p>
<p>This post-processing improves score not much, it gave just +<strong>0.01-0.015</strong>.</p> |
HuBMAP - Hacking the Kidney | 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: HuBMAP - Hacking the Kidney
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p><strong>Please consider the following links:</strong> <a href="https://www.kaggle.com/theoviel/hubmap-final-methodology-submission" target="_blank"><strong>writeup</strong></a>, <a href="https://github.com/Optimox/HubMap" target="_blank"><strong>code</strong></a>. Below I provide just a short description.</p>
<h3>The key:</h3>
<ul>
<li>proper consideration of healthy and unhealthy glomeruli and trust in CV</li>
<li>2 class approach</li>
<li>proper annotation of the data</li>
<li>be careful with d488c759a when check LB</li>
</ul>
<h3>Introduction</h3>
<p>Our team would like to thank organizers and kaggle for making this competition possible. And a really big thanks to my amazing teammates <a href="https://www.kaggle.com/theoviel" target="_blank">@theoviel</a> and <a href="https://www.kaggle.com/optimo" target="_blank">@optimo</a> for their incredible efforts in working on the competition and putting everything into writeup for the judge prize. Also <a href="https://www.kaggle.com/optimo" target="_blank">@optimo</a> received his first gold medal in this competition, big congratulation to him! Finally, congratulations to all participants of this challenge.</p>
<p>It was quite a long journey for some of us, since the competition started back in 2020. There were a number of challenges we needed to overcome, and there were many learning opportunities. For me, as well as for some participants, it was the opportunity to <strong>learn labeling medical data</strong>. It may sound funny, but doing this job I realized the amount of work organizers put into this challenge.</p>
<h3>Our approach</h3>
<p><strong>In core of our approach is proper treatment of healthy and unhealthy glomeruli.</strong><br>
In short, we quickly realized that d488c759a with FC annotated is destabilizing LB and creating a gap between CV and LB. Use of external data with <a href="https://www.kaggle.com/c/hubmap-kidney-segmentation/discussion/208972" target="_blank">this annotation</a> improved LB but did not affect or even degraded CV. The explanation is simple: it contained annotation of both healthy and unhealthy glomeruli (at least large portion of them), while the train set contained only annotation of healthy glomeruli. So <strong>how can we make a model to predict FC: train it on images with FC… But it was not a right thing</strong>: organizers were looking for healthy glomeruli only, and all images except d488c759a did not include FC into annotation. So, use the external data with the shared hand labeling was dangerous, and some people, I may expect, got affected by shake up at the end of the competition because of this.</p>
<p><strong>Our strategy was proper hand annotation of</strong> <a href="https://data.mendeley.com/datasets/k7nvtgn2x6/3" target="_blank"><strong>this external dataset</strong></a> <strong>with 2 classes</strong>: healthy and unhealthy glomeruli. There are many kinds of unhealthy glomeruli, but we decided to keep the things simple, combining them into a single class. We also hand annotated unhealthy glomeruli class in test images, which combined with PL for healthy glomeruli, were used in our training pipeline. We also used <a href="https://zenodo.org/record/4299694" target="_blank">zondo dataset</a>, which naturally includes two classes. However, there was quite a number of missed glomeruli, especially at the image edges, and we hand annotated them. Finally, we used 2 images from HuBMAP portal, not included into train/test datasets with PL (both healthy and unhealthy) generated by our model. Using of multiple data sources helped us to ensure that the model is able to generalize well on new cases. We also used a combined human+AI guided method to add missing annotation to the train data (there were just a few instances tough). </p>
<p><strong>Secret sauce: ignore d488c759a from LB evaluation.</strong> LB with fixed predictions on this image correlated quite well with CV</p>
<p>From the model perspective of view, there is nothing really special, EfficientNet, Unet… Though, we tried more advanced things, like BoT middle layer, Swin transformer backbone, FPN skip connections, but it was not giving any noticeable benefit. This competition really was not about it. The thing that helped was using 2 classes during training. The level of injury of glomeruli is on a continuous scale. So instead of confusing the model by providing nearly identical glomeruli included/excluded from masks, we made the model to learn that unhealthy glomeruli are also glomeruli, and at the end model decides whether a particular instance is healthy enough. To be honest, this competition was not really about segmentation but rather about classification. The uncertainty of including a particular glomerulus in the mask predicted by the model is the major factor degrading the model performance.</p>
<p>Our best submission (ensemble of two models) got 0.9439 CV, 0.941 LB (with including hand annotation of unhealthy glomeruli for d488c759a image), and 0.950 private LB. There were some technical difficulties with making submissions on the last day, so we could not make a submission with all our final models(</p>
<h4>Links: <a href="https://www.kaggle.com/theoviel/hubmap-final-methodology-submission" target="_blank"><strong>writeup</strong></a> <- please take a look (it provides additional details and results of the analysis we made), <a href="https://github.com/Optimox/HubMap" target="_blank"><strong>code</strong></a></h4> |
Cassava Leaf Disease Classification | 40th place solution(4 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: Cassava Leaf Disease Classification
<|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 say thanks to <a href="https://www.kaggle.com/qi0239" target="_blank">@qi0239</a> <a href="https://www.kaggle.com/bilogo" target="_blank">@bilogo</a> <a href="https://www.kaggle.com/ageage" target="_blank">@ageage</a> <a href="https://www.kaggle.com/hsdtlp" target="_blank">@hsdtlp</a> ,this is our first match in kaggle,they spend much time finding suitable method and persisted till the end.</p>
<h1>score</h1>
<ul>
<li>Public Leaderboard 0.9050</li>
<li>Private Leaderboard 0.9007</li>
</ul>
<h1>training details</h1>
<ul>
<li>data: 2020 data with 5fold</li>
<li>Image_size: 512x512</li>
<li>Models: efficientnet b4,efficientnet b3,repvgg b2g4,se_resnext50</li>
<li>Loss function: bi-tempered loss with label smooth </li>
<li>Optimizer: AdamW</li>
<li>Lr scheduler: Cosine Annealing with Warm Restarts</li>
<li>Augmentations: HorizontalFlip, VerticalFlip,ShiftScaleRotate,mixup,snapmix(when we using HueSaturationValue and RandomBrightnessContrast,it improve our cv,but lower lb)</li>
<li>TTA: ShiftScaleRotate,Flip</li>
</ul>
<h1>ensemble</h1>
<p>we using 4 models :efficientnet b4,efficientnet b3,repvgg b2g4,se_resnext50.like other teams,single model didn't performance as good as ensemble.At first,we using efficientnet b3 & se_resnext50,by this way,we get higest public lb 0.900.when finding ensemble working,we continue test efficientnet-b4 and add it in our ensemble,in this discussion<a href="url" target="_blank">https://www.kaggle.com/c/cassava-leaf-disease-classification/discussion/213183</a>,we notice repvgg model,and we tried testing type A0-B3,find type B2g4 have best performance in cv and public lb,by adding repvgg,it help our public lb +0.003.</p>
<h1>methods that didn't work</h1>
<ul>
<li>remove noisy images,we using PHash to find same images and remove similar images,both cv and lb become lower</li>
<li>Pseudo-Labelling</li>
<li>concat avgpool feature & maxpool feature</li>
</ul>
<h1>in this match,I have learnt a lot,people here are enthusiasm,their Reply in the discussion gave me a lot of help in the game.Best wish!</h1> |
Cassava Leaf Disease Classification | Private 7th | Public 71th 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: Cassava Leaf Disease Classification
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><blockquote>
<p>The experience of this competition is extraordinary for me, due to the noise data of PB, I think I am really lucky to enter the gold medal zone, because most people's PB scores are very close. I really appreciate all the discussion topics and public notebooks, and I learn a lot from it. Thank you very much!Congratulations to all the people and teams who won the medals !</p>
</blockquote>
<h1>Solution</h1>
<p>two schemes were selected to submit:</p>
<h2>1. the first submission: no secondary processing for noise label</h2>
<h4>CV 0.90398 | LB 0.906 | PB 0.901</h4>
<p><strong>this scheme is the best CV in local</strong>. It uses a lot of augmentation, including randomcrop, H/V flip, a large number of RGB transform, cutout, grid distortion, etc., </p>
<p><strong>6modelx4TTA:</strong></p>
<table>
<thead>
<tr>
<th>model</th>
<th>loss</th>
<th>size</th>
</tr>
</thead>
<tbody>
<tr>
<td>efficientnet_b4_ns</td>
<td>bi-tempered</td>
<td>512</td>
</tr>
<tr>
<td>seresnext101</td>
<td>bi-tempered</td>
<td>512</td>
</tr>
<tr>
<td>seresnext101</td>
<td>focalcos</td>
<td>512</td>
</tr>
<tr>
<td>seresnext50</td>
<td>bi-tempered</td>
<td>512</td>
</tr>
<tr>
<td>VIT_base16</td>
<td>focalcos</td>
<td>384</td>
</tr>
<tr>
<td>VIT_base16</td>
<td>bi-tempered</td>
<td>384</td>
</tr>
</tbody>
</table>
<p>the results show that the scores of all ensemble submitted PB without secondary processing for noise label were between 0.898 and 0.902. </p>
<p>there are two results of PB 0.902:</p>
<p><strong>3model and 5xrandomTTA:</strong><br>
<strong>CV --- | LB 0.902 | PB 0.902</strong></p>
<table>
<thead>
<tr>
<th>model</th>
<th>loss</th>
<th>size</th>
</tr>
</thead>
<tbody>
<tr>
<td>efficientnet_b4_ns</td>
<td>bi-tempered</td>
<td>512</td>
</tr>
<tr>
<td>seresnext101</td>
<td>bi-tempered</td>
<td>512</td>
</tr>
<tr>
<td>VIT_base16</td>
<td>bi-tempered</td>
<td>384</td>
</tr>
</tbody>
</table>
<p>randomTTA is the same as the augmentation method in training, randomly 5 times</p>
<p><strong>5model and 5xTTA:</strong><br>
<strong>CV --- | LB 0.901 | PB 0.902</strong></p>
<table>
<thead>
<tr>
<th>model</th>
<th>loss</th>
<th>size</th>
</tr>
</thead>
<tbody>
<tr>
<td>efficientnet_b4_ns</td>
<td>bi-tempered</td>
<td>512</td>
</tr>
<tr>
<td>efficientnet_b4_ns</td>
<td>focalcos</td>
<td>384</td>
</tr>
<tr>
<td>seresnext101</td>
<td>bi-tempered</td>
<td>512</td>
</tr>
<tr>
<td>VIT_base16</td>
<td>focalcos</td>
<td>384</td>
</tr>
<tr>
<td>regnety120</td>
<td>focalcos</td>
<td>512</td>
</tr>
</tbody>
</table>
<h2>2. the second submission: based on the prediction results of the first scheme, knowledge distillation is carried out, and the student model results and the teacher model results are weighted by a ratio of 4:6</h2>
<h4>CV 0.9063 | LB 0.902 | PB 0.900</h4>
<p>the augmentation and the model structure is unchanged</p>
<p><strong>6 student model and 4xTTA</strong><br>
<strong>CV 0.9079 | LB 0.901 | PB 0.898</strong></p>
<table>
<thead>
<tr>
<th>model</th>
<th>loss</th>
<th>size</th>
</tr>
</thead>
<tbody>
<tr>
<td>efficientnet_b4_ns</td>
<td>CE</td>
<td>512</td>
</tr>
<tr>
<td>seresnext101</td>
<td>CE</td>
<td>512</td>
</tr>
<tr>
<td>VIT_base16</td>
<td>CE</td>
<td>384</td>
</tr>
<tr>
<td>resnext101</td>
<td>CE</td>
<td>512</td>
</tr>
<tr>
<td>resnest101</td>
<td>CE</td>
<td>512</td>
</tr>
</tbody>
</table>
<p>I think the student model <strong>overfitting</strong> the training set, so I tried various weighting methods with the predicted probability of the first scheme. The range of pb is between 0.898 and 0.902</p>
<h2>3. something else (all changes to labels or delete labels are only for the training set, not the label of the validation set, keep the TRUE label in validation set)</h2>
<p>(as a comparison of the following, no processing has been applied to the noisy label: <br>
<strong>efficientnet-b4 5fold 5tta: PB 0.894</strong>, the following attempts all use this benchmark)</p>
<ul>
<li>images with prediction probability greater than 0.9 and incorrect predictions are deleted. <strong>PB 0.895</strong></li>
<li>the labels of images with prediction probability greater than 0.9 and incorrect predictions are changed. <strong>PB 0.896</strong></li>
<li>simply aug + snapmix, and gradually increase the probability of snapmix by epoch. <strong>PB 0.896</strong></li>
<li>2019+2020 Dataset, since the 2019 data set contains multiple sizes, and any resize/crop form will affect the final CV, I finally did not use the 2019 data ( The data for 2019 was deleted in the verification set) <strong>PB 0.895</strong></li>
<li>focalcos loss will increase CV, but some models will reduce the prediction probability of true label. </li>
<li>in my submit, when using random TTA, the score of PB and LB are close.</li>
<li>RegNet PB is higher than LB, but RegNet LB is too low, RegNet is not selected for submit.</li>
</ul>
<p>I am very glad to get my first solo gold, and I really look forward to 1st solution</p> |
NFL 1st and Future - Impact Detection | [10th place solution] Extended Centernet | 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: NFL 1st and Future - Impact Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks to NFL and Kaggle for hosting this interesting competition. Congratulation to all, especially to the prize winner and gold medalists.</p>
<p><em>The following is my approach.</em></p>
<p><strong>1. Detection models</strong><br>
My detection model is derived from <a href="https://github.com/xingyizhou/CenterNet" target="_blank">Centernet</a> (MIT licenced) with some modification.</p>
<ul>
<li><p>I replace the image-based feature extraction by a video-based feature extraction. Getting video features is very useful for deteting impact.</p></li>
<li><p>I stack multiple centernet's heads on the top of the feature extraction block. Each head is responsible for predicting helmet for each frame.</p></li>
<li><p>I calculate loss independently between 2 classes (helmet with impact and helmet without impact) and then using weighted sum of the 2 losses. </p></li>
<li><p>I write my own augmentation for video.<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F2545270%2F901fbd72b20f7781801a066a2d69ba09%2Fnet.jpg?generation=1609809101222562&alt=media" alt=""></p></li>
<li><p>Input: I use a sequence of 15 consecutive frames. I also use a customized sampling method that focus more on frames with impact. I think using longer sequence can improve the result further, but my GPU does not allowed me to do so.</p></li>
<li><p>Video feature extraction: I use EfficientB5 (need to modify number of input channels). I've tested EfficientB3, EfficientB5 and EfficientB6. I don't have enough time and GPU to explore further.</p></li>
<li><p>Detection head: I've used only Centernet for this detection head, because I am more familiar with it.</p></li>
</ul>
<p><strong>2. Post-Processing</strong></p>
<ul>
<li>IOU-Tracker: I simply use <a href="https://github.com/bochinski/iou-tracker" target="_blank">IOU-Tracker</a> (MIT licenced) to link the detected impacts from near by frames. For each tracked trajectory, I just keep the middle box and ignore the rest.</li>
<li>Dynamic confidence threshold: Since the impact most likely to happen from frame 30th to 80th, I use a low threshold within this range. The number of impacts decrease to the end of the video, so I slowly increase the confidence threshold to the end of the video. Below is the threshold I use for the whole video<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F2545270%2F52d822eabfcb8c39f6e9f128a009178f%2Fthresh.png?generation=1609809219877057&alt=media" alt=""></li>
</ul> |
Cassava Leaf Disease Classification | 14th Place Solution & 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: Cassava Leaf Disease Classification
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h2>Summary</h2>
<p>First, I would like to say thanks to my teammate <a href="https://www.kaggle.com/lizzzi1" target="_blank">@lizzzi1</a> for the great work and to Kaggle for organizing this competition. This was a very interesting learning experience. We invested a lot of time into building a comprehensive PyTorch GPU/TPU pipeline and used Neptune to structure our experiments. </p>
<p>Our final solution is a stacking ensemble of different CNN and ViT models; see the diagram below. Because of the label noise and the evaluation metric, trusting CV was very important to survive the shakeup. Below I outline the main points of our solution in more detail. <br>
<img src="https://i.postimg.cc/d1dcZ6Zv/cassava.png" alt="cassava"></p>
<h2>Code</h2>
<ul>
<li><a href="https://www.kaggle.com/kozodoi/14th-place-solution-stack-them-all" target="_blank">Kaggle notebook reproducing our submission</a></li>
<li><a href="https://github.com/kozodoi/Kaggle_Leaf_Disease_Classification" target="_blank">GitHub repo with the training codes and notebooks</a></li>
</ul>
<h2>Data</h2>
<ul>
<li>validating on 2020 data using stratified 5-fold CV</li>
<li>augmenting training folds with:<ul>
<li>2019 labeled data</li>
<li>up to 20% of 2019 unlabeled data (pseudo-labeled using the best models)</li></ul></li>
<li>removing duplicates from training folds based on hashes and DBSCAN on image embeddings</li>
<li>flipping labels or removing up to 10% wrong images to handle label noise (based on OOF)</li>
</ul>
<h2>Augmentations</h2>
<pre><code>- RandomResizedCrop
- RandomGridShuffle
- HorizontalFlip, VerticalFlip, Transpose
- ShiftScaleRotate
- HueSaturationValue
- RandomBrightnessContrast
- CLAHE
- Cutout
- Cutmix
</code></pre>
<ul>
<li>TTA: averaging over 4 images with flips and transpose</li>
<li>image size: between 384 and 600</li>
</ul>
<h2>Training</h2>
<ul>
<li>10 epochs of full training + 2 epochs of fine-tuning the last layers</li>
<li>gradient accumulation to use the batch size of 32</li>
<li>scheduler: 1-epoch warmup + cosine annealing afterwards</li>
<li>loss: Taylor or OHEM loss with label smoothing = 0.2</li>
</ul>
<h2>Architectures</h2>
<p>We used several architectures in our ensemble:</p>
<ul>
<li><code>swsl_resnext50_32x4d</code> - x14</li>
<li><code>tf_efficientnet_b4_ns</code> - x8</li>
<li><code>tf_efficientnet_b5_ns</code>- x7</li>
<li><code>vit_base_patch32_384</code> - x1</li>
<li><code>deit_base_patch16_384</code> - x1</li>
<li><code>tf_efficientnet_b6_ns</code> - x1</li>
<li><code>tf_efficientnet_b8</code> - x1</li>
</ul>
<p>ResNext and EfficientNet performed best, but transformers ended up being very important to improve the ensemble. Two EfficientNet models also included a custom attention module. Some models were pretrained on the PlantVillage dataset, others started from ImageNet weights.</p>
<h2>Ensembling</h2>
<p>Having done many experiments allowed us to inject a lot of diversity in the ensemble. Our best single model scored <strong>0.8995 CV.</strong> A simple majority vote with all models got <strong>0.9040 CV</strong> but we wanted to go beyond that and explored stacking.</p>
<p>Stacking was done with a LightGBM meta-model trained on the OOFs from the same CV folds. Apart from the 33 models described above, we included 2 "special" EfficientNet models:</p>
<ul>
<li>pretrained ImageNet classifier predicting ImageNet classes (from 1 to 1000)</li>
<li>binary classifier predicting sick/healthy cassava (0/1)</li>
</ul>
<p>Including the last two models and optimizing the meta-classifier allowed us to reach <strong>0.9067 CV</strong>, which was our best. To fit all 33+2 models into the 9-hour limit, we only used weights from a single fold for each of the base models. The inference took 8 hours and scored <strong>0.9016</strong> on private LB just a few hours before the deadline. It was tempting to choose a different submission since stacking only got <strong>0.9036</strong> on public LB (outside of the medal zone), but we trusted our CV and ended up rising to the 14th place. </p>
<p>Let me know if you have any questions and see you in the next competitions! 😊</p> |
Cassava Leaf Disease Classification | 45th 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: Cassava Leaf Disease Classification
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><blockquote>
<p><strong>Many congratulations to all the winners in this competition. Huge thanks to all the discussion topics, public notebooks and datasets - most of my learning came from them.</strong></p>
</blockquote>
<p>For the first time I am finishing so high in the final leaderboard grabbing a silver medal. I have failed miserably in past competitions, never had a satisfying finish but this time I really feel like I am learning from my mistakes, so yeah it feels great! </p>
<p><br></p>
<h2>Final Solution</h2>
<h4>Dataset:</h4>
<p><em>Competition Data ONLY. No extra data.</em></p>
<h4>CV Strategy:</h4>
<p>5 Fold Stratified CV</p>
<h4>Models (Pretrained):</h4>
<ul>
<li>EfficientNet-B7 NS (Noisy Student)</li>
<li>ViT Base16</li>
</ul>
<h4>Train Setting:</h4>
<p><strong>Image Size:</strong> 512 for B7 and 384 for ViT<br>
<strong>Epochs:</strong> 20 <br>
<strong>Early Stopping:</strong> No (Saved Best Epoch)<br>
<strong>Loss Function:</strong> Bi-tempered Logistic Loss with Label Smoothing<br>
<strong>Optimizer:</strong> Good old "Adam"<br>
<strong>LR Scheduler:</strong> Cosine Annealing with Warm Restarts<br>
<strong>Batch Size:</strong> 32 (with gradient accumulation)<br>
<strong>Augmentations:</strong> Standard (No CutMix, FMix or SnapMix)</p>
<pre><code> - Transpose
- HorizontalFlip
- VerticalFlip
- ShiftScaleRotate
- HueSaturationValue
- RandomBrightnessContrast
- CoarseDropout
- Cutout
</code></pre>
<blockquote>
<p>Edit: Both models didn't use the same augmentations, I did use mix augs for ViT. <br>
EfficientNet-B7: Standard Augs<br>
ViT Base P16: Standard + FMix + CutMix</p>
</blockquote>
<h4>Evaluation:</h4>
<ul>
<li>I used the 5 Fold OOF predictions to pick and evaluate the models based on "Accuracy".</li>
<li>Treated the Public Leaderboard Score as an alternative fold (as suggested in the forums)</li>
</ul>
<h4>Inference:</h4>
<p>I experimented a few things here, </p>
<ul>
<li>No TTA</li>
<li>Light TTA (only flips)</li>
<li>Standard TTA (used for aug)</li>
</ul>
<p>I noticed that my OOF predictions were more stable when I used Standard 4xTTA for both ViT and B7 so I went with that for the final submission.</p>
<h4>Submission:</h4>
<ul>
<li>EfficientNet-B7 was my best single model</li>
<li>I noticed that ViT alone was not enough on CV and LB</li>
</ul>
<p>I decided to evenly blend them at first and surprisingly that gave me a boost in OOF (CV) Score from 0.898 --> 0.901 and also a boost in Public LB 0.902 --> 0.905. However a weighted ensemble always seemed to be just short yet better than my single models. This gave me a feeling that an unweighted ensemble can cut it for me so I went with it. </p>
<h4>Results:</h4>
<table>
<thead>
<tr>
<th>Model</th>
<th>CV</th>
<th>Public LB</th>
<th>Private LB</th>
</tr>
</thead>
<tbody>
<tr>
<td>EfficientNet-B7 NS</td>
<td>0.894</td>
<td>0.900</td>
<td>0.894</td>
</tr>
<tr>
<td>ViT Base16</td>
<td>0.888</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
<td>EfficientNet-B7 NS 4xTTA</td>
<td>0.896</td>
<td>0.902</td>
<td>0.897</td>
</tr>
<tr>
<td>ViT Base16 4xTTA</td>
<td>0.891</td>
<td>0.899</td>
<td>0.896</td>
</tr>
<tr>
<td>(0.35 * ViT) + (0.65 * B7) weighted ensemble with 4xTTA</td>
<td>0.898</td>
<td>0.903</td>
<td>0.899</td>
</tr>
<tr>
<td>ViT + B7 unweighted ensemble with 4xTTA</td>
<td>0.901</td>
<td>0.905</td>
<td>0.900</td>
</tr>
</tbody>
</table>
<p>Looking forward to competing more and learning more!</p> |
Jane Street Market Prediction | Thanks! Becoming (Perhaps) One of the Youngest Competition Master | 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: Jane Street Market Prediction
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>My first gold medal! A huge thank you to the Kaggle community, without the discussion posts and public notebooks, I could not have reached this point! </p>
<p>I posted an <a href="https://towardsdatascience.com/my-journey-to-kaggle-master-at-the-age-of-14-e2c42b19c6f7" target="_blank">article</a> writing about the story and some tips I learned along the way .</p>
<h2>A Brief Summary of My Journey</h2>
<p>Hi, I'm Andy Wang, a 14 year old high school freshman. I became interested in Data Science and Machine Learning about a year ago. I found Kaggle hoping to enhance my skills and gain more experience of the industry. With my friend <a href="url" target="_blank">Andre Ye </a>, we started joining Kaggle competitions hoping to learn and discover new things. It was a shock to us when we received our silver medal in the <a href="https://www.kaggle.com/c/lish-moa" target="_blank">first competition</a> that we attended from a huge shakeup. Afterwards, we joined 2 more competition and was amazed by the results. I never thought that I could reach this point, the biggest thanks to the Kaggle community and my friends Andre. The knowledge I acquired from attending the competitions is more than that of the results. </p>
<p>Finally, the biggest lesson that I've learned from competitions is that <strong>simple solutions can go a long way.</strong> With the right cross validation scheme and a stable CV, the results were never too bad (Especially in this competition).</p>
<p>Again, I cannot thank the Kaggle community enough for teaching me and leading me through the fascinating field of Machine Learning. </p>
<p>(Aiming for Competition GM now! 😃 )</p> |
Rainforest Connection Species Audio Detection | 21st place solution - FP co-teaching with loss improvements | 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: Rainforest Connection Species Audio Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Congratulations to the top finishers!</p>
<p>The whole my solution is here: <a href="https://github.com/MPGek/mpgek-rfcx-species-audio-detection-public" target="_blank">https://github.com/MPGek/mpgek-rfcx-species-audio-detection-public</a>.<br>
I left the best configs that were used in the final submission.</p>
<h2>Summary</h2>
<p>Summary of my solution:</p>
<ul>
<li>General augmentations with frequency band augmentations:<ul>
<li>Frequency band filtering</li>
<li>Frequency band mixup</li></ul></li>
<li>TP training with a combined loss of the BCE for confident samples and LSoft 0.7 for noisy samples</li>
<li>FP training with a BCE for confident samples and ignored losses for samples with noisy samples</li>
<li>FP co-teaching training with loss as described in the co-teaching paper, but with the extra loss for the high loss samples</li>
<li>Ensemble of TP, FP, FP co-teaching results.</li>
</ul>
<h2>Spectrogram and random crop</h2>
<p>For the training, I used a random crop with the centered sample in 10 seconds and a random crop for 6 seconds.<br>
For validation and prediction, I used 6 seconds crop with a stride in 2 seconds with maximizing outputs.<br>
For the mel spectrogram, I used the following parameters:</p>
<ul>
<li>mels count: 380</li>
<li>FTT: 4096</li>
<li>window length: 1536</li>
<li>hop length: 400</li>
<li>fmin: 50</li>
<li>fmax: 15000</li>
</ul>
<p>So one sample in 6 seconds produced an image with size 720 x 380 pixels</p>
<h2>Augmentations</h2>
<p><strong>Augmentation that improves LB:</strong></p>
<ul>
<li>Gaussian noise</li>
<li>Random crop + resize with size reduction in 40 and 20 pixels</li>
<li>Frequency band filtering - based on f_min and f_max of the sample I set 0 values to all mels that lower or higher than f_min and f_max with a sigmoid transition to remove sharp edges<ul>
<li>Frequency band mixup - for some samples I used frequency band filtering and then I mixed it with different samples with a band that higher than f_max and with a band that lower than f_min. So I managed to get a single image with the 3 mixed samples.</li></ul></li>
</ul>
<p><strong>Example of the Frequency band filtering (top - original sample, bottom - sample after filtering):</strong><br>
<img src="https://github.com/MPGek/mpgek-rfcx-species-audio-detection-public/raw/main/img/Band%20filtering.png" alt=""><br>
<strong>Example of the Frequency band mixup (top - original sample, bottom - sample after mixup):</strong><br>
<img src="https://raw.githubusercontent.com/MPGek/mpgek-rfcx-species-audio-detection-public/main/img/Band%20mixup.png" alt=""><br>
<strong>Augmentation that doesn't improve LB:</strong></p>
<ul>
<li>SpecAugment</li>
<li>Sum mixup</li>
</ul>
<h2>Network topology</h2>
<p>I got the best results on EfficientNetB2, B4, B7 (noisy students weights) with a simple FC to 24 classes after the adaptive average pool.</p>
<p>I tried to use different head but all of them gave the same or worse result:</p>
<ul>
<li>the hyper column</li>
<li>the hyper column with auxiliary losses after each pooling</li>
<li>extra spatial and channel attentions blocks - CBAM</li>
<li>dense convolutions</li>
</ul>
<h2>TP training</h2>
<p>Based on the post where described that every sound file can present unlabeled samples I have to work noisy samples.</p>
<p>I split all samples into confident samples and noisy samples:</p>
<ul>
<li>confident samples - all sigmoid outputs for classes which present in the train_tp.csv file (1 in targets tensor)</li>
<li>noisy samples - all sigmoid outputs for classes which not described in the train_tp.csv file (0 in target tensor)</li>
</ul>
<p>For the confident samples, I used simple BCE. For the noisy samples, I used LSoft with beta 0.7 (<a href="https://arxiv.org/pdf/1901.01189.pdf)" target="_blank">https://arxiv.org/pdf/1901.01189.pdf)</a>. <br>
LSoft:</p>
<pre><code>def forward(self, input: torch.Tensor, target: torch.Tensor):
with torch.no_grad():
pred = torch.sigmoid(input)
target_update = self.beta * target + (1 - self.beta) * pred
loss = F.binary_cross_entropy_with_logits(input, target_update, reduction=self.reduction)
return loss
</code></pre>
<p>In the loss function, I flatten all outputs (even batch dim) to a linear array. And split items into 2 arrays where targets were 1 and where targets were 0.</p>
<p>With LSoft I got on EfficientNetB7 0.912-0.915 LB.<br>
Without LSoft - BCE for all samples I got only about 0.895-0.900.</p>
<h2>FP training</h2>
<p>For the FP training, I used a dataset with undersampling of the FP samples. Each epoch had all TP samples and the same count of the FP samples.<br>
I used batch sampling to provide a balanced batch of TP/FP samples - after each TP I added FP with the same species id.</p>
<p>In the loss function, I calculate loss only for those sigmoid outputs that present in train_tp.csv or train_fp.csv. So all noisy samples are ignored.</p>
<h2>FP co-teaching training</h2>
<p>I have tried to find a way how to use FOCI or SELFIE to work with noisy data, but all of them use historical predictions of each sample. With my random crop and frequency band mixup it's almost impossible. Even shift for 0.5-1 seconds can add a new species to the sample. So historical data will be incorrect.</p>
<p>I tried co-teaching training because it doesn't require historical data.<br>
Paper: <a href="https://arxiv.org/pdf/1804.06872.pdf" target="_blank">https://arxiv.org/pdf/1804.06872.pdf</a><br>
Code sample: <a href="https://github.com/bhanML/Co-teaching" target="_blank">https://github.com/bhanML/Co-teaching</a></p>
<p>When I implemented co-teaching training I have only 5 days before the deadline.<br>
The first experiments with co-teaching gave 0.830 LB for the TP and 0.880 LB for the FP. So it looked like a bad experiment.</p>
<p>I tried to improve loss function by adding high loss samples with changed targets (by default co-teaching should ignore high loss samples as wrong samples).</p>
<p>The final loss function consists of:</p>
<ul>
<li>50% lowest loss samples (all confident samples mandatory added to this part of loss with scale factor 2)</li>
<li>45% ignored losses</li>
<li>5% highest loss samples with the changed target (1 for predictions with sigmoid >= 0.5 and 0 for sigmoid < 0.5)<br>
The loss implementation is here: <a href="https://github.com/MPGek/mpgek-rfcx-species-audio-detection-public/blob/main/model/forward_passes_coteaching.py" target="_blank">https://github.com/MPGek/mpgek-rfcx-species-audio-detection-public/blob/main/model/forward_passes_coteaching.py</a></li>
</ul>
<p>When I invented this loss I had only 3 days before the deadline.<br>
This loss has a good potential for future experiments. I trained only 2 experiments with this loss, both with the same hyperparameters. The first one had a bug so it produces extremely high metrics and used wrong epochs to submission - however, even with the bug it produces a good LB score comparing to the original FP training.</p>
<h2>Folds and best epoch metric</h2>
<p>To chose the best epoch in all training I used the BCE which calculated only on confident samples.<br>
In some experiments I used 5 stratified KFold, in some, I used 7 folds with stratified shuffle split with test size 0.3.</p>
<h2>Ensembles</h2>
<p>The TP training with EfficientNetB7 gave me only 0.912-0.915 on the public LB.<br>
The FP training with EfficientNetB2-B4 gave only 0.887-0.893 LB.<br>
The ensemble of the TP and FP gave 0.929 LB.</p>
<p>The FP co-teaching training on simple EfficientNetB2 gave me 0.925 LB (a quite good improvement from the original FP with 0.893)</p>
<p><strong>The final ensemble consists of all best experiments (0.941 public LB and 0.944 private LB):</strong></p>
<ul>
<li>TP EfficientNetB7 with 0.915</li>
<li>FP EfficientNetB2-B4 with 0.893</li>
<li>FP co-teaching EfficientNetB2 with 0.925</li>
</ul> |
Jane Street Market Prediction | My (perhaps) over-complicated LSTM 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: Jane Street Market Prediction
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>tl:dr: <a href="https://www.kaggle.com/snippsy/js-over-complicated-lstm" target="_blank">Notebook</a></p>
<p>This was the first Kaggle competition I have more than a little effort into. <br>
It has been great to discuss and share ideas in the community. </p>
<p>I see now from some other published solutions that going simpler would have been better as I'm not that high up on the leaderboard. A saving grace is that at least my model scores better on the private than the public leaderboard. From 4900 -> 3700 (given 60% of the data the score would be 2900 if the data was the same). This could perhaps be down to underfitting. </p>
<p>The three things I did in the solution was:</p>
<ol>
<li><p><strong>Using features 41-43 to separate stocks</strong>. From <a href="https://www.kaggle.com/gregorycalvez/de-anonymization-price-quantity-stocks" target="_blank">this</a> notebook. <br>
This enabled me to use a time-series based model. </p></li>
<li><p><strong>Time embedding</strong>. Each stock could have from a few to hundreds of data points at irregular times. I wanted to emphasise this in the model, therefore, based on <a href="https://arxiv.org/abs/2003.09291" target="_blank">this</a> paper I created dense time features based on <code>feature_64</code>. </p></li>
<li><p><strong>Target denoising</strong>. Based on the idea from <a href="https://www.kaggle.com/lucasmorin/target-engineering-patterns-denoising" target="_blank">this</a> notebook, I used a linear regressor to denoise the targets. This improved the stability of the model massively. </p></li>
</ol>
<p>In addition to this, I dropped the <code>dates <85</code> and data with <code>weight = 0</code>. I tried using these data as well but yielded worse results. <code>CombPurgedKFoldCV</code> was used with 4 folds and 2 test periods per fold. </p>
<p>I did not have too much time to spare in the last few weeks of the competition, so I did minimal hyperparameter optimization (just manually), and therefore, the model is fairly simple, with <code><100k</code> parameters, if I remember correctly). </p>
<p>Finally, thank you to Jane Street for providing this great puzzle, and to all that have contributed actively to the discussions. This competition has been a great learning opportunity. </p>
<p>Best of luck to all. </p> |
NFL 1st and Future - Impact Detection | Zoom call/presentation to discuss solutions | 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: NFL 1st and Future - Impact Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>In the past Lyft competition I did a presentation with my meetup and zoom call with other competitors to discuss and exhibit various solutions to the problem. I would like to do another one for this competition. It was a much shorter period for this one so it would be great to share what was explored and deliberate on what the valuable take aways are. </p>
<p>I will update this post with a meetup/zoom link later once I get it scheduled. Intended date will be January 23rd at 10AM Pacific. </p>
<p><a href="https://www.meetup.com/San-Diego-Machine-Learning/events/275552917/" target="_blank">link to meetup </a></p>
<p>Here is a link to the recording of the previous zoom call to understand how it typically goes. <a href="https://www.youtube.com/watch?v=ScjnDwghHGM&t=2s" target="_blank">https://www.youtube.com/watch?v=ScjnDwghHGM&t=2s</a></p> |
Rainforest Connection Species Audio Detection | 3rd 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: Rainforest Connection Species Audio Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h1>3rd Place Solution</h1>
<p><strong>TLDR</strong></p>
<p>Our solution is a mean blend of 8 models trained on True positive labels of all recording ids in train_tp.csv (given + hand-labeled labels) also from some recording ids in train_fp.csv (hand-labeled labels) with heavy augmentations. Additionally, some models are also trained on pseudo labels and a hand-labeled external dataset. We also post-processed the blended results by thresholding species 3.</p>
<p>From 308 submissions it is obvious that we have tested a lot of techniques and I will share more detailed information by category below.</p>
<h2>Data Preparation</h2>
<p>I couldn't get a proper validation framework setup after trying out many techniques and decided at one point to start digging into the data and figured out that there are many unlabeled samples both in and out of the range of t_min and t_max labels given in train_tp.csv. In <a href="https://www.kaggle.com/c/rfcx-species-audio-detection/discussion/197735" target="_blank">https://www.kaggle.com/c/rfcx-species-audio-detection/discussion/197735</a> it was mentioned that using hand-labeled species was allowed, so I started labeling the data manually and after labeling 100 recording ids I could already get a > 0.9 public lb score and pretty consistent local CV scores that somewhat correlates with the public lb. Naturally, I continued to label the entire train_tp.csv seeing that it has only around 1.3k recording ids. Further labeling of train_fp.csv helped the score but only minimally so I stopped at one point. As I grew more familiar with the data I could label 300 recording ids in a day :), referring to pseudo labels helped a lot too. I also went through the train_tp.csv a few more rounds to make sure I have quality data. I used both spectrograms and listening strategy to analyze and label the data, some species are easy to spot with spectrograms and some are easier to spot by listening, and in some cases, both listening and visual inspection of the spectrograms can act as a multi verification technique to get more quality labels, especially when birds/frogs are very distant away from the recorder or there are strong noises like waterfall sounds. By labeling and analyzing the data I also figured out the kinds of sounds/noises that would appear and inspired me to try out a few augmentation methods which I will share below. Along with true positive labels, I also added noisy and non-noisy labels based on my confidence in the completeness of labels in a specific recording id. I am not a perfect labeler so I wanted to handle complete and non-complete labeled recording ids differently, which I will share below too.</p>
<p>I also removed some labels from train_tp.csv as I found some true positives suspicious, I didn't test not removing the labels before so not sure how much this helped.</p>
<p>Additionally, after finding out the paper from the organizers I searched for suitably licensed datasets with those species and found one dataset with species in this competition with a proper license. But there weren't any labels so I labeled it manually too with the same format as train_tp.csv. <a href="https://datadryad.org/stash/dataset/doi:10.5061/dryad.c0g2t" target="_blank">https://datadryad.org/stash/dataset/doi:10.5061/dryad.c0g2t</a> . I reuploaded the dataset <a href="https://www.kaggle.com/dicksonchin93/eleutherodactylus-frogs" target="_blank">HERE</a> with my manual labels.</p>
<p>I uploaded the extra labels as a dataset <a href="https://www.kaggle.com/dicksonchin93/extra-labels-for-rcfx-competition-data" target="_blank">https://www.kaggle.com/dicksonchin93/extra-labels-for-rcfx-competition-data</a>, feel free to use it and see if you can get a better single model score! mine was 0.970 on public lb</p>
<h2>Modeling / Data Pre-processing</h2>
<p>I used Mel Spectrograms with the following parameters: 32kHz sampling rate, a hop size of 716, a window size of 1366, and 224 or 128 Number of Mels. Tried a bunch of methods but plainly using 3 layers of standardized Mel Spectrograms works the best. The image dimensions were (num_mel_bins, 750). </p>
<p>Using train_tp.csv to create folds will potentially leak some training data into your validation data so I treated the problem as a multilabel target and used <a href="https://github.com/trent-b/iterative-stratification" target="_blank">iterative-stratification</a> to stratify the data into 5 partitions using unique recording ids and its multilabel targets. I had two different 5 fold partitions using different versions of the multi labels and used a mix of both in the final submission. </p>
<p>I used multiple different audio duration during the competition and at different stages of the competition, the best duration varied in my implementation but in the end, I used 5 seconds of audio for training and prediction as the LWLWRAP score was better on both public lb and local validation. </p>
<p>The 5-second audio was randomly sampled during training and in prediction time a 5-second sliding window was used with overlap and the max of predictions was used. How the 5-second audio is randomly sampled is considered to be an augmentation method in my opinion and so I will explain it in the heavy augmentations category below</p>
<h6>Augmentations</h6>
<ul>
<li>Random 5-second audio samples: <br>
a starting point was chosen randomly on values between reference t_mins and t_maxes obtained from </li>
</ul>
<pre><code>def get_ref_tmin_tmax_and_species_ids(
self, all_tp_events, label_column_key="species_id"
):
all_tp_events["t_min_ref"] = all_tp_events["t_min"].apply(
lambda x: max(x - (self.period / 2.0), 0)
)
def get_tmax_ref(row, period=self.period):
tmin_x = row["t_min"]
tmax_x = row["t_max"]
tmax_ref = tmax_x - (period / 4.0)
if tmax_ref < tmin_x:
tmax_ref = (tmax_x - tmin_x) / 2.0 + tmin_x
return tmax_ref
all_tp_events["t_max_ref"] = all_tp_events[
["t_max", "t_min"]
].apply(get_tmax_ref, axis=1)
t_min_maxes = all_tp_events[
["t_min_ref", "t_max_ref"]
].values.tolist()
species_ids = all_tp_events[label_column_key].values.tolist()
return t_min_maxes, species_ids
</code></pre>
<p>Labels were also assigned based on the chosen starting time and ending time with t_min and t_max labels.</p>
<ul>
<li>audio based pink noise</li>
<li>audio based white noise</li>
<li>reverberation</li>
<li>time stretch</li>
<li>use one of 16kHz or 48kHz sample rate data and resample it to 32kHz sample rate using randomly chosen resampling methods <code>['kaiser_best', 'kaiser_fast', 'fft', 'polyphase']</code></li>
<li>use different window types to compute spectrograms at train time <code>['flattop', 'hamming', ('kaiser', 4.0), 'blackman', 'hann']</code> , hann window is used at test and validation time</li>
<li>masking out non labeled chunks of the audio with a 10% chance</li>
<li>one of spectrogram <a href="https://arxiv.org/abs/2002.12047" target="_blank">FMix</a> and audio based mixup with the max of labels instead of using the blend from the beta parameter</li>
<li><a href="http://dcase.community/documents/challenge2019/technical_reports/DCASE2019_Bouteillon_27_t2.pdf" target="_blank">spec mix </a>: <br>
only one strip was used for each axis, for the horizontal axis when the chosen frequency range to mask out completely covers a specific species minimum f_min and maximum f_max , that species label will be dropped. Specmix is also using the max of labels instead of using the blend from the beta parameter. The code below shows how I obtain the function that can output frequency axis spectrogram positions from frequency</li>
</ul>
<pre><code>def get_mel_scaled_hz_to_y_axis_func(fmin=0, fmax=16000, n_mels=128):
hz_points = librosa.core.mel_frequencies(n_mels=n_mels, fmin=fmin, fmax=fmax)
hz_to_y_axis = interp1d(hz_points, np.arange(n_mels)[::-1])
# reversed because first index is at the top left in an image array
return hz_to_y_axis
</code></pre>
<ul>
<li>bandpass noise </li>
<li>Water from <a href="https://zenodo.org/record/4060432#.YC6IJ3VKjCI" target="_blank">Freesound50k</a> removing samples that have license to prevent derivative work</li>
<li>Engine and Motor Sounds from <a href="https://zenodo.org/record/4060432#.YC6IJ3VKjCI" target="_blank">Freesound50k</a> removing samples that have license to prevent derivative work</li>
<li>Honk, Traffic and Horn sounds from <a href="https://zenodo.org/record/4060432#.YC6IJ3VKjCI" target="_blank">Freesound50k</a> removing samples that have license to prevent derivative work</li>
<li>Speech sounds from <a href="https://zenodo.org/record/4060432#.YC6IJ3VKjCI" target="_blank">Freesound50k</a> removing samples that have license to prevent derivative work</li>
<li>Bark sounds from <a href="https://zenodo.org/record/4060432#.YC6IJ3VKjCI" target="_blank">Freesound50k</a> removing samples that have license to prevent derivative work</li>
</ul>
<p>checkout recording_id b8d1e4865 to find dogs barking and some human speech :D</p>
<h6>Architectures used</h6>
<p>No SED just plain classifier models with GEM pooling for CNN based models</p>
<ul>
<li>Efficientnet-b7</li>
<li>Efficientnet-b8</li>
<li>HRNet w64</li>
<li>deitbase224</li>
<li>vit_large_patch16_224</li>
<li>ecaresnet50</li>
<li>2x resnest50 from <a href="https://www.kaggle.com/meaninglesslives" target="_blank">https://www.kaggle.com/meaninglesslives</a>, checkout his writeup in a minimal notebook <a href="https://www.kaggle.com/meaninglesslives/rfcx-minimal" target="_blank">HERE</a>!</li>
</ul>
<h6>Loss</h6>
<p>The main loss strategy used for the final submission was using different loss function for samples which I am confident is complete in labels and samples which I am not confident is complete in labels. BCE was used for non-noisy/confident samples and a modified Lsoft loss was used on the noisy/non-confident. Lsoft loss was modified to be applied only to nonpositive samples, as I was confident in my manual labels. It looks like this </p>
<pre><code>def l_soft_on_negative_samples(y_pred, y_true, beta, eps = 1e-7):
y_pred = torch.clamp(y_pred, eps, 1.0)
# (1) dynamically update the targets based on the current state of the model:
# bootstrapped target tensor
# use predicted class proba directly to generate regression targets
with torch.no_grad():
negative_indexes = (y_true == 0).nonzero().squeeze(1)
y_true_update = y_true
y_true_update[negative_indexes[:, 0], negative_indexes[:, 1]] = (
y_true_update[negative_indexes[:, 0], negative_indexes[:, 1]] * beta +
(1 - beta) * y_pred[negative_indexes[:, 0], negative_indexes[:, 1]]
)
# (2) compute loss as always
loss = F.binary_cross_entropy(y_pred, y_true_update)
return loss
</code></pre>
<p>This was inspired by the first placed winner in the Freesound competition <a href="https://github.com/lRomul/argus-freesound" target="_blank">https://github.com/lRomul/argus-freesound</a> but I noticed that it doesn't make sense if it is used with mixup since audio will be mixed up anyways. So I also obtain the max of noisy binary labels so that noisy labels mixed with clean labels are considered to be noisy labels.</p>
<h6>Pseudo Labels</h6>
<p>I didn't get much boost from pseudo labels, maybe I did something wrong but nonetheless, it was used in some models. I used a 0.8 threshold for labels generated with 5-second windows and utilized the same window positions during training. Using raw predictions didn't help the model at all on lb.</p>
<h6>Post processing</h6>
<p>We set the species 3 labels to be 1 with a 0.95 threshold and it boosted the score slightly</p>
<h6>Other stuff</h6>
<ul>
<li>Early stopping of 20 epochs with a minimum learning rate of 9e-6 to start counting these 20 epochs</li>
<li>Reduce learning rate on Plateau with a factor of 0.6 and start with a few warmup epochs, when LR is reduced the best model weights was loaded back again</li>
<li>Catalyst was used</li>
</ul>
<h2>Things that failed</h2>
<ul>
<li>using models without pre-trained weights</li>
<li>timeshift</li>
<li>using species from the Cornell Competition that are confused with species in this competition as a distractor noise, for example, moudov is similar to species 15, reevir is similar to species 11, rebwoo is similar to species 6, bkbwar is similar to species 7, cacwre is similar to species 19, every is similar to species 17 and nrwswa is similar to species 20</li>
<li>using plane sounds from Freesound50k data</li>
<li>using PCEN, deltas or CQT</li>
<li><a href="https://www.kaggle.com/c/birdsong-recognition/discussion/183269" target="_blank">Random Power</a></li>
<li>TTA with different window types</li>
<li>Manifold mixup with resnest50</li>
<li>using trainable Switchnorm as an initial layer replacing normal standardization</li>
<li>using trainable Examplar norm as an initial layer replacing normal standardization</li>
<li>Context Gating</li>
<li>split audio intro three equal-length chunks and concat as 3 layer image</li>
<li>lsep and <a href="https://arxiv.org/abs/2009.14119" target="_blank">Assymetric loss </a></li>
<li>using rain sounds from Freesound50k data</li>
<li>using a fixed validation mask similar to how I used random training mask</li>
<li>use <a href="https://vsitzmann.github.io/siren/" target="_blank">SIREN</a> layer</li>
<li>Tried to separate some confusing patterns as separate manual labels but didn't get the chance to test them</li>
</ul>
<p>Hopefully, I didn't miss anything. Oh, we were holding off submitting a good model until <a href="https://www.kaggle.com/cpmpml" target="_blank">@cpmpml</a> came along :)</p> |
Cassava Leaf Disease Classification | Solution Arhitecture Pipeline for Bronze Medal | 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: Cassava Leaf Disease Classification
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>It had been a very interesting competition filled with of a lot of challenges, starting with the noise from the dataset, the possibility of using images from the previous competition dataset, and the diversity of possible solutions. <br>
I would like to share to the community one of the designed architectures that lead me and my team to the bronze medal<br>
<img src="https://i.ibb.co/M8QLDP8/general-Schematic.jpg" alt=""></p>
<p>Presented above is the general schema of the architecture which was designed from 4 steps.</p>
<p><strong>First step: Finding the best 3 models for the original provided data</strong></p>
<p>There were tuned:</p>
<ul>
<li>architecture type: EfficientNet B2, EfficientNet B3, EfficientNet B4</li>
<li>input image size: 480x480, 512x512, 520x520, 600x600</li>
<li>training epochs number: 30, 40</li>
<li>learning rate: 0.0001, 0.00015, 0.0002. 0.0003</li>
<li>learning rate scheduler: Cosine Anealing w/wo warmup, One Cycle, Reduce on Plateau</li>
<li>aditional layers on top of the network</li>
<li>random resize crop paramers</li>
<li>cutout probability, cutout size, cutout number, random brightness, random contrast parameters, - hue&saturation</li>
<li>label smoothing w/wo</li>
<li>cutmix w/wo and the proportions of cutting ([0.3, 0.4, 0.5, 0.6, 0.7])</li>
<li>imagenet vs noisy student initial weights</li>
<li>optimizer: Adam, RangerLars, AdamW</li>
</ul>
<p>The best 3 models configurations were:</p>
<p>Model 1:</p>
<ul>
<li>Model architecture: EfficientNet B2 (imagenet weights)</li>
<li>Image size: 600x600</li>
<li>Augmentations: Cutout(nr:32, size:32, prob:0.5), Random Brightness, Random Contrast, Transpose + Flip, Cutmix</li>
<li>Adam + One cycle (max value: 0.0003)</li>
</ul>
<p>Model 2:</p>
<ul>
<li>Model architecture: EfficientNet B4 (noisy student weights)</li>
<li>Image size: 512x512</li>
<li>Augmentations: Cutout(nr:32, size:32, prob:0.5), Random Brightness, Random Contrast, Transpose + Flip, Cutmix, </li>
<li>Adam + One cycle (max value: 0.0002) + Label Smoothing</li>
</ul>
<p>Model 3: </p>
<ul>
<li>Model architecture: EfficientNet B3 (imagenet weights)</li>
<li>Image size: 512x512</li>
<li>Augmentations: Cutout(nr:32, size:32, prob:0.5), Random Brightness, Random Contrast, Transpose + Flip, Cutmix, </li>
<li>Adam + One cycle (max value: 0.0002) + Label Smoothing</li>
</ul>
<p><strong>Second step: Denoising as much as possible the original data</strong><br>
<img src="https://i.ibb.co/nCqjXT4/cleanImg.jpg" alt=""><br>
The OOF prediction of the presented 3 models using 8 TTA combined using a weighted mean(weighted using the OOF score) was used to eliminate the samples that most likely were wrongly label. So we use the best OOF accuracy 3 models, each with 8 TTA added for extra robustness. We eliminated data where the predicted probabily for ground truth is lower than 0.20 (random chance). <br>
Using the new clean dataset, we tune the parameters and find the best possible model on this data</p>
<p><strong>Third step: Adding useful data from the last year similar competition</strong><br>
<img src="https://i.ibb.co/gtWBnxv/addData.jpg" alt=""><br>
The OOF prediction of the original 3 models using 8 TTA combined using a weighted mean(weighted using the OOF score) was used to determine what data are most likely to be correct from the last year dataset. So we use the best OOF accuracy 3 models, each with 8 TTA added for extra robustness. We added data where the predicted probabily for ground truth is higher than 0.90. <br>
Using the new clean dataset, we tune the parameters and find the best possible model on this data</p>
<p><strong>Forth step: Designing a meta classifier on top of the 3 models (original, cleaned and extended dataset)</strong><br>
<img src="https://i.ibb.co/R7f093v/stacking.jpg" alt=""></p>
<p>The input for the final step of the pipeline is the predictions of 3 models(original, cleaned and extended dataset) each with 4 TTA. So in total 12 predictions.<br>
There had been tested bagging, boosting and classical stacking and the best result is the one presented below<br>
<img src="https://i.ibb.co/n7NJF2w/meta.jpg" alt=""></p>
<p>So, we have a bagging of 100 meta classifiers, where each of the classifier is a two layer system with Random Forest, SVC, LGBM and Ridge at the bottom and SVC on the second layer. The main parameters of the bagging system is max_features = 0.3 and max_sample = 0.1 . <br>
The important parameters were tuned with a Bayesian approach. <br>
An interesting comparison was made between bagging and boosting methodology. As it you know, boosting is an algorithm which lead to more good results but prone to overfitting and bagging is more robust, generalize better but can give lower accuracy. And our results confirm this hypothesis. In the validation set, boosting provide much better accuracy but on the leaderboard due to the fact that we don't have a very good alignment between validation and learboard, bagging wins due to extra robustness.</p>
<p>In the end I want to congratulate the winners and to all participants !</p> |
Jane Street Market Prediction | Current 29th place 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: Jane Street Market Prediction
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>I'm relatively new to kaggle, so I'm surprised to be high in the leaderboard (maybe because of much luck). I learned a lot from this competition. I would like to share my approach. I published <a href="https://www.kaggle.com/hedwig100/js-inference-notebook" target="_blank">inference notebook</a> and <a href="https://www.kaggle.com/hedwig100/nn-training-notebook" target="_blank">training notebook</a>. </p>
<p>Later in this competition, I noticed ensembling models boosts my local CV. I think this is caused by stable prediction. So, I trained various models, and ensembled these models. Details are shown below. </p>
<p><br> </p>
<h1>Training Strategy</h1>
<ul>
<li>PurgedGroupTimeSeriesSplit(5fold and 20gap)</li>
<li>but maybe leakage was caused when training encoder… </li>
<li>watched AUC and UtilityScore in each fold.</li>
<li>used Early Stopping by valid-auc </li>
</ul>
<p><br></p>
<h1>Preprocess</h1>
<ul>
<li>fill NaN by 0 and FeatureNeutralization(p=0.25)</li>
<li>fill NaN by mean </li>
<li>denoising autoencoder</li>
</ul>
<p><br></p>
<h1>Model</h1>
<ul>
<li>simple NN, CNN and DenseNet. </li>
<li>I also used <a href="https://www.kaggle.com/a763337092/pytorch-resnet-starter-training" target="_blank">this famous notebook</a>'s model architecture. I trained this model with my CV strategy. </li>
<li>In first submission, I used my 3model. </li>
<li>In second submission, I used my 3model + 1pytorch model</li>
<li>For each model, I used weight trained in last fold, and weight trained with all data(except for weight = 0 and first 85days)</li>
<li>second submission achieves higher score. </li>
</ul>
<p><br></p>
<h1>Ensemble</h1>
<ul>
<li>weight average</li>
<li>weight was decided by CV. </li>
</ul>
<p><br> </p>
<p>Thank you for reading!</p> |
Cassava Leaf Disease Classification | 16th place solution with detailed and readable code for beginner | 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: Cassava Leaf Disease Classification
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks to <strong>Makerere University AI Lab</strong> and <strong>Kaggle</strong> for organizing this competition.<br>
Here is <a href="https://github.com/freedom1810/kaggle-cassava" target="_blank">our solution with code</a>, our approach is based on a <strong>good CV splitting strategy</strong> and better augmentation + loss + optimization to face the <strong>noisy-label problem</strong>.<br>
<strong>1. Data Preprocessing + Augmentation:</strong><br>
<strong>Dataset: 2019 + 2020 (512 input size).</strong><br>
<strong>For training:</strong></p>
<ul>
<li><strong>Simple augmentation</strong>: RandomResizedCrop, Transpose, HorizontalFlip, VerticalFlip, ShiftScaleRotate, ShiftScaleRotate, HueSaturationValue, RandomBrightnessContrast, Normalize, CoarseDropout, Cutout (we referred to this <a href="https://www.kaggle.com/khyeh0719/pytorch-efficientnet-baseline-train-amp-aug" target="_blank">kernel</a> (many thanks to <a href="https://www.kaggle.com/khyeh0719" target="_blank">@khyeh0719</a>), with a little bit change in the RandomResizedCrop and Normalize params).</li>
<li><strong>Advance augmentation</strong>: We tried with mixup, cutmix, fmix, snapmix. With our model, snapmix worked best with alpha = 5 (we refer to this <a href="https://www.kaggle.com/sachinprabhu/pytorch-resnet50-snapmix-train-pipeline" target="_blank">kernel </a>for snapmix, many thanks to <a href="https://www.kaggle.com/sachinprabhu" target="_blank">@sachinprabhu</a>). </li>
</ul>
<p><strong>For validation:</strong> We remove RandomResizedCrop by using CenterCrop + Resize with cv2.INTER_AREA. Snapmix was also not used. We also applied TTA = 5.</p>
<p><strong>2. Traning parameters</strong></p>
<ul>
<li><p><strong>Loss function</strong>: We tried focal cosine loss, bi-tempered loss, SCE loss (with label smoothing, of course). Bi-tempered worked best with t1 = 0.6, t2 = 1.2, label_smoothing=0.1, num_iters=5(we refered to this <a href="https://github.com/mlpanda/bi-tempered-loss-pytorch/blob/master/bi_tempered_loss.py" target="_blank">kernel </a>for bi-tempered loss).</p></li>
<li><p><strong>Optimization</strong>: We tried Adam, Ranger, SAM. SAM worked best on our CV (0.2-0.3% higher than Adam on CV). However, it did not show good results on Public LB. Finally, we chose Adam.</p></li>
<li><p><strong>LR Scheduler</strong>: We used the LR scheduler based on the Yolov5 <a href="https://github.com/ultralytics/yolov5/blob/master/train.py" target="_blank">code </a>and <a href="https://arxiv.org/pdf/1812.01187.pdf" target="_blank">tricks </a>on this paper with init LR = 1e-4 -> 5e-4, lrf = 1e-2.</p></li>
<li><p><strong>Training strategy</strong>: We unfroze the backbone after 5 epochs. The total training epochs were 50.</p></li>
<li><p><strong>Backbone model</strong>: All the pre-trained models are noisy-student models. We tried with B0 (using B0 as a baseline), B3, B4, and resnext50 using <a href="https://github.com/rwightman/pytorch-image-models" target="_blank">Timm</a>. With limited resources (up to 2x2080Ti and Colab Pro), we were not able to obtain a better result with B4 compared to B3 on the CV. Also, it took a lot of time for some experiments with ViT, but we did not get any prospects.</p></li>
<li><p><strong>Some tricks</strong>: We applied EMA on yolov5 with fp16. Using fp16 helped us to save a lot of time and computing resources.</p></li>
</ul>
<p><strong>3. Splitting strategy</strong><br>
It sounds really simple. We separately divided the 2020 and 2019 data into 5folds. After each trial, we mixed the best and the worst folds on the CV and resplitted them until the gap CV is not large than 0.4% (it took 4-5 days using Colab Pro with B0). It helped us to boost our result at the very last submits.</p>
<p><strong>4. Experiments</strong><br>
Here are some of our outstanding experiments.</p>
<table>
<thead>
<tr>
<th>Model</th>
<th>Note</th>
<th>CV</th>
<th>Public LB</th>
<th>Private LB</th>
</tr>
</thead>
<tbody>
<tr>
<td>B0</td>
<td>SAM + 10 TTA</td>
<td>0.8993</td>
<td>0.8969</td>
<td>0.8989</td>
</tr>
<tr>
<td>B3</td>
<td>Adam + 10 TTA</td>
<td>0.9011</td>
<td>0.9036</td>
<td>0.8984</td>
</tr>
<tr>
<td>B3</td>
<td>SAM + 10 TTA</td>
<td>0.9029</td>
<td>0.9027</td>
<td>0.8981</td>
</tr>
<tr>
<td>B3</td>
<td>SAM + newest splitting + 5 TTA</td>
<td>0.9033</td>
<td>0.9007</td>
<td>0.8992</td>
</tr>
<tr>
<td>B3 + B4 + resnext50</td>
<td>5 TTA</td>
<td>…</td>
<td>0.9045</td>
<td>0.9014</td>
</tr>
<tr>
<td>B3 + B4 + B0</td>
<td>5 TTA</td>
<td>…</td>
<td>0.9032</td>
<td>0.8990</td>
</tr>
<tr>
<td>B3 + B0 + resnext50</td>
<td>5 TTA</td>
<td>…</td>
<td>0.9030</td>
<td>0.9001</td>
</tr>
</tbody>
</table>
<p>The inference notebook is not included in our code, inference TTA is similar to validation TTA.<br>
We are working to modify your code as readable and usable as possible. I hope it could help the newbie to get familiar with other Kaggle competitions.</p>
<p><strong>P/S:</strong> We are a Vietnamese team (me and <a href="https://www.kaggle.com/gdvipbb258" target="_blank">@gdvipbb258</a>), thank you in advance for reading!</p> |
Rainforest Connection Species Audio Detection | 7th place solution - Beluga & Peter | 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: Rainforest Connection Species Audio Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks, Kaggle and RFCx, for this audio competition, and special thanks to my teammate <a href="https://www.kaggle.com/gaborfodor" target="_blank">@gaborfodor</a> Without him, I probably would have given up a long time ago, somewhere at 0.8xx.</p>
<h2>Data preparation</h2>
<p>Resampling everything to 32kHz and split the audio files into 3 seconds duration chunks. We used a sliding window with a 1-second step.</p>
<h2>Collecting more label</h2>
<p>The key to our result was that Beluga collected tons of training samples manually. He created an awesome annotation application; you can find the details <a href="https://www.kaggle.com/c/rfcx-species-audio-detection/discussion/220305" target="_blank">here</a>. <em>Source code included</em>.<br>
After the first batch of manually labeled examples, we quickly achieved 0.93x with an ensemble of a varying number of PANN (cnn14) models. </p>
<h2>Input</h2>
<p>We used mel-spectrograms as inputs with various <code>n_bin</code> (128, 192, 256, 288). Beluga trained PANN-cnn14 models with one input channel. For the other backbones (effnets, resnets, etc) I used three input channels with a simple trick:</p>
<ul>
<li>I used different <code>n_mel</code> and <code>n_fft</code> settings for every channel. E.g. n_mel=(128, 192, 256), n_fft=(1024, 1594, 2048). This results in different height images, so resizing to the same value is necessary.<br>
We both used <code>torchlibrosa</code> to generate the mel-spectrograms.</li>
</ul>
<h2>Augmentation</h2>
<p>We used three simple augmentations with different probability:</p>
<h5>Roll</h5>
<pre><code>np.roll(y, shift=np.random.randint(0, len(y)))
</code></pre>
<h5>Audio mixup</h5>
<pre><code>w = np.random.uniform(0.3, 0.7)
mixed = (audio_chunk + rnd_audio_chunk * w) / (1 + w)
label = (label + rnd_label).clip(0, 1)
</code></pre>
<h5>Spec augment</h5>
<pre><code>SpecAugmentation(time_drop_width=16, time_stripes_num=2, freq_drop_width=16, freq_stripes_num=2)
</code></pre>
<h2>Architectures</h2>
<ul>
<li>PANN - cnn14</li>
<li>EfficientNet B0, B1, B2</li>
<li>Densenet 121</li>
<li>Resnet-50</li>
<li>Resnest-50</li>
<li>Mobilnet v3 large 100<br>
We trained many versions of these models with different augmentation settings and training data. Beluga used a PANN - cnn14 model (I think it is the same as the original) from his <a href="https://www.kaggle.com/c/birdsong-recognition/discussion/183407" target="_blank">Cornell solution</a>.<br>
I trained a very similar architecture with different backbones and I used attention head from SED:</li>
</ul>
<pre><code>x = ...generate mel-specotrogram...
x = self.backbone.forward_features(x)
x = torch.mean(x, dim=2)
x1 = F.max_pool1d(x, kernel_size=3, stride=1, padding=1)
x2 = F.avg_pool1d(x, kernel_size=3, stride=1, padding=1)
x = x1 + x2
x = F.dropout(x, p=0.5, training=self.training)
x = x.transpose(1, 2)
x = F.relu_(self.fc1(x))
x = x.transpose(1, 2)
x = F.dropout(x, p=0.5, training=self.training)
(clipwise_output, norm_att, segmentwise_output) = self.att_block(x)
segmentwise_output = segmentwise_output.transpose(1, 2)
framewise_output = interpolate(segmentwise_output, self.interpolate_ratio)
output_dict = {
"framewise_output": framewise_output,
"clipwise_output": clipwise_output,
}
</code></pre>
<h2>Training</h2>
<p>Nothing special. Our training method was the same for all of the models:</p>
<ul>
<li>4 folds</li>
<li>10 epochs (15 with a higher probability of mixup)</li>
<li>Adam (1e-3; *0.9 after 5 epochs)</li>
<li>BCE loss (PANN version)</li>
<li>We used the weights of the best validation LWRAP epoch for inference.</li>
</ul>
<h2>Pseudo labeling</h2>
<p>After we had an excellent ensembled score on the public LB (0.950), we started to add pseudo labels to our dataset. The result after we re-trained everything was 0.96x.</p>
<h2>Final Ensemble</h2>
<p>Our final ensemble had 80+ models (all of them trained with 4-folds) </p> |
NFL 1st and Future - Impact Detection | Team tara 13th 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: NFL 1st and Future - Impact Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>[Update]</p>
<p>Our codes are released <a href="https://github.com/kentaroy47/kaggle-nflimpact-13thplace" target="_blank">here</a>.</p>
<p>First of all, thank you for the hosts for organizing this great challenge! </p>
<p>Congrats to all the winners and big thanks to my wonderful teammates <a href="https://www.kaggle.com/tereka" target="_blank">@tereka</a> <a href="https://www.kaggle.com/hidehisaarai1213" target="_blank">@hidehisaarai1213</a> <a href="https://www.kaggle.com/rishigami" target="_blank">@rishigami</a>, it was a great opportunity to work with such talents.</p>
<p>We really wanted to celebrate a birth of a new GrandMaster but time shall wait! </p>
<p>It was a big challenge for me too, since it was my first kaggle competition after my baby son was born..</p>
<h1>Overview</h1>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F3508221%2Fa5abcefa4a1968535ed22d82b18569ee%2Fimage%20(1).png?generation=1609822336590711&alt=media" alt=""></p>
<p>Our solution is based on a 2-stage pipeline with the first stage detecting impact candidate boxes and the second stage classifying either the candidate box is true or false positive. </p>
<ul>
<li><p>Detectors<br>
We train two separate detectors with Endzone and Sideline videos, respectively. Training separate detectors held better CV in our experiments.</p></li>
<li><p>PP of detections<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F3508221%2F6b4e699284aa5ff836225856ea0b9dc4%2Fimage%20(2).png?generation=1609822406670388&alt=media" alt=""></p></li>
</ul>
<p>One of the challenge we faced here was that impact boxes other than the time of impact had to be filtered. To cope with this, we use time-nms, where we grouped boxes with iou>0.3 within a certain duration (30 frames) and only the median box was extracted, which should represent the time of impact and other candidates are filtered out. Also we filter boxes that do not exist in both End or Side video within certain frames.</p>
<p>The output of the first stage scores <code>Precision 0.2, Recall 0.6, F1 0.2</code>. The parameters are tuned so the detector will achieve a high recall. </p>
<ul>
<li>Classification</li>
</ul>
<p>Like the 3rd place team's solution, we crop +- 4 frames of helmet images around the candidate box and classify them using Resnet3D. We implemented this based on the torchvision's video classifier model. We ensemble 8 classifiers with horizontal-flip TTA. We trained the classifiers using both Endzone and Sideline videos.</p>
<ul>
<li>Threshold optimization</li>
</ul>
<p>Since the impacts/video was about 10~20, we adaptively control the prediction threshold so that the final prediction/ video will range within 15-25 predication per video. This makes the model robust to threshold tuning and was quite important since a single video with a lot of FPs can corrupt the entire score. </p>
<p>The final CV was <code>Precision: 0.56, Recall 0.4, F1: 0.47</code> which has more room for improvement!</p>
<h2>Training the detector</h2>
<p>Training the detector was quite hard for us, since there were lots of options. We use mixup+cutmix augmentations and oversample images with impact during training. We use images without impacts as well, which improved the precision of the detectors.</p>
<h2>Training the classifier</h2>
<p>We were inspired by the <a href="https://www.kaggle.com/c/deepfake-detection-challenge/discussion/158158" target="_blank">Deepfake 3rd place solution</a> and used <a href="https://arxiv.org/pdf/1711.11248.pdf" target="_blank">3d CNNs</a> for classifiers.</p>
<p>We trained the classifier with all helmet images cropped in 96x96 or 128x128 images. Since there are lots of False images, we used focal loss as criterion. Also mixup contributed to the CV as well.</p>
<p>Since we didn't have much time to train, the detector and classifier were single-fold models.</p>
<h1>What didn't work (for us</h1>
<p>TTA, ensembling of detectors (TTA improved in PB but didn't work for CV and LB). Should have dug deeper here.</p>
<p>Classifiers with 27-channel input efficient nets. The CV/LB was much lower for us.</p>
<p>Using tracking data.</p>
<p>The CV for Endzone videos was about <code>0.43</code> and for sideline videos, <code>0.5</code>. We could not close this gap and think that Endzone videos are fundamentally hard because of occlusions between players and wonder what other teams did to close this gap.</p> |
Rainforest Connection Species Audio Detection | 23rd Place Solution: Supervised Contrastive Learning Meets Domain Generalization (with TF 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: Rainforest Connection Species Audio Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h3>Introduction</h3>
<p>Thanks Kaggle for this exciting competition and our team ( <a href="https://www.kaggle.com/dathudeptrai" target="_blank">@dathudeptrai</a> <a href="https://www.kaggle.com/mcggood" target="_blank">@mcggood</a> <a href="https://www.kaggle.com/akensert" target="_blank">@akensert</a> <a href="https://www.kaggle.com/theoviel" target="_blank">@theoviel</a> <a href="https://www.kaggle.com/ratthachat" target="_blank">@ratthachat</a> ) congratulate all winners -- we have learned a lot from this competition and all winners’ solutions !!</p>
<p>From the winner solutions, it turns out there are mainly 4 ways to break 0.95x</p>
<ol>
<li>Masked loss</li>
<li>Post-processing</li>
<li>Pseudo-labelling</li>
<li>Extra labeling</li>
</ol>
<p>We actually tried the first three but unfortunately could not really make them work effectively.<br>
Here, as an alternative solution, we would love to share our own solution which is able to reach 0.943 Private. </p>
<h3>Training pipeline (improve from 0.80x baseline to 0.92x)</h3>
<h4>Baseline</h4>
<p>Our baseline models score slightly above 0.8. We adopt an audio tagging approach using a densenet121 backbone and the BCE loss. </p>
<p>Our training pipeline includes the following tricks :</p>
<ul>
<li>Class-balanced sampling, using 8 classes per batch. Batch sizes were usually 64, and 32 for bigger models.</li>
<li>Cyclical learning rate with min_lr is 0.0001 and max_lr is 0.001, step_size is 3 epochs. We train models for 100 epochs with early stopping. </li>
<li>LookAhead with Adam optimizer (sync_period is 10 and slow_step_size is 0.5)</li>
</ul>
<h4>Pretraining with Supervised contrastive Learning (SCL) [0.81x -> 0.85x]</h4>
<p>Because of the small amount of data, models overfit quickly. To solve this problem,two options were using external data and cleverly pretraining our models. Unlike a lot of competitors, we focused on self-pretraining techniques : <a href="https://www.kaggle.com/dathudeptrai" target="_blank">@dathudeptrai</a> tried auto-encoders, GANs, SimCLR, Cola, and <a href="https://arxiv.org/abs/2004.11362" target="_blank">Supervised Contrastive Learning</a> which ultimately was the only thing to work. </p>
<h4>Non-overlap time Cutmix [0.85x -> 0.88x]</h4>
<p><img src="https://i.imgur.com/gH2ONQh.png" alt=""></p>
<p>Our sampling strategy consists of randomly selecting a crop containing the label. Most of the time, crops are bigger than labels which introduces false positives. One idea to make full use of our windows was to adapt cutmix to concatenate samples such that labels are entirely kept (when possible). </p>
<h4>Domain Generalization with MixStyle [0.88x -> 0.89x]</h4>
<p>Domain shift always exists in deep learning, in both practice and kaggle challenges, especially for small data. Therefore, domain generalization techniques should help with robustness. We applied a simple yet effective technique called <a href="https://openreview.net/pdf?id=6xHJ37MVxxp" target="_blank">Mixstyle</a>.</p>
<h4>Multi Scale inference (MSI) [0.89x -> 0.91x]</h4>
<p>Duration of species’ call varies quite a lot. For example, for class 3 it is around 0.7 seconds while for class 23 is around 8 seconds. To use this prior information, we use multiple window sizes (instead of using a single one). For each class, we choose the one that yields the best CV. In case we have multiple window sizes reaching the maximum, we take the largest window. Although our CV setup which consists of crops centered around the labels did not correlate really well with LB, the 2% CV improvement reflected on LB quite well.</p>
<h4>Positive learning and Negative learning [0.91x -> 0.92x]</h4>
<p>We used the following assumption to improve the training of our models : <br>
For a given recording, if a species has a FP and no TP, then it is not in the call. Our BCE was then updated to make sure the model predicts 0 for such species. </p>
<h3>Ensembling</h3>
<p>Our best single model densenet121 scores around 0.92 public and 0.93 private. Averaging some models with different backbones, we were able to reach 0.937. We tried many different ensembling, scale fixing and post-processing ideas, and were able to improve our score a bit, but unfortunately we could not find the real magic.</p>
<p>In the end, we empirically analyzed the most uncertain class predictions from our best models, and averaged predictions with other (weaker) models. We relied on diversity to make our submission more robust. Our final ensemble scored public 0.942 and private 0.943.</p>
<h5>Thanks for reading !</h5>
<p><a href="https://github.com/dathudeptrai/rfcx-kaggle" target="_blank">TensorFlow Code Here</a></p> |
Rainforest Connection Species Audio Detection | 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: Rainforest Connection Species Audio Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thank you for opening this competition<br>
Also the notebooks and discussions have helped me a lot, thank you all!</p>
<p>My solution was similar to Beluga & Peter in 7th Place.<br>
<a href="https://www.kaggle.com/https" target="_blank">@https</a>://<a href="http://www.kaggle.com/c/rfcx-species-audio-detection/discussion/220443" target="_blank">www.kaggle.com/c/rfcx-species-audio-detection/discussion/220443</a>.</p>
<ul>
<li>Multi-class multi-label problem</li>
<li>Data cleaning train_data with hand labels</li>
<li>SED model</li>
</ul>
<p></p>
<p><strong>[hand labels]</strong><br>
While observing the data from t_min and t_max in the given train__tp.csv, I found that there are many kinds of bird calls mixed together.<br>
So I decided to treat it as a multi-class multi-label problem.<br>
It was also mentioned in the discussion that the test labels were eventually carefully labeled by humans.<br>
The TPs in the given t_min, t_max range are all easy to understand, but there are many TPs in the 60s clip that are difficult to understand and not labeled.<br>
I thought it would be better to label them carefully by myself to make the condition as close to test as possible in case such incomprehensible calls are also labeled in test.<br>
And I was thinking of doing Pseudo labeling after the accuracy of the model improves.</p>
<p>I trimmed the 5s~ around t_min and t_max in train__tp.csv.<br>
Hand labels took about a week.<br>
As a result, a total of 2428 clips and 5s chunks were used as train_data.<br>
The distribution of the train_data classes looks like this<br>
(I couldn't upload the image, so I'll post it later)</p>
<p>class nb<br>
s3 1257<br>
s12 520<br>
s18 512<br>
:<br>
s16 100<br>
s17 100<br>
s6 97</p>
<p>I can see that there is a label imbalance, especially for s3, s12, and s18, because their labels co-occur among the other classes of clips.</p>
<p>In particular, s3 is dominant, so it tends to output high probability, while a few classes output low probability, so i thought this is a bad problem for this evaluation index.<br>
Therefore, in order to achieve a more balanced distribution, I oversampled the minority classes and undersampled the majority classes.<br>
However, the LB became worse.<br>
Looking back, I didn't think of approaching the test distribution, as Chris pointed out.<br>
<a href="https://www.kaggle.com/c/rfcx-species-audio-detection/discussion/220389" target="_blank">https://www.kaggle.com/c/rfcx-species-audio-detection/discussion/220389</a></p>
<p>Eventually, i ensembled 15 models with various losses(FocalLoss,FbetaLoss+FocalLoss,ResampleLoss).</p>
<p><strong>[trainning]</strong><br>
example single model <br>
PANNsDense161 (public_LB 0.95548, private_LB 0.96300)</p>
<p>I also tried EfficientNet_b0, Dense121, etc., but Dense161 worked well.</p>
<p>train_data(sr=48000,5s)<br>
window_size=2048,hop_size=512,mel_bins=256<br>
MultilabelStratifiedKFold 5fold<br>
BCEFocalLoss(α=0.25,β=2)<br>
GradualWarmupScheduler,CosineAnnealingLR(lr = 0.001,multiplier=10,epo35)</p>
<p><strong>Augmentation</strong><br>
GaussianNoise(p=0.5)<br>
GaussianSNR(p=0.5)<br>
FrequencyMask(min_frequency_band=0.0, max_frequency_band=0.2, p=0.3)<br>
TimeMask(min_band_part=0.0, max_band_part=0.2, p=0.8)<br>
PitchShift(min_semitones=-0.5, max_semitones=0.5, p=0.1)<br>
Shift(p=0.1)<br>
Gain(p=0.2)</p>
<p><strong>[inference]</strong><br>
stride=1<br>
framewise_output max<br>
No TTA (I used it in the final ensemble model)</p>
<p>Finally, I've uploaded the train_data_wav (sr=48000) and csv that I used. <br>
<a href="https://www.kaggle.com/shinoda18/rainforest-data" target="_blank">https://www.kaggle.com/shinoda18/rainforest-data</a></p> |
NFL 1st and Future - Impact Detection | 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: NFL 1st and Future - Impact Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thanks to the organisers of this competition, it was a very interesting task to solve!</p>
<p>My approach was very similar to the other top solutions: 2d detection of all helmets, tracking of helmets, 3d classification of crops and post processing to suppress false positives.</p>
<h1>Detection</h1>
<p>I used the YoloV5-l trained on 10k images using the full resolution.<br>
I started using EfficientDet based detector with modified set of anchors to better match the helmet size distribution and trained on video frames, but YoloV5 worked better.</p>
<h1>Helmets Tracking</h1>
<p>For each detected helmet, I found the optical flow between a few surrounding frames.<br>
I tried to use either OpenCV or RAFT (Thanks <a href="https://www.kaggle.com/daigohirooka" target="_blank">@daigohirooka</a> for the great notebook and referring RAFT). I used the optical flow to track helmets between frames and to estimate the average helmet velocity on the image plane over a few surrounding frames. I think RAFT worked slightly better but my top submit still used OpenCV for helmets tracking.</p>
<h1>2.5D Classification</h1>
<p>For classification I used 16x3x128x128 crops, scaled so the median helmet size over the current frame is mapped to the center 40 pixels. It provides the consistent scale, robust to detected bounding box variations, especially for partially visible helmets.</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F743064%2Fc22c2310d8795c4235fc1cc160c6eb99%2FScreenshot%20from%202021-01-07%2022-50-44.png?generation=1610023878290751&alt=media" alt=""></p>
<p>I also corrected for the linear helmet movement between frames. The current frame at 8th slice is always centered, but all the other frames are shifted using the current box velocity, estimated during the tracking stage. So when the player is running with the constant speed or camera is panning, the helmet stays at the frame center, but during acceleration it would move to and from center.</p>
<p>The intuition behind - the acceleration is important for classification, but it's harder to estimate on top of potentially fast movement due to camera movement.</p>
<p>For classification models, instead of 3d convolution I used the <a href="https://arxiv.org/pdf/1811.08383.pdf" target="_blank">Temporal Shift Module</a>:</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F743064%2F54a8a6bc002ffe63f1aa4ef207cacfd0%2Ftsm.png?generation=1610023740252006&alt=media" alt="Temporal Shift Module"></p>
<p>TSM has very little overhead comparing to N 2d models, can reuse any ImageNet pretrained 2d classification model and performed reasonably well for video understanding tasks.</p>
<p>I also had promising results with the <a href="https://arxiv.org/abs/2007.09933" target="_blank">MotionSqueeze: Neural Motion Feature Learning for Video Understanding</a> approach, which adds flow estimation to TSM based model, but the implementation is not trivial and does not have license specified.</p>
<p>I found small models with TSM added at the start of residual blocks work well and are usually easy and fast to train (from an hour to a few hours per model). I used the ensemble of EfficientNet B0-B3, Resnet18 and Resnet34. When comparing the TSM approach to 3d convolution, it's easy to notice the lack of pooling in the time dimension, so instead of shifting features by one frame, I shifted by 2 and 3 frames in the last blocks of resnets/efficient nets to mimic the dilated convolution.</p>
<p>During training I marked 3 frames around the impact as positive and used 5 or 10% positive samples.<br>
In addition to annotated training labels, I added the false positive prediction from a few undertrained detection models. I used 4 folds CV, for submission I averaged predictions of multiple models from all 4 <br>
folds. To speed up prediction, I ran classification on a few fast models first, to filter 95% of simple to predict negative samples.</p>
<h1>Post-Processing</h1>
<p>The postprocessing is quite simple, I select the detected/classified box with highest impact confidence and use flow/tracking information to suppress the detections for the same player for surrounding frames, with suppression decaying from the current confidence to 0 over 16 frames. I used the same threshold for all video files and frames.</p>
<p>I checked if such post-processing would suppress the positive samples using training dataset and found surprisingly significant amount of positive samples within 3-10 frames for the same player. Most of such sequential impacts were of the different type, for example helmet to helmet impact followed by helmet to body. To address this, I changed the classification model to predict the impact type as well, and suppressed the predicted impact type only. The score improvement was quite small, less than 0.01 estimated on local CV.</p> |
NFL 1st and Future - Impact Detection | 181th 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: NFL 1st and Future - Impact Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thank you for organizing this fun competition!</p>
<p>It didn't go well, but here's what i tried.</p>
<p>Extend the bbox<br>
In the provided bbox, it was difficult to distinguish between impact and not_impact, and I thought it would lead to false positives.</p>
<p>So I thought that extending the bbox would make it easier to distinguish between them, so I did four types of hand labels: Healmet, Shoulder, Body, and Ground.</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F4289810%2Ff8aae5f74fb6d393b69c6b9d4e7f91f8%2F2021-01-05%2016.02.18.png?generation=1609833984847349&alt=media" alt=""></p>
<p>In the case of Head, we hand-labeled the two helmets so that they are included.<br>
As shown in the figure, the detected impacts from the two models were compared, and if there were two or more detected impact with an IoU greater than 0.1, the top two impact were adopted as the impact.</p>
<p>If there was only one or no overlapping impacts, it was considered a false positive.<br>
By doing this, we thought we could prevent false detections of only one helmet in situations where there was no impact at all, or false detections of unrelated areas such as the ground, the player's body, and others.</p>
<p>I'm sure there were a lot of things I misunderstood, but thank you for reading.</p> |
Jane Street Market Prediction | RANK 119 - 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: Jane Street Market Prediction
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Here we go 😎<br>
-> Removed features which had high collinearity with others and used feature selection to keep the needful<br>
-> Used Optuna to get the best hyper-parameters!.<br>
-> Trained 5 XGB_models on 5 different targets #Multi-target<br>
-> Used tree-lite for faster inference (Was able to predict within 2:40 mins)</p>
<p>That's all 😂 </p>
<p><strong>Most surprising thing is that this was my first Kaggle competition and I had just started learning Machine Learning through YouTube and online courses.</strong></p>
<p><strong>I know it so simple!!!😁 There is nothing to boast about it</strong>. But I was quite happy because I had done this all within the first one-two months of learning ML and Kaggling.💛🧡. </p>
<p>Learnt a lot from this Jane Street competitions!!!</p>
<p>Here is the <strong>notebook</strong>🔽<br>
<a href="https://www.kaggle.com/oldwine357/janestreet-xgb-rank-80-73-362-314-317?scriptVersionId=62345420" target="_blank">https://www.kaggle.com/oldwine357/janestreet-xgb-rank-80-73-362-314-317?scriptVersionId=62345420</a></p>
<p>Most of all I would like to thank <a href="https://www.kaggle.com/code1110" target="_blank">@code1110</a>. For introducing the treelite, I wouldn't have done it without faster inference method.🧡</p>
<p><a href="https://www.kaggle.com/code1110/janestreet-faster-inference-by-xgb-with-treelite" target="_blank">https://www.kaggle.com/code1110/janestreet-faster-inference-by-xgb-with-treelite</a></p> |
Jane Street Market Prediction | 3217th -> 17th place simple LSTM model with custom loss function | 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: Jane Street Market Prediction
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>I was very surprised at how well my model is doing on the reruns given its final public LB score was only ~4000, so thought I would share my method!</p>
<p>It's a simple, small LSTM network where I've trained on the time series data by splitting it into chunks of between 5 and 10 time points - 7 in the submission.</p>
<p>The only explanation I can think of for the increase in relative performance on the rerun data is that I used a loss function that tries to penalise high variance in returns in a similar way to the utility function:<br>
$$L = - \sum_i p_i + \beta \sum_i p_i^2$$<br>
where <br>
$$p_i = \text{response}_i.\text{action}_i$$</p>
<p>and beta is a tunable parameter for the extent of the penalty.</p>
<p>Maybe as we get further from the training regime the variance of the models' responses increases and this loss function is able to prevent that to some extent by penalising 'risky' trades.</p>
<p>Here's the notebook:<br>
<a href="https://www.kaggle.com/scottishkimchi/lstm-with-custom-loss" target="_blank">https://www.kaggle.com/scottishkimchi/lstm-with-custom-loss</a></p> |
Cassava Leaf Disease Classification | Private 28th, Public 8th, Thank you all, my first medal! | 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: Cassava Leaf Disease Classification
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h2>✨ Result</h2>
<ul>
<li>Private: 28th, 0.901</li>
<li>Public: 8th, 0.908</li>
</ul>
<p>This competition is my first image classification competition,<br>
so many parts of my solution came from public notebooks and discussions in this competition.<br>
I've learnt many things from it.</p>
<p>Thank you for all kagglers and organizers for this competition.</p>
<p>And I'm happy to get a solo silver as my first medal!</p>
<h2>🔖 Solution</h2>
<p>I don't have a strong single model, but the ensemble has surprised me.</p>
<h3>🎨 Base Model</h3>
<ul>
<li>EfficientNet B4 with Noisy Student</li>
<li>SE-ResNeXt50 (32x4d)</li>
<li>Vision Transformer (base patch16)</li>
</ul>
<table>
<thead>
<tr>
<th>Train</th>
<th>Inference</th>
<th>Public LB</th>
<th>Private LB</th>
<th>CV</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="https://github.com/IMOKURI/Cassava-Leaf-Disease-Classification/blob/f639150116370039666b7bab452abd85932f4d24/cassava-training.ipynb" target="_blank">EfficientNet</a></td>
<td><a href="https://www.kaggle.com/imokuri/cassava-inference?scriptVersionId=52135491" target="_blank">EfficientNet-inf</a></td>
<td><strong>0.900</strong></td>
<td>0.891</td>
<td>0.89103</td>
</tr>
<tr>
<td><a href="https://github.com/IMOKURI/Cassava-Leaf-Disease-Classification/blob/fb7397ca97d624eb4db467c3d67a4c492313aaad/cassava-training.ipynb" target="_blank">SE-ResNeXt50</a></td>
<td><a href="https://www.kaggle.com/imokuri/cassava-inference?scriptVersionId=52812836" target="_blank">SE-ResNeXt50-inf</a></td>
<td>0.899</td>
<td>0.894</td>
<td><strong>0.89532</strong></td>
</tr>
<tr>
<td><a href="https://github.com/IMOKURI/Cassava-Leaf-Disease-Classification/blob/9b7093ed7501254f7705edd31f96467f2be00d8b/cassava-training.ipynb" target="_blank">ViT</a></td>
<td><a href="https://www.kaggle.com/imokuri/cassava-inference?scriptVersionId=52893502" target="_blank">ViT-inf</a></td>
<td>0.899</td>
<td>0.890</td>
<td>0.89220</td>
</tr>
</tbody>
</table>
<h3>🐎 Ensemble and TTA</h3>
<p>I tried weighted average of no TTA and TTA.</p>
<table>
<thead>
<tr>
<th>Inference</th>
<th>Validation</th>
<th>TTA</th>
<th>Public LB</th>
<th>Private LB</th>
<th>CV</th>
<th>TTA weight</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="https://www.kaggle.com/imokuri/cassava-inference?scriptVersionId=54132321" target="_blank">inf-no-TTA</a></td>
<td><a href="https://github.com/IMOKURI/Cassava-Leaf-Disease-Classification/blob/f7143beaf5c25829e686f94162cdfa7d0d88d7b1/cassava-validation.ipynb" target="_blank">val-no-TTA</a></td>
<td>noTTA</td>
<td>0.905</td>
<td>0.896</td>
<td>0.9429</td>
<td>-</td>
</tr>
<tr>
<td><a href="https://www.kaggle.com/imokuri/cassava-inference?scriptVersionId=54141945" target="_blank">inf-TTA</a></td>
<td>-</td>
<td>noTTA + TTAx6</td>
<td>0.907</td>
<td>0.899</td>
<td>-</td>
<td>6:6</td>
</tr>
<tr>
<td><a href="https://www.kaggle.com/imokuri/cassava-inference?scriptVersionId=54244968" target="_blank">inf-TTA-weight</a></td>
<td>-</td>
<td>noTTA + TTAx6</td>
<td><strong>0.908</strong></td>
<td>0.900</td>
<td>-</td>
<td>4:6</td>
</tr>
</tbody>
</table>
<p>I decided TTA weight by the public LB score, So I think this may overfit to public LB.<br>
I choose second final submission is average of no TTA and TTA.</p>
<table>
<thead>
<tr>
<th>Inference</th>
<th>Validation</th>
<th>TTA</th>
<th>Public LB</th>
<th>Private LB</th>
<th>CV</th>
<th>TTA weight</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="https://www.kaggle.com/imokuri/cassava-inference/execution?scriptVersionId=54503857" target="_blank">inf-TTA-avg</a></td>
<td>-</td>
<td>noTTA + TTAx9</td>
<td>0.908</td>
<td>0.901</td>
<td>-</td>
<td>9:9</td>
</tr>
</tbody>
</table>
<h2>✏️ Memo</h2>
<p>I've used following techniques for this competition.</p>
<h3>🍃 Datasets</h3>
<ul>
<li><a href="https://www.kaggle.com/piantic/train-cassava-starter-using-various-loss-funcs/notebook" target="_blank">Use 2019 datasets</a></li>
</ul>
<h3>🛠️ Preprocessing</h3>
<ul>
<li><a href="https://www.kaggle.com/c/cassava-leaf-disease-classification/discussion/207450" target="_blank">Image size 512 ~ 384</a></li>
<li><a href="https://www.kaggle.com/khyeh0719/pytorch-efficientnet-baseline-train-amp-aug#Define-Train\Validation-Image-Augmentations" target="_blank">Additional augumentations</a><ul>
<li><a href="https://www.kaggle.com/c/cassava-leaf-disease-classification/discussion/212347" target="_blank">No augmentation for first few epochs.</a></li>
<li>Reduce augmentation for last few epochs.</li>
<li>Remove augmentation for final epoch.</li>
<li><a href="https://www.kaggle.com/c/cassava-leaf-disease-classification/discussion/209065" target="_blank">CutMix</a></li>
<li><a href="https://www.kaggle.com/c/cassava-leaf-disease-classification/discussion/212060" target="_blank">MixUp</a></li></ul></li>
</ul>
<h3>📉 Loss</h3>
<ul>
<li><a href="https://www.kaggle.com/c/cassava-leaf-disease-classification/discussion/202017" target="_blank">Bi-Tempered Logistic Loss</a><ul>
<li><a href="https://www.kaggle.com/piantic/train-cassava-starter-using-various-loss-funcs/notebook#Bi-Tempered-Loss" target="_blank">with label smoothing</a></li></ul></li>
</ul>
<h3>🏃 Training</h3>
<ul>
<li><a href="https://keras.io/examples/vision/image_classification_efficientnet_fine_tuning/#tips-for-fine-tuning-efficientnet" target="_blank">batch normalization layers frozen for EfficientNet</a><ul>
<li>also vision transformer.</li></ul></li>
<li>Gradient accumulation for increasing batch size.</li>
<li><ul>
<li></li></ul></li>
</ul>
<h3>🚀 Inference</h3>
<ul>
<li>Random seed ensemble.</li>
<li><a href="https://www.kaggle.com/khyeh0719/pytorch-efficientnet-baseline-inference-tta" target="_blank">TTA(Test Time Augmentation)</a><ul>
<li><a href="https://www.kaggle.com/c/cassava-leaf-disease-classification/discussion/214559#1171803" target="_blank">10 is the minimum number to establish a stable result.</a></li></ul></li>
<li><a href="https://www.kaggle.com/c/cassava-leaf-disease-classification/discussion/210921#1153396" target="_blank">Include original image on TTA.</a><ul>
<li>Weighted ensemble of original image inference and augmented one.</li></ul></li>
<li><a href="https://www.kaggle.com/c/cassava-leaf-disease-classification/discussion/206489" target="_blank">Light augmentation for inference</a></li>
</ul>
<h3>💡 Tips</h3>
<ul>
<li><a href="https://www.kaggle.com/c/cassava-leaf-disease-classification/discussion/207450" target="_blank">A few things for easy start</a></li>
<li><a href="https://www.kaggle.com/c/cassava-leaf-disease-classification/discussion/203594" target="_blank">Sharing some improvements and experiments</a></li>
<li><a href="https://www.kaggle.com/c/cassava-leaf-disease-classification/discussion/208402" target="_blank">Important points to boost the LB score</a></li>
<li><a href="https://www2.slideshare.net/RyuichiKanoh/practical-tips-for-handling-noisy-data-and-annotaiton-204195412" target="_blank">Practical tips for handling noisy data and annotaiton</a></li>
</ul>
<p>Thank you again. I will try to be expert next competition!</p> |
Cassava Leaf Disease Classification | 375th place private LB (278th place 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: Cassava Leaf Disease Classification
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>So, after the latest updates, I moved up a few places on the LB and slipped into the bronze medals. Within two days I've gone from zero medals to my second bronze medal. 😃 On this competition, I worked on my own, while on the Rainforest Connection Species Audio Detection competition](<a href="https://www.kaggle.com/c/rfcx-species-audio-detection" target="_blank">https://www.kaggle.com/c/rfcx-species-audio-detection</a>) I had the pleasure to work with a great team. So, I thought I'd write up some of the more interesting things I tried on this competition.</p>
<p>My best selected solution was a weighted power averaging ensemble (i.e. squaring the predictions of each model and then averaging, followed by picking the class with the highest score) of</p>
<ul>
<li><strong>EfficientNet-B5</strong> (i.e. not noisy student, somehow my noisy student version seemed worse on CV - I failed to figure out why) on image size 456 by 456 with TTA</li>
<li><strong>EfficientNet-B4-noisy student</strong> on image size 512 by 512 with TTA</li>
<li><strong>ResNeXt-50 (32x4d)</strong> with image size 512 by 512</li>
<li><strong>Vision Transformer</strong> (<code>vit_base_patch16_224</code>) image size 224 by 224</li>
</ul>
<p>I did two different test-time augmentation approaches for the two EfficientNets and no TTA for the others (yes, yes, I clearly have an EfficientNet bias).</p>
<p><strong>Things that worked</strong>:</p>
<ul>
<li><strong>label smoothing cross-entropy</strong> with epsilon of 0.1 to 0.2 or so as a loss function (not surprising, given that it was originally proposed for noisy labels)</li>
<li><strong>focal loss</strong> (not in my selected solutions, but in CV it was very similar to label smoothing cross-entropy)</li>
<li><strong>Ensembling</strong> (not surprise there, either)<ul>
<li><strong>Power averaging</strong> was behind my best selected submission. This looked somewhat promising on CV and not that bad on the public LB (while I selected a weighted arithmetic mean based on LB, which did worse - in part, I also just wanted to select a second submission that was not too similar to the other one). </li>
<li>I got some even better private LB numbers with <strong>rank averaging</strong> (in silver territory, but I did not select it), but admittedly my very best private LB score was a simple weighted arithmetic mean of two of the models. See below for what did not work so well (i.e. selection the best submission)…</li>
<li>Why did I think power and rank averaging would work? I kind of figured that accuracy is in some sense a rank based metric (you only care about the first rank of course) and those methods had just been helpful in the <a href="https://www.kaggle.com/c/rfcx-species-audio-detection" target="_blank">Rainforest Connection Species Audio Detection competition</a> that used mean average precision (a very rank based metric).</li></ul></li>
<li>Using <strong>diverse models</strong> in my ensemble, even if it does hurt on the public LB (I hedged my bets a bit and tried to bet on a half-way house that probably relied on the public LB to much, which cost me a bit in ranks).<ul>
<li>The idea was to have diverse image sizes as inputs, somewhat diverse models and diverse augmentations during training (and TTA).</li>
<li>Nevertheless, it seems the two EfficientNets were different enough that having both helped. I probably would not have added the EfficientNet-B4-NS, if it had not been for the public LB score of <a href="https://www.kaggle.com/japandata509/ensemble-resnext50-32x4d-efficientnet-0-903" target="_blank">this notebook</a>. That notebook also made me stop trying other ResNet-types and just go with ResNeXt-50 (32x4d) (who knows whether that was the right decision).</li>
<li>My choice of architectures was perhaps a bit limited I mostly picked these architectures based on what I could get as pre-trained models via <code>timm</code> and perhaps payed too much attention to what others did. </li></ul></li>
<li><strong>Gradient accumulation</strong> to use bigger batch sizes (72) with EfficientNet-B5 (necessary when using a GPU on Kaggle or my own 1080-Ti). It appeared to help a tiny bit in CV to use a batch size >32 despite the whole "<a href="https://twitter.com/ylecun/status/989610208497360896?lang=en" target="_blank">Friends dont let friends use minibatches larger than 32</a>" <a href="https://arxiv.org/abs/1804.07612" target="_blank">thing</a>.</li>
<li><strong>flat learning rate before cosine annealing learning rate schedule</strong> that I learnt about from <a href="https://www.kaggle.com/abhishek/tez-faster-and-easier-training-for-leaf-detection" target="_blank">Abishek Thakur's notebook</a></li>
<li>Weight decay - whenever I tried it, it helped.</li>
<li><code>fastai</code> + <code>timm</code> as e.g. described in this <a href="https://www.kaggle.com/muellerzr/recreating-abhishek-s-tez-with-fastai" target="_blank">great notebook</a> by <a href="https://www.kaggle.com/muellerzr" target="_blank">@muellerzr</a> (thanks, again, for that nice starter kit) and PyTorch. You only appreciate how smoothly that works with CPU and GPU when you try to use the TPU with PyTorch, which kind of worked, but was a bit painful.</li>
</ul>
<p><strong>Things that did not work for me (mostly my fault, some of these clearly worked out better for others):</strong></p>
<ul>
<li>Selecting the best submissions - I did 27 submission before the deadline and I selected in terms of the private LB the 17th and 20th best of these.<ul>
<li>I suspect I was not sufficiently disciplined with running everything I tried in the last few days through a proper CV (yes, yes, I know, that's a terrible sin…) and was too influenced by the public LB.</li>
<li>I wonder whether those that did best that were super disciplined and perhaps even used repeated k-fold?! </li>
<li>To some extent the ordering of my various submissions may have had a strong element of luck (accuracy is such a low information content metric and I did not manage to) and dropping 97 places is not that bad, but I aspire to do better next time.</li></ul></li>
<li>Getting value out of the 2019 competition data, but I probably just invested insufficient time. It just always made my CV worse even after de-duplication, so I gave up.</li>
<li>Stochastic weight averaging: it kept reliably improving my loss function in CV, but not accuracy (it seemed I got the best accuracy when very slightly overfitting in terms of (label-smoothing) cross-entropy - which I understand is sort of expected). I wonder whether I should nevertheless put a model with SWA in my ensemble.</li>
<li>Really large models: I initially thought that the biggest EfficientNet I could train with TPU would be best, then I scaled my "ambitions" back to the largest one I could comfortably cross-validate (B5) some experiments for… </li>
<li>Doing two competitions that ended within 24 hours of each other. Yes, I got two medals, but I am left feeling I would have liked to rather do one of them more deeply and do a better job / contribute more to the one where I teamed up.</li>
</ul> |
Cassava Leaf Disease Classification | Private LB 105th / Public LB 970th solution and first medal 🥳 | 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: Cassava Leaf Disease Classification
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>First of all, congratulations to all the competitors. Huge thanks to Kaggle, Makerere University AI Lab for organising this competition. <br>
I'd also like to thank my amazing teammate, <a href="https://www.kaggle.com/kjkr73" target="_blank">@kjkr73</a>. He did most of the heavy lifting. He'll be publishing a kernel soon.</p>
<p>⚠ We actually jumped to 105. :)</p>
<h2>Data</h2>
<ul>
<li>We only used the competition data.</li>
</ul>
<h2>Validation Strategy</h2>
<ul>
<li>Stratified 5-fold.</li>
<li>My CV score and LB score were correlated from the very start so I didn't worry about it too much.</li>
<li>Trusted our CV but didn't disregard Public LB entirely.</li>
</ul>
<h2>Image Preprocessing And Augmentations</h2>
<ul>
<li>We trained models on 224*224, 256*256, 384*384 and 512*512 image size. Larger image size always had better scores.</li>
<li>We tried multiple combinations of augmentations. Following combinations performed the best:<ul>
<li>Cutout, HorizontalFlip, VerticalFlip, ShiftScaleRotate, HueSaturationValue, RandomBrightnessContrast.</li>
<li>Cutout, CoarseDropout, HorizontalFlip, VerticalFlip.</li></ul></li>
</ul>
<h2>Neural Network Architectures</h2>
<ul>
<li>We tried ResNet34, ResNext50_32x4d, EfficientNet B1 NS, EfficientNet B3 NS, EfficientNet B4 NS, ViT-Base patch 16, and DeiT-Base patch 16 224.</li>
</ul>
<h2>Miscellaneous</h2>
<ul>
<li>Loss(es):<ul>
<li>Bi-tempered loss with label smoothing</li>
<li>Taylor Crossentropy with label smoothing</li></ul></li>
<li>Optimizer:<ul>
<li>Adam</li></ul></li>
<li>LR Scheduler(s):<ul>
<li>OneCycleLR</li>
<li>CosineAnnealingWarmRestarts</li></ul></li>
<li>Hardware/ platform:<ul>
<li>Kaggle kernels</li></ul></li>
</ul>
<h2>Final Submissions</h2>
<ul>
<li>Selected Submission 1 (Private 0.8999, Public 0.9009) is a blend of:<ul>
<li>EfficientNet B1 NS on 512*512 image size [1xTTA].</li>
<li>ResNext50_32x4d on 512*512 image size [1xTTA].</li>
<li>ResNext50_32x4d on 512*512 image size [No TTA].</li>
<li>EfficientNet B3 NS on 512*512 image size [No TTA]. </li></ul></li>
<li>Selected Submission 2 (Private 0.8981, Public 0.9002) is a blend of:<ul>
<li>EfficientNet B1 NS on 512*512 image size [1xTTA].</li>
<li>ResNext50_32x4d on 512*512 image size [No TTA].</li>
<li>EfficientNet B3 NS on 512*512 image size [No TTA]. </li></ul></li>
</ul>
<h2>Some observations/ tips for competing in a CV comp with Kaggle Kernels only:</h2>
<ul>
<li>Data preprocessing != data augmentation. Resize images to the intended size before training, it will save you some GPU quota and speed up your experiments. Credits: <a href="https://www.kaggle.com/cdeotte" target="_blank">@cdeotte</a>; read more <a href="https://www.kaggle.com/c/siim-isic-melanoma-classification/discussion/161446" target="_blank">here</a>.</li>
<li>Create a proof of concept kernel which is essentially a smaller version of the training kernel for fast experimentation or to check the feasibility of an idea. This kernel should run quickly and return an OOF CV score. You can make this kernel fast with a smaller number of CV folds/ smaller number of epochs. If you see improvement in this CV score, copy the config and run it on your training kernel.</li>
<li>Write modular, maintainable, and readable code.</li>
</ul>
<h2>Credits</h2>
<ul>
<li><code>pandas</code> <a href="https://github.com/pandas-dev/pandas" target="_blank">https://github.com/pandas-dev/pandas</a></li>
<li><code>torch</code> <a href="https://github.com/pytorch/pytorch" target="_blank">https://github.com/pytorch/pytorch</a></li>
<li><code>timm</code> <a href="https://github.com/rwightman/pytorch-image-models" target="_blank">https://github.com/rwightman/pytorch-image-models</a>.</li>
<li><code>albumentations</code> <a href="https://github.com/albumentations-team/albumentations" target="_blank">https://github.com/albumentations-team/albumentations</a></li>
<li><code>lycon</code> <a href="https://github.com/ethereon/lycon" target="_blank">https://github.com/ethereon/lycon</a></li>
</ul>
<p>PS: This is our (my and <a href="https://www.kaggle.com/kjkr73" target="_blank">@kjkr73</a>'s) first medal 🥳<br>
Edit: Updated LB scores and rank.</p> |
Rainforest Connection Species Audio Detection | 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: Rainforest Connection Species Audio Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h2>Overview</h2>
<p>I trained simple classification models (24 binary classes) with logmel spectrograms :</p>
<ol>
<li>bootstrap stage: models are trained on TP/FP with masked BCE loss</li>
<li>generate soft pseudo labels with 0.5 second sliding window </li>
<li>train models with pseudo labels and also sample (with p=0.5) places with TP/FP - this partially solves confirmation bias problem. </li>
</ol>
<p>Rounds of pseudo labeling and retraining (points 2,3) were repeated until the score on public LB didn't improve. Depending on the settings it took around 4-10 rounds to converge.</p>
<p>My initial models that gave 0.86 on TP/FP alone easily reached 0.96x with pseudo labeling . After this success I gave this challenge a 5 weeks break as I lost any motivation to improve my score :)<br>
Later to my surprise it was extremely hard to beat 0.97 even with improved first stage models.</p>
<h2>Melspectrogram parameters</h2>
<ul>
<li>256 mel bins</li>
<li>512 hop length</li>
<li>original SR</li>
<li>4096 nfft</li>
</ul>
<h2>FreqConv (CoordConv for frequency)</h2>
<p>After my first successful experiment with pseudo labeling that reached 0.969 on public LB I tried to just swap encoders and blend models but this did not bring any improvements. <br>
So I visualised the data for different classes and understood that when working with mel spectrograms for this task we don’t need translation invariance and classes really depend on both frequency and patterns.<br>
I added a channel to CNN input which contains the number of mel bin scaled to 0-1. This significantly improved validation metrics and after this change log loss on crops around TP after the first round of training with pseudo labels was around 0.04 (same for crops around FP). Though it only slightly improved results on the LB.</p>
<h2>First stage</h2>
<p>For the first stage I used all tp/fp information without any sampling and made crops around the center of the signal.</p>
<p><strong>Augmentations</strong></p>
<ul>
<li>time warping</li>
<li>random frequency masking below TP/FP signal</li>
<li>random frequency masking above TP/FP signal</li>
<li>gaussian noise</li>
<li>volume gain</li>
<li>mixup on spectrograms</li>
</ul>
<p>For mixup on spectrograms - I used constant alpha (0.5) and hard labels with clipping (0,1). Masks were also added. </p>
<h2>Pseudolabeling stages</h2>
<p>Sampled TP/FP with p=0.5 otherwise made a random crop from the full spectrogram. </p>
<p>Without TP/FP sampling labels can become very soft and the score decreases after 2 or 3 rounds.<br>
After training 4 folds of effnet/rexnet I generated OOF labels and ensembled their predictions. Then the training is repeated from scratch.</p>
<p><strong>Augmentations</strong></p>
<ul>
<li>gaussian noise</li>
<li>volume gain</li>
<li>mixup </li>
<li>time warping</li>
<li>spec augment</li>
<li>mixup on spectrograms</li>
</ul>
<p><strong>Mixup</strong></p>
<p>I used constant alpha (0.5) and added soft labels from two samples. This hurts logloss on FP a bit but at the same time significantly increases recall on TP.</p>
<h2>Validation</h2>
<p>Local validation did not have high correlation with the public leaderboard. Logloss on TP was somehow correlated but still it was not robust. <br>
So without proper validation I decided to not select the best checkpoints and just trained 60 epochs (around 200 batches in each epoch) with CosineLR and AdamW optimizer.</p>
<p>My best models on validation - auc 0.999, log loss 0.03 did not produce great results (0.95). After the competition though It turned out that they can be easily improved with postprocessing to 97x-98x range.</p>
<h2>Final ensemble</h2>
<p>I used 4 models with 4 folds from Effnet and Rexnet (<a href="https://arxiv.org/abs/2007.00992" target="_blank">https://arxiv.org/abs/2007.00992</a> lightweight models with great performance) families:</p>
<ul>
<li>Rexnet-200 (4 sec training/inference), EffnetB3 (4 sec training/inference)</li>
<li>Rexnet-150 (8 sec training/inference), EffnetB1 (8 sec training/inference)</li>
</ul>
<p>Rexnet was much better than EfficientNet alone (less overfitting), but in ensemble they worked great.</p>
<p>During inference I just used 0.5 second sliding window and took max probabilities for the full clip and then averaged predictions from different models.</p>
<h2>Lessons learned</h2>
<p>I did not know about the paper and lacked this useful information about the dataset.</p>
<p>In my solutions I often rely on models alone but don’t explore the data deeply. <br>
In this case I understood that the relabeled train set has similar class distribution to the test set and decided that models would easily learn that. I was wrong and simple post-processing could significantly improve results (though this happened due to severe class imbalance). </p> |
Rainforest Connection Species Audio Detection | 5th place solution (Training 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: Rainforest Connection Species Audio Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h1>5th place solution (Training Strategy)</h1>
<p>Congratulations to all the participants, and thanks a lot to the organizers for this competition! This has been a very difficult but fun competition:)</p>
<p>In this thread, I introduce our approach about training strategy.<br>
About ensemble part will be written by my team member.</p>
<p>Our team ensemble each best model.</p>
<p>My model is Resnet18 which has a SED header. This model's LWLRAP is Public LB=0.949 /Private LB=0.951, and I trained by google colab using <a href="https://www.kaggle.com/c/rfcx-species-audio-detection/discussion/198048" target="_blank">Theo Viel's npz dataset</a>(32 kHz, 128 mels). Thank you, Theo Viel!!</p>
<p>Our approach has 3 stage, <br>
Other team members are different in some things likes the base model and hyperparameter, but these default strategies are about the same.</p>
<h2>1st stage: pre-train</h2>
<p><em>※I think this part is not important. Team member Ahmet skips this part.</em></p>
<p>This stage transfers learning from Imagenet to spectograms.</p>
<p>Theo Viel's npz dataset can be regarded as 128x3751 size image.<br>
I cut to 512 by this image in sound point from t_min and t_max.<br>
I train this image by tp_train and 30 sampled fp_train.</p>
<p>Parameters:</p>
<ul>
<li>Adam</li>
<li>learning_rate=1e-3</li>
<li>CosineAnnealingLR(max_T=10)</li>
<li>epoch=50</li>
</ul>
<p>Continue 2nd and 3rd stage use this trained weight.</p>
<h2>2nd stage: pseudo label re-labeling</h2>
<p>The purpose of stage2 is to improve the model and make pseudo labels by this model.</p>
<p>Use 1st stage trained weight.</p>
<p>The key point I think is to calculate gradient loss only labeled frame. The positive labels were sampled from tp_train.csv only and the negative labels were sampled from fp_train.csv only.<br>
I put 1 to positive label and -1 to negative label.</p>
<pre><code>tp_dict = {}
for recording_id, df in train_tp.groupby("recording_id"):
tp_dict[recording_id+"_posi"] = df.values[:, [1,3,4,5,6]]
fp_dict = {}
for recording_id, df in train_fp.groupby("recording_id"):
fp_dict[recording_id+"_nega"] = df.values[:, [1,3,4,5,6]]
def extract_seq_label(label, value):
seq_label = np.zeros((24, 3751)) # label, sequence
middle = np.ones(24) * -1
for species_id, t_min, f_min, t_max, f_max in label:
h, t = int(3751*(t_min/60)), int(3751*(t_max/60))
m = (t + h)//2
middle[species_id] = m
seq_label[species_id, h:t] = value
return seq_label, middle.astype(int)
# extract positive label and middle point
fname = "00204008d" + "_posi"
posi_label, posi_middle = extract_seq_label(tp_dict[fname], 1)
# extract negative label and middle point
fname = "00204008d" + "_nega"
nega_label, nega_middle = extract_seq_label(fp_dict[fname], -1)
</code></pre>
<p>loss function is that:</p>
<pre><code>def rfcx_2nd_criterion(outputs, targets):
clipwise_preds_att_ti = outputs["clipwise_preds_att_ti"]
posi_label = ((targets == 1).sum(2) > 0).float().to(device)
nega_label = ((targets == -1).sum(2) > 0).float().to(device)
posi_y = torch.ones(clipwise_preds_att_ti.shape).to(device)
nega_y = torch.zeros(clipwise_preds_att_ti.shape).to(device)
posi_loss = nn.BCEWithLogitsLoss(reduction="none")(clipwise_preds_att_ti, posi_y)
nega_loss = nn.BCEWithLogitsLoss(reduction="none")(clipwise_preds_att_ti, nega_y)
posi_loss = (posi_loss * posi_label).sum()
nega_loss = (nega_loss * nega_label).sum()
loss = posi_loss + nega_loss
return loss
</code></pre>
<p>And image are cut and stack by sliding window.<br>
I set the window size to 512 and cut out the entire range of 60's audio data by covering it little by little. Cover 49 pixels each, considering that important sounds may be located at the boundaries of the division.</p>
<pre><code>N_SPLIT_IMG = 8
WINDOW = 512
COVER = 49
slide_img_pos = [[0, WINDOW]]
for idx in range(1, N_SPLIT_IMG):
h, t = slide_img_pos[idx-1][0], slide_img_pos[idx-1][1]
h = t - COVER
t = h + WINDOW
slide_img_pos.append([h, t])
print(slide_img_pos)
# [[0, 512], [463, 975], [926, 1438], [1389, 1901], [1852, 2364], [2315, 2827], [2778, 3290], [3241, 3753]]
</code></pre>
<p>I predict each sliding window and put the pseudo label, so I got 8 windows in one 60 sec recording.</p>
<table>
<thead>
<tr>
<th>patch idx</th>
<th>pixcel</th>
<th>time(s)</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>0〜512</td>
<td>0〜8</td>
</tr>
<tr>
<td>1</td>
<td>463〜975</td>
<td>7〜15</td>
</tr>
<tr>
<td>2</td>
<td>926〜1438</td>
<td>14〜23</td>
</tr>
<tr>
<td>3</td>
<td>1389〜1901</td>
<td>22〜30</td>
</tr>
<tr>
<td>4</td>
<td>1852〜2364</td>
<td>29〜37</td>
</tr>
<tr>
<td>5</td>
<td>2315〜2827</td>
<td>37〜45</td>
</tr>
<tr>
<td>6</td>
<td>2778〜3290</td>
<td>44〜52</td>
</tr>
<tr>
<td>7</td>
<td>3241〜3753</td>
<td>51〜60</td>
</tr>
</tbody>
</table>
<p>Parameters:</p>
<ul>
<li>Adam</li>
<li>learning_rate=3e-4</li>
<li>CosineAnnealingLR(max_T=5)</li>
<li>epoch=5</li>
</ul>
<h2>3rd stage: train by label re-labeled</h2>
<p>This stage trains on the new labels re-labeled by 2nd stage model.</p>
<p>Use 1st stage trained weight.</p>
<p>The new label is ensemble by our team output like my 2nd stage.</p>
<ul>
<li>our prediction average value is<ul>
<li><code>>0.5</code>: soft positive = 2</li>
<li><code><0.01</code>: soft negative = -2</li></ul></li>
</ul>
<p>In this stage, I calculate gradient loss only labeled frame as with 2nd stage. </p>
<p>Parameters:</p>
<ul>
<li>Adam</li>
<li>learning_rate=3e-4</li>
<li>CosineAnnealingLR(max_T=5)</li>
<li>epoch=5</li>
</ul>
<p>Some My Tips:</p>
<ul>
<li>Don't use soft negative.</li>
<li>The re-label's loss(soft positive) is weighted 0.5.</li>
<li>last layer mixup(from <a href="https://medium.com/analytics-vidhya/better-result-with-mixup-at-final-layer-e9ba3a4a0c41" target="_blank">this blog</a>)</li>
</ul>
<h2>CV</h2>
<p>I use <a href="https://github.com/trent-b/iterative-stratification" target="_blank">iterative-stratification</a>'s MultilabelStratifiedKFold. Validation data is made from tp_train only and fp_train data is used training in all fold.</p>
<p>Each stage LWLRAP is that:</p>
<table>
<thead>
<tr>
<th>stage</th>
<th>CV</th>
<th>Public</th>
<th>Private</th>
</tr>
</thead>
<tbody>
<tr>
<td>1st</td>
<td>0.7889</td>
<td>0.842</td>
<td>0.865</td>
</tr>
<tr>
<td>2nd</td>
<td>0.7766</td>
<td>0.874</td>
<td>0.878</td>
</tr>
<tr>
<td>3rd</td>
<td>0.7887</td>
<td>0.949</td>
<td>0.951</td>
</tr>
</tbody>
</table>
<p>3rd stage's re-labeled LWRAP is 0.9621.</p>
<h2>predict</h2>
<p>In test time, I increase COVER to 256, so I got 14 windows in one 60 sec recording.<br>
The prediction is max pooling in each patch.</p>
<p>I use clipwise_output in training, and I use framewise_output in prediction. This approach came from <a href="https://www.kaggle.com/c/rfcx-species-audio-detection/discussion/209684" target="_blank">shinmura0's discussion thread</a>. Thank you shinmura0:)</p>
<h2>did not work for my model</h2>
<ul>
<li>TTA</li>
<li>26 classes (divide song_type)</li>
<li>label wright loss</li>
<li>label smoothing(but team member's kuto improved)</li>
</ul>
<hr>
<p>Finally, I would like to thank the team members.<br>
If I was alone, I couldn't get these result.<br>
kuto, Ahmet, thank you very much.</p>
<p>My code:<br>
<a href="https://github.com/trtd56/RFCX" target="_blank">https://github.com/trtd56/RFCX</a></p> |
Cassava Leaf Disease Classification | public 87th -> private 668th very bad solution for remembering sad memory... | 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: Cassava Leaf Disease Classification
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Firstly, congratulation to all competitors!</p>
<p>This is my regret for large shake down.</p>
<p>I used 3 type CNN.</p>
<ol>
<li>SEResNext50 32x_4d public : 0.898 -> private : 0.895</li>
<li>EfficientNetB4 public : 0.899 -> private : 0.890 </li>
<li>ViT_base_384 public : 0.899 -> private : 0.890</li>
</ol>
<p>In final, I weights each model with 1 : 1.2 : 1.2 for ensemble.</p>
<ul>
<li>Public LB : 0.905</li>
<li>Private LB : 0.896</li>
</ul>
<p>I regret to overfit to public LB…</p>
<p>I thought this competition is my first silver, but result is reflecting my current ability.</p>
<p>And, I think the cause of weak model is below</p>
<ul>
<li>using cutmix</li>
<li>don't use tempered loss</li>
<li>fixed random seed for cv through all model</li>
</ul>
<p>I doubt seed ensemble can help me a little, but the bird has flown :(</p>
<p>The ensemble SEResNeXt50_32x4d + SEResNet152d_320</p>
<ul>
<li>Public LB : 0.900</li>
<li>Pirvate LB : 0.899</li>
</ul>
<p>The ensemble 1SEResNext50 32x_4d + EfficientNetB4 + ViT_base_384 (public:0.895, private:0.891) </p>
<ul>
<li>Public LB : 0.902</li>
<li>Pirvate LB : 0.899</li>
</ul>
<p>These model can get medal zone private score, but I don't know why bad score ViT is essential for good score. This competition definiely needs for early stopping for not perfect fitting training data?</p>
<p>Please tell me how do you think cutmix , tempered loss, seed and so on and your preventing shake method.</p> |
NFL 1st and Future - Impact Detection | 9th Place - 2D Detection 3D 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: NFL 1st and Future - Impact Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h1>Overview</h1>
<p>Our solution (like a lot of other teams) consists of a two-step pipeline (detection and classification) followed by some post-processing. We use 2D detection to find possible impact boxes, and then we use 3D classification to determine which boxes are impacts. </p>
<h1>Using 2D, Is This a Helmet Impact?</h1>
<p>Our detection model finds the yellow box as a possible helmet impact.<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1723677%2F941a0e534d355b76997947feae189af8%2Fquiz.png?generation=1609887772117223&alt=media" alt=""><br>
From only 2D it is impossible to know whether these helmets are about to impact. It appears probable but maybe the silver helmet is about to pass behind the white helmet.</p>
<h1>Using 3D, Is This a Helmet Impact?</h1>
<p>Our classification model uses frames before and after this frame. With this information, our classification model correctly identifies that these two helmets do not impact but rather pass by each other. <br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1723677%2F681af4fc454c479b02a760dc82480396%2Fframes.png?generation=1609887810082337&alt=media" alt=""></p>
<h1>Impact Detection Model</h1>
<p>(written by <a href="https://www.kaggle.com/jinssaa" target="_blank">@jinssaa</a>)</p>
<p>We used DetectoRS(ResNeXt-101-32x4d) model for detecting impacts. <a href="https://github.com/open-mmlab/mmdetection" target="_blank">https://github.com/open-mmlab/mmdetection</a> This model was built in two steps:</p>
<p>Helmet Detection Model for warm-up: We trained a Helmet Detection Model for 12 epochs using the train helmet dataset which is in the image folder, this model shows 'bbox_mAP_50', 0.877 validation score.<br>
2-Class Detection Model: We used the final weights of the Helmet Detection Model (as pretrained weights) to build a Helmet/Impact Detection model. We benched <a href="https://www.kaggle.com/tito" target="_blank">@tito</a>'s notebook and set +- 4 frames from impact as impact class.<br>
Using the Helmet Detection Model as pretrained weight makes the 2-Class Model converge much faster and detect impacts easier.</p>
<p>This approach showed good performance to detect impact. We set the confidence score up to 0.9 which showed 0.39 public LB score after a simple post processing (without any classifiers). Then, we set a lower confidence score to catch more true positives after we plug in the classifier. DetectoRS showed good performance to detect impact but it took a long time to test our ideas.</p>
<h1>Impact Classification Model</h1>
<p>(written by <a href="https://www.kaggle.com/theoviel" target="_blank">@theoviel</a>)</p>
<h3>2D Models</h3>
<p>I kept struggling with improving my EfficientDet models as I had no experience with object detection, I figured out it would be better to go back to what I can do : classification models. The main idea was that a crop around a helmet has the same information regarding whether it is an impact or not as the whole image. <br>
Therefore, I extracted a 64x64 crop around all the boxes in the training data and started building models to predict whether a crop had an impact. To tackle imbalance, I used the [-4, +4] extended label as a lot of people did. After a few tweaking, I had a bunch of models with a 0.9+ AUC (5 folds stratified by gameplay) : Resnet-18 & 34, EfficientNet b0 -> b3. </p>
<p>Tricks used for 2D models include :<br>
Limiting the number of boxes sampled per player at each epoch, in order to have more control on convergence<br>
Linear learning rate scheduling with warmup<br>
Removing the stride of the first layer : 64x64 is a small image size and it’s better not to decrease the network resolution too fast<br>
Stochastic Weighted Averaging<br>
Classical augmentations </p>
<p>Then, I used <a href="https://www.kaggle.com/tjungblut" target="_blank">@tjungblut</a>’s detector (<a href="https://www.kaggle.com/c/nfl-impact-detection/discussion/200995" target="_blank">https://www.kaggle.com/c/nfl-impact-detection/discussion/200995</a>) to benchmark how bad my models were on the public leaderboard. Turns out that after some post-processing, a resnet-18 + efficientnet-b1 + efficientnet-b3 blend achieved 0.33+, which at that time was in the gold zone.</p>
<h3>Merging</h3>
<p>Shortly after, I merged with the rest of the team with the goal of plugging my classification models on top of a strong detection model to leverage their potential. There were about two weeks left before the end of the competition, so we first focused on plugging <a href="https://www.kaggle.com/Uijin" target="_blank">@Uijin</a>’s detection models with my classifiers. For a while, we couldn’t beat the detector LB’s of 0.39+, but after setting up a good CV scheme and improving the detection model training strategy, we reached LB 0.41+. </p>
<h3>3D Models</h3>
<p>Around this time, I upgraded my 2D classifiers to be 3D. Models will now take as input frames [-8, -6, -4, -2, 0, 2, 4, 6, 8] instead of just frame 0. The pipeline was easy to adapt, the data loader was slightly modified, architectures were changed, and augmentations were removed for I was too lazy to dig into that.</p>
<p>The first batch of 3D model is based on <a href="https://github.com/kenshohara/3D-ResNets-PyTorch" target="_blank">https://github.com/kenshohara/3D-ResNets-PyTorch</a> : <br>
resnet-18 & resnet-34, using as target the same as the one of the middle frame (that was extended)<br>
resnet-18, using an auxiliary classifier to predict the impact type<br>
resnet-18, with a target extended to frames [-6, +6]</p>
<p>The only additional trick I used is getting rid of all the strides on the temporal axis. Models are made for videos longer than 9 frames so once again I adapt the networks to my small input size.</p>
<p>They helped CV, didn’t really help public LB. In fact our jump to 0.49 at the time came from retraining our detection model on the whole dataset & tweaking some post-processing parameters. <br>
They did however help private LB, but this was after the leak so we didn’t know. </p>
<h3>More 3D Models</h3>
<p>After recovering from NYE, I did some state of the art browsing and implemented 3 new 3D models that all outperformed the previous ones. <br>
i3d from <a href="https://github.com/piergiaj/pytorch-i3d" target="_blank">https://github.com/piergiaj/pytorch-i3d</a><br>
Slowfast from <a href="https://github.com/open-mmlab/mmaction2" target="_blank">https://github.com/open-mmlab/mmaction2</a><br>
Slowonly with Omnisource pretrained weights from <a href="https://github.com/open-mmlab/mmaction2" target="_blank">https://github.com/open-mmlab/mmaction2</a></p>
<p>This was done on the 2nd and 3rd of January, so we had 10 submissions to try these out because of my procrastinating. My first submissions using them gave a small LB boost and we reached 0.50+. </p>
<p>Fortunately the rest of the team worked hard on the detection models to compute results of our detection models on all our folds. This allowed them to find a powerful set of hyperparameters which worked in the end !</p>
<h1>Validation - "Trust Your CV"</h1>
<p>(written by <a href="https://www.kaggle.com/cdeotte" target="_blank">@cdeotte</a>)</p>
<p>Building a reliable validation was very important because it was easy to overfit the public LB or a hold out validation set of only a few videos. Our final model was configured using a full 120 video 5 fold validation. By reviewing our OOF predictions, we were able to tell what we needed to do to improve our model. One tool we used was to watch the ground truths and predictions together in all 3 views. More info <a href="https://www.kaggle.com/cdeotte/watch-submission-csv-as-video/" target="_blank">here</a> and <a href="https://www.kaggle.com/c/nfl-impact-detection/discussion/208782" target="_blank">here</a><br>
<a href="http://playagricola.com/Kaggle/labeled_57586_001934-pair_1.mp4" target="_blank"><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1723677%2Fe46b13bc1feb0e773fb476e689cf5403%2Fpreview.png?generation=1609809137273907&alt=media" alt="IMAGE ALT TEXT HERE"></a><br>
This gave us insight into choosing hyperparameters for our detection and classification models and it gave us insight into creating post process.</p>
<h1>Post-processing</h1>
<p>(written by <a href="https://www.kaggle.com/vaghefi" target="_blank">@vaghefi</a>)</p>
<h3>Thresholding</h3>
<p>We had to find good thresholds for both our detection and classification models. We observed that a single split is not enough and F1 score variation between folds is significant. Therefore, we used the CV calculated on the entire train set (5 folds) to optimize our thresholds. The following tricks improved our CV and LB:<br>
Different thresholds for detection and classification model: Originally we had the same threshold for detection and classification models (~0.5). As the classification model became better, we needed to lower detection thresholds (~0.35) to include more helmet detections and then use the classification model to classify the impacts.<br>
Different thresholds for Endzone and Sideline views: Endzone and Sideline videos are different in terms of image content, box area, box size, etc. We realized that using different thresholds can improve both CV and LB. We tried different combinations and best CV was achieved by using around 0.05 higher threshold in Sideline than Endzone<br>
Different thresholds over time: Both detection and classification models have no information about time-elapsed. From the training set, we know that the chance of impact decreases as frame number increases. We tried different combinations (fixed, piecewise, and linear) and ended up using a piecewise method where we used different thresholds for frame >= 150 and frame < 150.</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1723677%2F73d38ec1aa72b0375c3106e4ba1c4c0b%2Ftime2.png?generation=1609892194122820&alt=media" alt=""></p>
<h3>Box Expansion</h3>
<p>Increasing the size of the bounding boxes helped our models, for some reason. In our last submission, we made the bounding boxes 1.22x bigger.</p>
<h3>Adjacency Post-Processing</h3>
<p>The goal of this PP was to cluster detections (through multiple frames) which belong to the same player and remove FP. We used an IOU threshold and frame-difference threshold to optimize our algorithm. We also tried temporal NMS and soft-NMS but our custom algorithm performed better. </p>
<h3>View Post-Processing</h3>
<p>Impacts that were detected with a confidence lower than <code>T</code> were removed if no impact was found in the other view. That’s the best we came up with regarding merging information from both views.</p>
<h1>Final results</h1>
<p>We selected two submissions : Best public LB and best CV.</p>
<ul>
<li>CV 0.4885 - <strong>Public 0.5408 (10th)</strong> - Private 0.4873 (13th)</li>
<li><strong>CV 0.5125</strong> - Public 0.4931 (13th) - <strong>Private 0.5153 (9th)</strong>. </li>
</ul>
<p>Our competition inference notebook is <a href="https://www.kaggle.com/cdeotte/nfl-2d-detect-3d-classify-0-515" target="_blank">here</a></p>
<h2>Takeaways</h2>
<p>We should’ve trusted our classification models more, as they were 3D, they most likely were better than our detection model. It would’ve been a better approach to use detection models to detect all helmets instead of only impacts and then use 3D classification models to classify impacts. </p> |
HuBMAP - Hacking the Kidney | 54th Place Solution Pytorch Single_5fold_UNet50 private_lb:0.946 | 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: HuBMAP - Hacking the Kidney
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Model: UNet aspp with Resnext50 backbone</p>
<p>Keys:</p>
<ul>
<li><strong>aspp_stride</strong>: 1024x1024 tiles rescaled to 480x480 to feed the model. With 480x480 model input, backbone output feature map is 15x15, so set aspp_stride to 2 to get dilations of 2,4,6,8 which gives the desired coverage of the 15x15 output feature map of the backbone.</li>
<li><strong>batch_size</strong>: Chose 480x480 instead of say 512x512 for model input, so as to be able to train with a batch size of at least 32 on a P100 GPU in mixed precision, as the model has batchNorm layers. </li>
<li><strong>edge_ignore</strong>: During inference, when making predictions for a tile, ignore the predictions at tile edges. Let overlap take care of ignored tile edges.</li>
<li>Tuned the number of training epochs on the validation holdout.</li>
<li>Don't overfit to the public test set. </li>
</ul>
<p>I went through and built on <a href="https://www.kaggle.com/iafoss" target="_blank">@iafoss</a> public notebook: <a href="https://www.kaggle.com/iafoss/hubmap-pytorch-fast-ai-starter" target="_blank">https://www.kaggle.com/iafoss/hubmap-pytorch-fast-ai-starter</a></p>
<p>Generating the training dataset: <br>
<a href="https://www.kaggle.com/pratikkumar/hubmapdataset-sz480-window1024" target="_blank">https://www.kaggle.com/pratikkumar/hubmapdataset-sz480-window1024</a><br>
Tile Size of 1024x1024 rescaled to 480x480 with 20% overlap.</p>
<p>Training:<br>
<a href="https://colab.research.google.com/drive/1u9NXkjRbgI9_3Mwc1FGRLciyXcMFo3Rv?usp=sharing" target="_blank">https://colab.research.google.com/drive/1u9NXkjRbgI9_3Mwc1FGRLciyXcMFo3Rv?usp=sharing</a><br>
Model: Pytorch/Fastai UNet50 (from <a href="https://www.kaggle.com/iafoss" target="_blank">@iafoss</a>) with aspp_stride of 2.<br>
Data Augmentation: </p>
<blockquote>
<p>HorizontalFlip(),<br>
VerticalFlip(),<br>
RandomRotate90(),<br>
ShiftScaleRotate(p=0.5, rotate_limit=15),<br>
OneOf([<br>
OpticalDistortion(),<br>
GridDistortion(),<br>
IAAPiecewiseAffine(scale=(0.02, 0.03)),<br>
], p=0.2),<br>
OneOf([<br>
HueSaturationValue(10,15,10),<br>
RandomBrightnessContrast(0.1,0.1),<br>
], p=0.5),</p>
</blockquote>
<p>Reduced the intensity of some augmentations and removed clahe.<br>
5 fold training.</p>
<p>Inference:<br>
<a href="https://www.kaggle.com/pratikkumar/hubmap-win1024-sz480-inference-batched-subds" target="_blank">https://www.kaggle.com/pratikkumar/hubmap-win1024-sz480-inference-batched-subds</a><br>
Overlap of 30% and Edge Ignore of slightly less than 15%.</p> |
Cassava Leaf Disease Classification | Private LB 101 / Public LB was 433 (+332 ) - Silver 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: Cassava Leaf Disease Classification
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Hi Kagglers!</p>
<p>101 place Kernel is here:<br>
<a href="https://www.kaggle.com/izotov/public-lb-score-0-901-priate-0-900-101st-place" target="_blank">https://www.kaggle.com/izotov/public-lb-score-0-901-priate-0-900-101st-place</a><br>
Public LB was only 433.</p>
<p>Many thanks to contributors!<br>
Special thanks to contributors of source Kernels:<br>
<a href="https://www.kaggle.com/piantic/no-tta-cassava-resnext50-32x4d-inference-lb0-903/output" target="_blank">https://www.kaggle.com/piantic/no-tta-cassava-resnext50-32x4d-inference-lb0-903/output</a><br>
<a href="https://www.kaggle.com/underwearfitting/clean-inference-kernel-8xtta-lb902/data" target="_blank">https://www.kaggle.com/underwearfitting/clean-inference-kernel-8xtta-lb902/data</a><br>
<a href="https://www.kaggle.com/shubham108/cassava-ensemble-efnetb3-resnet50" target="_blank">https://www.kaggle.com/shubham108/cassava-ensemble-efnetb3-resnet50</a></p>
<p>And my conrgatulations to winners!</p> |
Cassava Leaf Disease Classification | Private LB 34th / Public LB 30th 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: Cassava Leaf Disease Classification
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thank you to all my teammates and participants. I would like to share a summary of our solution.</p>
<p>※Some teams were removed. I changed Topic Title because our LB changed (private LB 38→34th, public LB 31→30th).</p>
<h1>Summary</h1>
<p><img src="https://github.com/riron1206/kaggle_Cassava/blob/master/Cassava_Leaf_Disease_Classification_Model_Pipeline.jpg?raw=true" alt="img1"></p>
<p>Private LB 34th / Public LB 30th Inference Notebook: <br>
<a href="https://www.kaggle.com/anonamename/cassava-emsemble-v2-stacking?scriptVersionId=54065022" target="_blank">https://www.kaggle.com/anonamename/cassava-emsemble-v2-stacking?scriptVersionId=54065022</a></p>
<h3>TTA</h3>
<p>We increased number of TTA for the 224*224 Vit model because accuracy of TTA using RandomResizedCrop with small image size was not stable.<br>
Since public LB did not increase with stronger augmentation such as RandomBrightnessContrast, we only did flip.<br>
Depending on random number of TTA, public LB changed by about 0.001-0.003, but this problem could not be solved.</p>
<h3>Blending</h3>
<p>We blended ViT-B/16, EfficientnetB4, ResNeSt101e, and SE-Resnext50_32x4d model.<br>
We used Unsupervised Data Augmentation (Semi-Supervised Learning) or BYOL (Self-Supervised Learning) on 2019 data, but it did not contribute much to accuracy improvement.<br>
By averaging k-fold confidence and blending five or more models, we were able to achieve a stable public LB over 0.900.<br>
We blended based on confusion matrix to get a higher cv, but private LB became worse.</p>
<h3>Stacking</h3>
<p>We were able to increase public LB from 0.905 to 0.907 by stacking using Conv2d+MLP.<br>
We used predictive label of blended model as Pseudo label.<br>
To avoid overfiting, we trained the model by adding gaussian noise to the feature.</p>
<hr>
<h3>Comment</h3>
<p>For simple average blending without stacking, there was a submit that was 0.902 for both public and private LB.<br>
<img src="https://github.com/riron1206/kaggle_Cassava/blob/master/sub_img.png?raw=true" alt="img2"></p>
<p>As discussed in other discussions, simple average blending was better for noisy test data sets.</p> |
HuBMAP - Hacking the Kidney | 44th 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: HuBMAP - Hacking the Kidney
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>I give here a brief overview of my solution mostly to share the methodology I used to tackle that competition: I used chunks of codes that track the evolution of the different experiments through git, which turns out to be quite useful in order to monitor the evolution along the various attempts. </p>
<p>Since I had not previous experience on computer vision, I entered HubMap using the code shared by <a href="https://www.kaggle.com/hengck23" target="_blank">@hengck23</a> (I take this opportunity to thanks <a href="https://www.kaggle.com/hengck23" target="_blank">@hengck23</a> for all the material and knowledge he shares along its kaggle's journey).</p>
<p>The code used for training and inference is available on <a href="https://github.com/FabienDaniel/HubMap/" target="_blank">git</a>. <br>
The inference code on Kaggle is <a href="https://www.kaggle.com/fabiendaniel/submit-hubmap" target="_blank">here</a>. (utility scripts are used inside this script.) </p>
<p>My solution consists in a two stage modeling:</p>
<ul>
<li>a first stage with 256 x 256 tiles, with a reduction by a factor 4 in resolution: this network is trained with emphasis on false negatives, using images that cover the entire .tiff images.</li>
<li>the output of the previous network is used to locate the potential glomeruli on the image. A second network is then trained using images that are mostly located around known glomeruli. The train images have sizes of 515 x 512 with a scale factor of 2. </li>
</ul>
<p>For each of these two networks, I used Unet models with Efficientnet b0 backbones. I quickly checked other backbones but didn't see any noticeable impact on the results. It quickly appear that selecting the dataset to train the model was the key for model performance.</p>
<h1>CV scheme</h1>
<p>As mentioned many times, finding a correlation between local CV and LB was difficult because of the <code>d48</code> image. During the course of this competition, I tried various CV schemes:</p>
<ol>
<li>Kfold on whole tiles</li>
<li>a random sampling of images with a random 20% of each tile used as validation</li>
<li>a whole part of each tile kept as validation.</li>
</ol>
<p>A posteriori, the two latest schemes give good results with scores well aligned with the private LB. During the competition, it was not clear if any of these scheme would be reliable but I auto-convinced myself that the 3rd one should be reliable and I used it to select the details of the models.</p>
<h1>Pseudo-labelisation</h1>
<p>In the last days, I started to include the test tiles in order to train some models. For these images, the mask were generated using the best model I had so far. I subsequently checked "visually" that the glomeruli selected that way and the corresponding masks were reliable with respect to what I expected.</p>
<p>[TO COMPLETE]</p> |
NFL 1st and Future - Impact Detection | [40th place solution] 2-Class Prediction + HFlip + NMS + Filtering | 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: NFL 1st and Future - Impact Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Firstly, thanks both to Kaggle founders and the NFL competition organisers for the possibility to take part in this contest! Secondly, thanks to <a href="https://www.kaggle.com/its7171" target="_blank">@its7171</a> and his <a href="https://www.kaggle.com/its7171/2class-object-detection-training" target="_blank">kernel</a> for the great idea of 2-class training!</p>
<h1>Brief Summary</h1>
<p>The <a href="https://github.com/AlexeyAB/darknet/blob/master/cfg/yolov4-tiny-3l.cfg" target="_blank">Tiny-YOLOv4</a> from<a href="https://github.com/AlexeyAB/darknet" target="_blank"> AlexeyAB's darknet repository</a> was used. The training of both impacts and non-impacts with leaving impacts only was done. To gain more accuracy, horizontal flipping data augmentation both when training and testing, filtering and non-max suppression of both (flipped and original) frames were implemented.<br>
<img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F2209740%2F579d67615527f33d40be1038d26ac5c2%2FNFL%20Impact%20Detection.png?generation=1610007246515155&alt=media" alt="The complete pipeline"></p>
<h1>Training</h1>
<p>The only videos and train_labels.csv were used in training. No separate frames from image_labels.csv and tracking data were used because of the lack of time and resources.</p>
<p>The parameters are:</p>
<ul>
<li>batch_size: 64,</li>
<li>classes: 2,</li>
<li>iterations: 4000 (with 64 images per iteration),</li>
<li>step: 15,</li>
<li>augmentation: horizontal flip only,</li>
<li>total images: ~4000 (2000 * 2),</li>
<li>input size: 896x512 (with random resize).</li>
</ul>
<p>It was used the step to extract frames from videostream to decrease the consumed time of training and also to make difference between impacted and non-impacted helmets.</p>
<h1>Inference</h1>
<p>The main idea is to use not only one but two images per the real video frame: the original and the horizontally flipped one.</p>
<p>When the prediction of both them is done, it's made the filtering by following parameters:</p>
<ul>
<li>nearest_index_distance: 5 (the farthest distance between two nearest impact frames),</li>
<li>farthest_index_distance: 23 (the distance between start and stop frames of the filtered sequence),</li>
<li>nearest_iou: 0.4 (the Intersection-Over-Union metric).</li>
</ul>
<p>When the filtering is done, it's made the Non-Max-Suppression to merge the overlapped bboxes and exclude the non-overlapped ones from the submission. The NMS is done on not the only one frame but few nearest frames in the sequence. So, the parameters are:</p>
<ul>
<li>nms_max_distance: 4,</li>
<li>nearest_iou: 0.4.</li>
</ul> |
Cassava Leaf Disease Classification | Private 606th / Public 34th 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: Cassava Leaf Disease Classification
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Hi everyone!</p>
<p>First of all, congratulations to all the winners and did a great job on all participants' hard works!</p>
<h1>Overview</h1>
<p>I selected two versions based on best CV & LB scores because I'm really worried about a huge shakeup. (However, I did not make it out :cool_crying:)</p>
<ul>
<li>Public LB: 34th, 0.907</li>
<li>Private LB: 606th, 0.898</li>
</ul>
<h2>Base Model</h2>
<p>I only got Kaggle GPU, so I couldn't experiment with many models with various recipes.<br>
I tried 6 models (ResNeSt50, ResNeSt50 4s2x40d, EffNet-B3, 4, ViT-L/16, DeiT-B/16) and decided to use <strong>ResNeSt50 4s2x40d</strong>, <strong>EffNet-B4</strong> based on LB & CV scores.</p>
<table>
<thead>
<tr>
<th>arch</th>
<th>CV</th>
<th>Public LB</th>
<th>Private LB</th>
</tr>
</thead>
<tbody>
<tr>
<td>ResNeSt50-fast-4s2x40d (tta4)</td>
<td>0.891</td>
<td>0.898</td>
<td>0.895</td>
</tr>
<tr>
<td>EfficientNet-B3 NS (tta4)</td>
<td>0.895</td>
<td>0.896</td>
<td>0.895</td>
</tr>
<tr>
<td>EfficientNet-B4 NS (tta4)</td>
<td>0.891</td>
<td>0.900</td>
<td>0.893</td>
</tr>
</tbody>
</table>
<p>To increase the robustness, I trained the model on different training recipes with the same architecture. I chose to use <code>focal cosine loss</code> & <code>cross-entropy w/ label smoothing 0.2</code>.</p>
<table>
<thead>
<tr>
<th>arch</th>
<th>loss</th>
<th>CV</th>
<th>Public LB</th>
<th>Private LB</th>
</tr>
</thead>
<tbody>
<tr>
<td>EfficientNet-B4 NS (tta3)</td>
<td>focal cosine</td>
<td>0.890</td>
<td>0.900</td>
<td>0.895</td>
</tr>
<tr>
<td>EfficientNet-B4 NS (tta4)</td>
<td>cross entropy w/ label smooth</td>
<td>0.891</td>
<td>0.900</td>
<td>0.893</td>
</tr>
</tbody>
</table>
<p>Lastly, the pseudo label boosts the CV score +0.007. (I generated a pseudo label based on my best CV score, 0.9051)</p>
<table>
<thead>
<tr>
<th>arch</th>
<th>pseudo</th>
<th>CV</th>
<th>Public LB</th>
<th>Private LB</th>
</tr>
</thead>
<tbody>
<tr>
<td>EfficientNet-B4 NS (tta4)</td>
<td>no</td>
<td>0.891</td>
<td>0.900</td>
<td>0.893</td>
</tr>
<tr>
<td>EfficientNet-B4 NS (tta4)</td>
<td>yes</td>
<td>0.898</td>
<td>0.898</td>
<td>0.893</td>
</tr>
</tbody>
</table>
<h2>Ensemble</h2>
<h3>Weights</h3>
<p>Single model's CV & LB scores seem not good, But, ensembling raises the CV & LB scores to 0.005. Also, TTA increases LB scores +0.002.</p>
<p>I tuned the ensemble weights with <code>Optuna</code> & <a href="https://www.kaggle.com/daisukelab/optimizing-ensemble-weights-using-simple" target="_blank"><code>Simple</code></a> on CV.</p>
<p>Here is the script : <a href="https://www.kaggle.com/kozistr/valid-optimize-cv" target="_blank">optimive cv</a></p>
<h3>Combinations</h3>
<ul>
<li>best LB : 2 x ResNeSt50-fast-4s2x40d + 2 x EffNet-B4</li>
<li>best CV : 3 x ResNeSt50-fast-4s2x40d + 3 x EffNet-B4 + 1 x EffNet-B3</li>
</ul>
<table>
<thead>
<tr>
<th>baseline</th>
<th>CV</th>
<th>Public LB</th>
<th>Private LB</th>
</tr>
</thead>
<tbody>
<tr>
<td>best LB</td>
<td>0.9003</td>
<td>0.907</td>
<td>0.897</td>
</tr>
<tr>
<td>best CV</td>
<td>0.9051</td>
<td>0.905</td>
<td>0.896</td>
</tr>
</tbody>
</table>
<p>Here is the script : <a href="https://www.kaggle.com/kozistr/inference-rns50-effnet-b4" target="_blank">inference</a></p>
<h2>TTA</h2>
<p>Simply using <code>CenterCrop + horizontal & vertical flop</code> achieves better CV & LB scores.</p>
<h2>Training Recipe</h2>
<ul>
<li>Data : 2019 + 2020 datasets, only 2020, w/ pseudo labels</li>
<li>Validation : stratified kfold - 5 folds</li>
<li>Augmentations : FMix, CutMix, SnapMix, MixUp, Cutout, etc…</li>
<li>Optimizer : AdamW, AdamP, RAdam</li>
<li>Loss : focal cosine, cross-entropy w/ label smoothing, bi-tempered</li>
<li>Scheduler : Cosine Anealling w/o warm-up (1e-4 to 1e-6)</li>
<li>Epochs : 10 ~ 20</li>
<li>Resolution : 512x512</li>
<li>Auxiliary : freeze BN layer</li>
<li>TTA : n_iters 4 is best in my case.</li>
</ul>
<p>Experiment : <a href="https://www.kaggle.com/kozistr/cassava-leaf-disease-experiments" target="_blank">note</a></p>
<h3>Works</h3>
<ol>
<li>Label Smoothing (alpha = 0.2)</li>
<li>TTA (n_iters 4 is best)</li>
<li>Adam, AdamW to RAdam (slight improvement)</li>
<li>external dataset (2019 dataset)</li>
</ol>
<h3>Not Works</h3>
<ol>
<li>noise-tolerant(?) loss like bi-tempered loss</li>
</ol>
<h2>Reflections</h2>
<ol>
<li>ensemble weights</li>
</ol>
<p>I guess tuning ensemble weights might be one of the reasons, especially where there're noisy labels. Usually, the tuned versions tend to have a lower score than the average one. (-0.001 ~ -0.002 gap on Private LB score). But, Ironically best Private score is the tuned version (not the selected one).</p>
<ol>
<li>multiple scales (image resolution)</li>
</ol>
<p>I think training & inferencing with multiple scales would be helpful to improve the score. On several experiments, a lower resolution (384x384) works better than a higher resolution (512x512).</p>
<p>Thank you very much!</p> |
Cassava Leaf Disease Classification | [2/21 Update] Private 13th, Public 52th Place Solution. My first medal 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: Cassava Leaf Disease Classification
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Hi, everyone!<br>
First of all, thank you for all the kagglers who contributed to this competition and congratulations to the winners.</p>
<p>I was so amazed that I got 13th place on the private LB. I wouldn't dream of it! Unbelievable! </p>
<p>In this discussion, I would like to share my solution. </p>
<h1>Summary</h1>
<p>My best public submission is<br>
CV: 0.9071<br>
Public LB: 0.905 <br>
Private LB: 0.901<br>
<img src="https://user-images.githubusercontent.com/66665933/108469766-37ccde00-72cc-11eb-886d-0d9b497a120d.png" alt=""></p>
<table>
<thead>
<tr>
<th>model arch</th>
<th>loss</th>
<th>CV strategy</th>
<th>CV score</th>
<th>LB score</th>
<th>Private score</th>
<th>TTA</th>
</tr>
</thead>
<tbody>
<tr>
<td>EfficientNet-B0</td>
<td>CrossEntropy</td>
<td>CV1</td>
<td>0.87867458</td>
<td>0.8828</td>
<td>0.8902</td>
<td>None</td>
</tr>
<tr>
<td>EfficientNet-B2</td>
<td>CrossEntropy</td>
<td>CV2</td>
<td>0.890498668</td>
<td>0.8982</td>
<td>0.8902</td>
<td>None</td>
</tr>
<tr>
<td>EfficientNet-B3</td>
<td>BiTemperedLoss(t1=0.2, t2=1.0)</td>
<td>CV1</td>
<td>0.8904519</td>
<td>0.8998</td>
<td>0.8957</td>
<td>None</td>
</tr>
<tr>
<td>EfficientNet-B4</td>
<td>CrossEntropy</td>
<td>CV2</td>
<td>0.89816329</td>
<td>0.9054</td>
<td>0.897</td>
<td>Resize, CenterCrop</td>
</tr>
<tr>
<td>EfficientNet-B5</td>
<td>DistillationLoss</td>
<td>CV2</td>
<td>0.892788708</td>
<td>0.8984</td>
<td>0.8936</td>
<td>None</td>
</tr>
<tr>
<td>DenseNet121</td>
<td>BCE(smoothing=0.01)</td>
<td>CV1</td>
<td>0.891059494</td>
<td>0.8969</td>
<td>0.8906</td>
<td>None</td>
</tr>
<tr>
<td>DenseNet121</td>
<td>BCE(smoothing=0.1)</td>
<td>CV1</td>
<td>0.89171379</td>
<td>0.8944</td>
<td>0.8896</td>
<td>None</td>
</tr>
<tr>
<td>InceptionV4</td>
<td>BCE(no smoothing)</td>
<td>CV1</td>
<td>0.89087255</td>
<td>0.8914</td>
<td>0.893</td>
<td>None</td>
</tr>
<tr>
<td>ViT (7)</td>
<td>CrossEntropy</td>
<td>CV2</td>
<td>0.8871337</td>
<td>0.8887</td>
<td>0.8853</td>
<td>None</td>
</tr>
<tr>
<td>ViT (0)</td>
<td>BiTemperedLoss(t1=0.8, t2=1.4, smoothing=0.06)</td>
<td>CV1</td>
<td>0.89348974</td>
<td>0.8896</td>
<td>0.8856</td>
<td>Resize, CenterCrop</td>
</tr>
<tr>
<td>ResNext50-32x4d</td>
<td>BCE with weight</td>
<td>CV2</td>
<td>0.895405898</td>
<td>0.8961</td>
<td>0.8966</td>
<td>None</td>
</tr>
</tbody>
</table>
<h1>CV strategy</h1>
<p>I used 2 CV strategies.<br>
Stratified K-Fold (CV1)<br>
Stratified K-Fold with clustering data (CV2)<br>
CV1 is just a normal stratified-kfold. (Probably many people use it.)<br>
CV2 is inspired with <a href="https://www.kaggle.com/bjoernholzhauer/cassava-leaf-disease-classif-eda-cv-strategy" target="_blank">this</a> notebook. The notebook describes there are just a few root images in the dataset. So I made a clustering data and used it when splitting into folds like <code>skf.split(X=train["clustering"], y=train["label"])</code>.</p>
<p>In my case, the correlations between CV and public LB are high. <br>
This way I trust my CV. </p>
<p>[2/20 Update!]</p>
<h1>2019 Dataset</h1>
<p>I used the whole 2019 images(train+test+extra) except duplicates.<br>
I rarely use the labels because the labels seem to be noisier than the 2019 dataset.<br>
I predicted the train images using some models and observed the accuracy was pretty lower (around 0.85) than the CV score (around 0.89).</p>
<h1>Models for final submission</h1>
<p>All models are trained with 5folds.</p>
<h2>EfficientNet-B0</h2>
<p>Actually, this model is made just to compare if <code>cleanlab</code> works or not.<br>
This model is the version that does not use <code>cleanlab</code>.<br>
It doesn’t mean <code>cleanlab</code> doesn’t work. The <code>cleanlab</code> model scored higher than non <code>cleanlab</code> one on CV, LB, private LB. Moreover, the other version using <code>cleanlab</code> has less correlation between other models.</p>
<p>As I didn’t expect to use this model for final submission, there might be something to improve this model. </p>
<table>
<thead>
<tr>
<th>optimzer</th>
<th>scheduler</th>
<th>epochs</th>
<th>weight decay</th>
<th>loss fn</th>
<th>CV</th>
<th>LB</th>
<th>Private</th>
</tr>
</thead>
<tbody>
<tr>
<td>Adam</td>
<td>None</td>
<td>5</td>
<td>1e-6</td>
<td>CrossEntropy</td>
<td>0.8786</td>
<td>0.8828</td>
<td>0.8902</td>
</tr>
</tbody>
</table>
<p>I applied light augmentation, which is <code>RandomResizedCrop, HorizontalFlip</code> for training, <code>Resize</code> for prediction.</p>
<h2>EfficientNet-B2</h2>
<p>I trained this model using Mixup Without Hesitation inspired from some discussions.<br>
MHW was applied like this</p>
<pre><code>mask = random.random()
if epoch >= 36:
threshold = (40 - epoch) / (40 - 36)
if mask < threshold:
x, y_a, y_b, lam = mixup_data(x, y, 0.5, use_cuda=True, device=self.device)
else:
y_a, y_b = y, y
lam = 1.0
elif epoch >= 24:
if epoch % 2 == 0:
x, y_a, y_b, lam = mixup_data(x, y, 0.5, use_cuda=True, device=self.device)
else:
y_a, y_b = y, y
lam = 1.0
else:
x, y_a, y_b, lam = mixup_data(x, y, 0.5, use_cuda=True, device=self.device)
</code></pre>
<p>I slightly changed <code>mixup_data</code> from <a href="https://github.com/yuhao318/mwh" target="_blank">github</a> because I wanted to use <code>cuda:n</code>.</p>
<table>
<thead>
<tr>
<th>optimzer</th>
<th>scheduler</th>
<th>epochs</th>
<th>weight decay</th>
<th>loss fn</th>
<th>CV</th>
<th>LB</th>
<th>Private</th>
</tr>
</thead>
<tbody>
<tr>
<td>Adam</td>
<td>OneCycleLR</td>
<td>40</td>
<td>1e-6</td>
<td>CrossEntropy</td>
<td>0.8905</td>
<td>0.8982</td>
<td>0.8902</td>
</tr>
</tbody>
</table>
<p>The augmentation for training was heavy, which is </p>
<pre><code>A.RandomResizedCrop(params["height"], params["width"]),
A.OneOf([A.Transpose(p=0.5),
A.HorizontalFlip(p=0.5),
A.VerticalFlip(p=0.5),
A.ShiftScaleRotate(p=0.5)], p=1.0),
A.OneOf(
[A.HueSaturationValue(hue_shift_limit=0.2, sat_shift_limit=0.2, val_shift_limit=0.2, p=0.5),
A.RandomBrightnessContrast(brightness_limit=(-0.1, 0.1), contrast_limit=(-0.1, 0.1), p=0.5),], p=0.5),
A.Normalize(mean=[0.4303, 0.4967, 0.3134],
std=[0.2142, 0.2191, 0.1954],),
A.OneOf([
A.CoarseDropout(p=0.5),
A.Cutout(p=0.5),], p=0.5),
ToTensorV2(p=1.0)
</code></pre>
<p>The reason I use <code>A.OneOf</code> is to speed up the training process. </p>
<h2>EfficientNet-B3</h2>
<table>
<thead>
<tr>
<th>optimzer</th>
<th>scheduler</th>
<th>epochs</th>
<th>weight decay</th>
<th>loss fn</th>
<th>CV</th>
<th>LB</th>
<th>Private</th>
</tr>
</thead>
<tbody>
<tr>
<td>Adam</td>
<td>MultiStepLR</td>
<td>20</td>
<td>1e-6</td>
<td>BiTemperedLoss</td>
<td>0.8904</td>
<td>0.8998</td>
<td>0.8957</td>
</tr>
</tbody>
</table>
<p>The t1 and t2 for loss function are t1=0.2, t2=1.0.<br>
In the first epoch, I trained only the classifier by freezing the rest of layers.<br>
From the second epoch, I set all layers trainable.<br>
I applied middle augmentation for training, which includes <code>RandomResizedCrop, HorizontalFlip, ShiftScaleRotate</code>. I used <code>CenterCrop</code> for prediction.</p>
<h2>EfficientNet-B4</h2>
<table>
<thead>
<tr>
<th>optimzer</th>
<th>scheduler</th>
<th>epochs</th>
<th>weight decay</th>
<th>loss fn</th>
<th>CV</th>
<th>LB</th>
<th>Private</th>
</tr>
</thead>
<tbody>
<tr>
<td>Adam+SAM</td>
<td>CosineAnnealingWarmRestarts</td>
<td>15</td>
<td>1e-6</td>
<td>CrossEntropy</td>
<td>0.8981</td>
<td>0.9054</td>
<td>0.8970</td>
</tr>
</tbody>
</table>
<p>This model is trained in two stages.</p>
<ol>
<li>training with the 2020 dataset.</li>
<li>making soft labels of the 2019 dataset by using the model in the first step and then , train with 2019+2020 dataset. </li>
</ol>
<p>This idea is inspired by the Noisy Student Method.<br>
In the first step, the augmentation for training is middle, which includes <code>RandomResizedCrop, HorizontalFlip, ShiftScaleRotate</code>. I used <code>Resize</code> for soft label prediction.<br>
In the second step, I added dropout after the last linear. The augmentation for training is heavy, which is the same as EfficientNet-B2. The labels are clipped [0.1, 0.9] at the probability of 0.5. (This is instead of label smoothing.) The optimizer is Adam+SAM, which boosted the CV and LB score.<br>
The CV without TTA (only Resizing) is 0.896, LB is 0.899.<br>
The CV with TTA (Resizing, CenterCrop) is 0.898, LB is 0.905. (I felt this is overfitting)</p>
<h2>EfficientNet-B5</h2>
<table>
<thead>
<tr>
<th>optimzer</th>
<th>scheduler</th>
<th>epochs</th>
<th>weight decay</th>
<th>loss fn</th>
<th>CV</th>
<th>LB</th>
<th>Private</th>
</tr>
</thead>
<tbody>
<tr>
<td>Adam+SAM</td>
<td>CosineAnnealingWarmRestarts</td>
<td>15</td>
<td>1e-6</td>
<td>DistillationLoss</td>
<td>0.8927</td>
<td>0.8984</td>
<td>0.8936</td>
</tr>
</tbody>
</table>
<p>This model is trained with knowledge distillation with 2019+2020 dataset.</p>
<p>First, load the probabilities of 2019 dataset and 2020 dataset and create hard labels of 2019 dataset that don't have the label (test-images, extra-images). I used the label in the dataset for this model. This time I have soft and hard labels in both dataset.</p>
<p>The loss function is the sum of hard label CrossEntropyLoss and soft label Kullback-Leibler divergence. This is inspired by the <code>Deit</code> repository. The <code>alpha</code> is set to 0.5.</p>
<pre><code>def forward(self, pred, y, soft_label):
dist_loss = F.kl_div(F.log_softmax(pred, dim=1), soft_label.log())
ce_loss = F.cross_entropy(pred, y.argmax(dim=1))
return dist_loss * self.alpha + ce_loss * (1 - self.alpha)
</code></pre>
<p>augmentation is heavy, which is the same as EfficinetNet-B2.</p>
<h2>DenseNet121, InceptionV4</h2>
<table>
<thead>
<tr>
<th>model arch</th>
<th>optimzer</th>
<th>scheduler</th>
<th>epochs</th>
<th>weight decay</th>
<th>loss fn</th>
<th>CV</th>
<th>LB</th>
<th>Private</th>
</tr>
</thead>
<tbody>
<tr>
<td>DenseNet121</td>
<td>Adam</td>
<td>MuliStepLR</td>
<td>15</td>
<td>1e-6</td>
<td>BCE, smoothing=0.01</td>
<td>0.8910</td>
<td>0.8969</td>
<td>0.8906</td>
</tr>
<tr>
<td>DenseNet121</td>
<td>Adam</td>
<td>MuliStepLR</td>
<td>15</td>
<td>1e-6</td>
<td>BCE, smoothing=0.1</td>
<td>0.8917</td>
<td>0.8944</td>
<td>0.8896</td>
</tr>
<tr>
<td>InceptionV4</td>
<td>Adam</td>
<td>MuliStepLR</td>
<td>15</td>
<td>1e-6</td>
<td>BCE, No smoothing</td>
<td>0.8908</td>
<td>0.8914</td>
<td>0.8930</td>
</tr>
</tbody>
</table>
<p>I trained this model using BinaryCrossEntropyLoss.<br>
The idea is from the fact that there are duplicate images in the dataset and they have different labels. There might be multiple diseases in the same images. So I tried BCE.</p>
<p>The training detail is almost the same as EfficientNetB3. The difference is loss function.<br>
I applied BCE with smoothing for DenseNet121 models. One is smoothing=0.01, the other is 0.1, InceptionV4 for no smoothing.<br>
You may feel why I put almost the same model for the final prediction. <br>
The reason is simple. Optuna suggested that I put these models to maximize the CV score!<br>
The detailed process is described in the next section. </p>
<h2>ViT (1)</h2>
<table>
<thead>
<tr>
<th>optimzer</th>
<th>scheduler</th>
<th>epochs</th>
<th>weight decay</th>
<th>loss fn</th>
<th>CV</th>
<th>LB</th>
<th>Private</th>
</tr>
</thead>
<tbody>
<tr>
<td>MomentumSGD</td>
<td>OneCycleLR</td>
<td>50</td>
<td>1e-6</td>
<td>CrossEntropy</td>
<td>0.8871</td>
<td>0.8887</td>
<td>0.8853</td>
</tr>
</tbody>
</table>
<p>The training method of this model is almost the same as EfficientNet-B2 except using MomentumSGD for optimizer, the number of epochs, input size.<br>
It means Mixup Without Hesitation is also applied when training this model.<br>
The epoch to apply Mixup Without Hesitation is the same as EfficientNet-B2 although the number of epochs is different. This is because I forgot to change it. However, it worked well and this is the best ViT model that I trained by myself. </p>
<h2>ViT (2)</h2>
<table>
<thead>
<tr>
<th>optimzer</th>
<th>scheduler</th>
<th>epochs</th>
<th>weight decay</th>
<th>loss fn</th>
<th>CV</th>
<th>LB</th>
<th>Private</th>
</tr>
</thead>
<tbody>
<tr>
<td>Adam</td>
<td>CosineAnnealingWarmRestarts</td>
<td>10</td>
<td>0</td>
<td>BiTemperedLoss</td>
<td>0.8897</td>
<td>0.8896</td>
<td>0.8856</td>
</tr>
</tbody>
</table>
<p>This model is a fork of <a href="https://www.kaggle.com/mobassir/vit-pytorch-xla-tpu-for-leaf-disease" target="_blank">this notebook</a>. <br>
I tried to improve the score, only to find it worsened the score. So I used the pretrained weights.<br>
The scores are 0.8897 for CV, 0.889 for LB without TTA<br>
When predicting, I applied 2xTTA(Resize, CenterCrop), whose scores were 0.8934 for CV, 0.889 for LB (No LB improvement).</p>
<h2>ResNext50-32x4d</h2>
<table>
<thead>
<tr>
<th>optimzer</th>
<th>scheduler</th>
<th>epochs</th>
<th>weight decay</th>
<th>loss fn</th>
<th>CV</th>
<th>LB</th>
<th>Private</th>
</tr>
</thead>
<tbody>
<tr>
<td>Adam+SAM</td>
<td>CosineAnnealingWarmRestarts</td>
<td>15</td>
<td>1e-6</td>
<td>BCE with weights</td>
<td>0.8954</td>
<td>0.896</td>
<td>0.8966</td>
</tr>
</tbody>
</table>
<p>The training method of this model is almost the same as EfficientNet-B4 except loss function. The loss function is BCE. Since the classes are highly imbalanced, I applied class weights <code>[1.5, 0.7, 0.7, 0.6, 1.5]</code>. I applied <code>drop_path_rate=0.0001</code>. </p>
<h1>How to choose the models for final submission</h1>
<p>Since I relied on the CV, the models are chosen to maximize the CV score. Here are the steps for it.</p>
<ol>
<li>find the best model combination</li>
<li>find the optimal weight for the models</li>
</ol>
<p>In the first step, I used <code>optuna</code> and <a href="https://www.kaggle.com/c/siim-isic-melanoma-classification/discussion/175614" target="_blank">this method</a> for choosing the combination. <br>
Although <code>optuna</code> doesn’t officially support finding combinations, I used 6~12x <code>trial.suggest_categorical</code> to find the combinations allowing the duplicates. (I can remove them by human hand.)</p>
<p>In the second step, I used <code>optuna</code> for finding the optimal weights.<br>
Since the result is different every time I run the code, I reran it again, again and again.</p>
<p>I prepared 2 kinds of weights. One is 1d weights for each model. The other is 2d weights for each class probabilities. </p>
<p>The weights for the final submission is </p>
<table>
<thead>
<tr>
<th></th>
<th>cbb</th>
<th>cbsd</th>
<th>cgm</th>
<th>cmd</th>
<th>healthy</th>
</tr>
</thead>
<tbody>
<tr>
<td>EfficientNet-B0</td>
<td>0.12</td>
<td>0.06</td>
<td>0.1</td>
<td>0.34</td>
<td>0.27</td>
</tr>
<tr>
<td>EfficientNet-B2</td>
<td>0.77</td>
<td>0.47</td>
<td>0.88</td>
<td>0.21</td>
<td>0.84</td>
</tr>
<tr>
<td>EfficientNet-B3</td>
<td>1</td>
<td>0.96</td>
<td>0.46</td>
<td>0.84</td>
<td>0.74</td>
</tr>
<tr>
<td>EfficientNet-B4</td>
<td>0.87</td>
<td>0.45</td>
<td>0.54</td>
<td>0.81</td>
<td>0.28</td>
</tr>
<tr>
<td>EfficientNet-B5</td>
<td>0.88</td>
<td>0.06</td>
<td>0</td>
<td>0.46</td>
<td>0.29</td>
</tr>
<tr>
<td>DenseNet121_1</td>
<td>0.36</td>
<td>0.29</td>
<td>0.77</td>
<td>0.27</td>
<td>0.23</td>
</tr>
<tr>
<td>Densenet121_2</td>
<td>0.06</td>
<td>0.62</td>
<td>0.2</td>
<td>0.56</td>
<td>0.03</td>
</tr>
<tr>
<td>InceptionV4</td>
<td>0.02</td>
<td>0.87</td>
<td>0.08</td>
<td>0.72</td>
<td>0.88</td>
</tr>
<tr>
<td>ViT (1)</td>
<td>0.88</td>
<td>0.45</td>
<td>0.64</td>
<td>0.43</td>
<td>0.38</td>
</tr>
<tr>
<td>ViT (2)</td>
<td>0.48</td>
<td>0.66</td>
<td>0.76</td>
<td>0.73</td>
<td>0.05</td>
</tr>
<tr>
<td>ResNext50-32x4d</td>
<td>0.72</td>
<td>1</td>
<td>0.15</td>
<td>0.8</td>
<td>0.84</td>
</tr>
</tbody>
</table>
<p>Actually, models with 2d weights could achieve higher in CV, but slightly lower in Public LB compared to 1d weights. I was a bit concerned that the models with 2d weights are overfitting to the CV. However, I selected the best CV submission and the best LB submission for the final score. The best CV submission scored the best in Private LB. Trust your CV is true!</p>
<p>[2/21 update!]</p>
<ul>
<li>changed the table</li>
</ul>
<h1>Correlations</h1>
<p>The correlations are calculated from saved oof(probabilities for each class) files and reshaped them to 1d. <br>
<img src="https://user-images.githubusercontent.com/66665933/108615417-37a51d80-7447-11eb-8371-dd462531dec5.png" alt=""></p>
<h1>Confusion matrix of final submission's oof</h1>
<p><img src="https://user-images.githubusercontent.com/66665933/108615422-4095ef00-7447-11eb-82ae-95fa593baba5.png" alt=""></p>
<h1>What worked and didn’t work</h1>
<h3>worked</h3>
<ul>
<li>changing seed</li>
<li>bi-tempered loss </li>
<li>BCE loss</li>
<li>taylor cross entropy with smoothing = 0.2 </li>
<li>SAM optimizer</li>
<li>momentum SGD (slow but higher performance)</li>
<li>knowledge distillation</li>
<li>2019 dataset</li>
<li>CenterCrop for prediction</li>
<li>mixup without hesitation</li>
<li>calculating optimal weights of oofs </li>
</ul>
<h3>didn’t work</h3>
<ul>
<li>Adabelief optimizer </li>
<li><code>HorizontalFlip</code> for TTA </li>
<li>lightgbm for middle features of pretrained model (higher CV, LB but lower Private score)</li>
<li>using TabNet for classifier</li>
</ul>
<p>Let me know if you have any questions. Thank you again. See you in the next competition :)</p> |
Jane Street Market Prediction | 39th Place - Solution Overview & 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: Jane Street Market Prediction
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>I thought I’d post an overview of my solution while I am relatively high on the leaderboard which might not last for long. My solution is based on a simple MLP with some elements that I have not seen posted before including a bit of feature and target engineering and weight-dependent voting in post-processing.</p>
<h1>1. CV Strategy</h1>
<p>For me this is by far the most important part – with the amount of noise in the data everything else would not be possible to evaluate without a decent CV strategy.</p>
<p>I’ve spent a huge chunk of time trying to find a validation approach that gave at least somewhat consistent and logical results. I eventually landed on using mean OOF utility scores similar to what I posted <a href="https://www.kaggle.com/dmitryvyudin/jane-street-oof-utility-scores" target="_blank">here</a>. From the very start I decided not to use the public LB other than to check that the code runs and does not time out – otherwise the temptation to overfit the public LB would be too difficult to resist. </p>
<p>I used all the data for both training and validation based on <code>GroupKFold</code> split using dates as groups – this was a risky decision as I assumed there was no leakage between training and validation dates. I have a few reasons to think that this leakage indeed was not a problem:<br>
• First, this seems to be an HFT competition – as <a href="https://www.kaggle.com/gregorycalvez" target="_blank">@gregorycalvez</a> noticed in this excellent <a href="https://www.kaggle.com/gregorycalvez/de-anonymization-time-aggregation-tags" target="_blank">notebook</a>, the <code>NaN</code> patterns suggest that the data contains some rolling intraday features. This does not mean that there are no other rolling features covering many days, but from my point of view, it does make it less likely/important.<br>
• I tried splitting data into groups of consecutive days – from 1 to 100 days in one group. In case of leakage you could expect to get better results with 1-day groups compared to 100-day groups because there is potentially much more interaction between training and validation data. But after tons of experiments I just could not see this effect.<br>
For the actual training I used groups of 50 consecutive days.<br>
• At the beginning I tried splitting data completely randomly, i.e. using trades from the same date both for training and validation. In this setup the intraday leakage was noticeable but even then my model had to run for a lot of epochs to pick up this information with validation scores continuing to improve even after 100’s of epochs. I have not observed this behavior with <code>GroupKFold</code>.</p>
<h1>2. Feature Engineering</h1>
<p>There were a number of discussions about the meaning of <code>feature_0</code> (buy/sell, long/short?). I have no idea what the correct answer is – my hypothesis is that it is produced by a separate JS model that selects the trading opportunities. And if this is true then its recent history might be indicative of some sort of market condition. This gave me an idea to build a series of rolling 'lag' features based on <code>feature_0</code> and this resulted in a modest but noticeable improvement in the CV scores.</p>
<p>I have also added a few other features based on the ‘clock’ <code>feature_64</code> that together also improved the CV score:<br>
• Binary feature representing part of the trading day (before/after lunch)<br>
• Number of trades suggested by JS algorithm earlier today (for the first part of the day) or after lunch (for the second part of the day) - the intuition here that together with 'clock' this feature could also represent a market condition (e.g. more trade opportunities = more volatility)<br>
• 'Gradient' of <code>feature_64</code> with respect to timestamp - similar intuition to the previous point</p>
<h1>3. Target Engineering</h1>
<p>Like many others, I have noticed that treating this task as multi-label classification leads to better results compared to trying to predict just one label - <code>resp</code>. I have made a couple of adjustments compared to most public notebooks:<br>
• I did not use <code>resp_4</code> - my CV always went down when I tried to add it. This could be to some extent explained by the fact (conjecture?) that the time horizon of <code>resp_4</code> is longer than that of <code>resp</code>.<br>
• Instead, I added the mean value of <code>resp</code>, <code>resp_1</code>, <code>resp_2</code> and <code>resp_3</code> as a separate target which did improve the CV score. This can be thought of as a proxy for the general direction of returns over the whole <code>resp</code> time horizon.</p>
<h1>4. Model & Training</h1>
<p>Nothing interesting architecture-wise – very basic 3-layer MLP with batch normalization and dropout. </p>
<p>For optimization I used <a href="https://arxiv.org/abs/1904.00962" target="_blank">LAMB </a> with Lookahead – according to the paper, LAMB is supposed to work well with large batch sizes and it seemed to outperform other optimizers I tried. </p>
<h1>5. Inference & Post-Processing</h1>
<p>I did not like the idea of playing with the threshold – values other than 0.5 seem artificial and lack any intuitive meaning. Instead, for most of the competition, I used a ‘qualified’ majority voting. I.e. only accepting the trade opportunity if 66% of models ‘voted’ for it. </p>
<p>Later on, I started taking the weight of the trading opportunity into account - the more the weight of the opportunity, the more confident I have to be to act on it. This results in slightly better utility scores since the utility score formula punishes high variance.</p>
<p>Overall I used 50 models (5 folds & 10 seeds) with each model having 5 votes – one vote per target.</p>
<h1>6. Code</h1>
<p>• Training - <a href="https://www.kaggle.com/dmitryvyudin/jane-street-tf-lamb" target="_blank">https://www.kaggle.com/dmitryvyudin/jane-street-tf-lamb</a><br>
• Inference - <a href="https://www.kaggle.com/dmitryvyudin/jane-street-weighted-voting-inference" target="_blank">https://www.kaggle.com/dmitryvyudin/jane-street-weighted-voting-inference</a></p>
<h1>7. Other</h1>
<p>Some of the things I tried but could not make work based on my CV strategy:<br>
• Treating the problem as regression as opposed to classification – much better results with L1 loss than MSE but still worse than classification<br>
• Using weight or log(weight) in the loss function<br>
• Adding noise to targets<br>
• Knowledge distillation as a target de-noising technique – this looked very promising but I found a leakage literally hours before the submission deadline and had to revert to earlier, simpler models<br>
• <a href="https://arxiv.org/abs/2006.00719" target="_blank">AdaHessian </a> optimizer (was very excited about the results initially but in the end LAMB performed better)<br>
• TabNet – found it too slow for this competition </p> |
NFL 1st and Future - Impact Detection | 50th place solution (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: NFL 1st and Future - Impact Detection
<|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 thank the Kaggle and NFL for hosting this interesting competition. And, special thanks to <a href="https://www.kaggle.com/its7171" target="_blank">@its7171</a> and <a href="https://www.kaggle.com/nvnnghia" target="_blank">@nvnnghia</a>.</p>
<p>The main ideas of my solution are model architecture and post-processing. Let me explain them.</p>
<h1>Model Architecture</h1>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1497263%2F6c129f8ae06a934bde53688382645c93%2F2021-01-05%2011.43.59.png?generation=1609814660849278&alt=media" alt=""></p>
<ul>
<li>Using multi frames(t, t-5, t-10)</li>
<li>Using 1x1 Conv2D to reduce computational costs</li>
<li>Training and predicting only the first 105 frames</li>
</ul>
<h1>Post-processing</h1>
<ol>
<li>Remove all boxes that aren't present in both Sideline and Endzone views<br>
<a href="https://www.kaggle.com/artkulak/2class-object-detection-inference-with-filtering/data" target="_blank">https://www.kaggle.com/artkulak/2class-object-detection-inference-with-filtering/data</a></li>
<li>Remove duplicate frames within +-4 frames (apply 2 times changing threshold)</li>
</ol>
<pre><code>result_df = pd.DataFrame()
for video_name in test_df.video.unique():
tmp = test_df.query('video == @video_name').sort_values(by='frame').reset_index(drop=True)
tmp_copy = deepcopy(tmp)
result_idxs = []
while len(tmp_copy) > 0:
idx = tmp_copy.index.min()
frame = tmp_copy.loc[idx, 'frame']
max_frame = frame + 9
candidates = tmp_copy.query('@frame < frame & frame < @max_frame')
if len(candidates) == 0:
result_idxs.append(idx)
tmp_copy.drop([idx], axis=0, inplace=True)
continue
frames = [idx]
for j in candidates.index:
s = 0
for col in ['left', 'top', 'width', 'height']:
s += abs(tmp_copy.loc[idx, col] - candidates.loc[j, col])
if s < 16:
frames.append(j)
if len(frames) == 1:
result_idxs.append(idx)
tmp_copy.drop(frames, axis=0, inplace=True)
elif len(frames) == 2:
result_idxs.append(tmp_copy.loc[frames]['scores'].idxmax())
tmp_copy.drop(frames, axis=0, inplace=True)
elif len(frames) >= 3:
result_idxs.append(frames[len(frames) // 2])
tmp_copy.drop(frames, axis=0, inplace=True)
result_df = pd.concat([result_df, tmp.iloc[result_idxs]])
result_df.reset_index(drop=True, inplace=True)
</code></pre> |
NFL 1st and Future - Impact Detection | [6th place solution] EfficientDet + 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: NFL 1st and Future - Impact Detection
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thank you to all participants and organizers!<br>
Thanks especially to <a href="https://www.kaggle.com/its7171" target="_blank">@its7171</a> and <a href="https://www.kaggle.com/nvnnghia" target="_blank">@nvnnghia</a> for sharing amazing notebooks!</p>
<p>My solution is made up of the following two stages.<br>
(Stage-1) Detect all helmets with EfficientDet-d5<br>
(Stage-2) Classify all helmet to impact or no impact with resnet18</p>
<p><img src="https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F3009367%2F027d750fd39f79ccdb7e6f9df7a43b7c%2Fnfl_hirai.jpg?generation=1609831143184495&alt=media" alt=""></p>
<h3>Stage-1</h3>
<p>I trained EfficientDet-d5 on helmet 1class.<br>
For training, I used the frames where collisions exist and frames where they don't. Training images are extracted from the video every 10 frames and +-5 frames of the frame with collisions.<br>
Images were enlarged to 1280*1280, and only horizontal flip was used for augmentation because loss converged faster.<br>
The inference was performed on two images, the original image, and the horizontally flipped image, and the results were merged using wbf.</p>
<h3>Stage-2</h3>
<p>I trained resnet18 on 2 classes(impact or not) and used it to classify the targeting helmet had collided.<br>
For resnet18 input, I cropped the image around the helmet and prepared 9 images from 4 frames before and after.<br>
The cropped image size is three times the longest side of the helmet rectangle(max(w,h) * 3).<br>
The cropped image was padded to square and resized to 112*112.</p>
<p>As in stage 1, the training images were extracted from the video every 10 frames and only the collision frame.<br>
When creating training data, the same evaluation criteria were used to label whether a collision occurred or not(impact=1, confidence>1, visibility>0).<br>
For augmentation, I used the alubumentation library and applied the following</p>
<ul>
<li>HorizontalFlip</li>
<li>RandomBrightness</li>
<li>RandomContrast</li>
<li>one of(MotionBlur,MedianBlur,GaussianBlur,GaussNoise)</li>
<li>HueSaturationValue</li>
<li>ShiftScaleRotate</li>
<li>Cutout</li>
</ul>
<p>In addition to the above, I also used the following augmentation</p>
<ul>
<li>Changed crop size randomly (max(w,h) * 2.5 ~ max(w,h) * 3.5)</li>
<li>Shifted cropping position randomly (-max(w,h) * 0.07 ~ max(w,h) * 0.07)</li>
<li>Replaced a random frame image with a black image (All 0's numpy array)</li>
</ul>
<p>When doing augmentation, the same augmentation is applied to all images in 9 frames.</p>
<p>I trained two resnet18 models(2d conv and 3d conv).<br>
For the 2d conv resnet18 input, the 9-frame images are combined in the RGB channels to form a 27-channel image.<br>
For the 3d conv resnet18 input, the 9-frame images are converted to a 9frame movie.</p>
<p>The inference process was performed on the two models, and the final output was the ensemble of the respective outputs.<br>
I also used the same flip tta as in stage-1.</p>
<h3>Post-Processing</h3>
<p>If helmets are detected in the same position within 4 frames, only the middle frame will be kept, and the others will be ignored.<br>
In addition, I ignored the first and last 10 frames of the video because it is expected to be a low collision.</p>
<h3>Score</h3>
<p>cv for EfficientDet-d5 : 0.926(for all helmets)<br>
roc_auc for 2d conv resnet18 : 0.964<br>
roc_auc for 3d conv resnet18 : 0.967<br>
cv for local : 0.53<br>
public score : 0.56<br>
private score : 0.59</p> |
Cassava Leaf Disease Classification | 30th solution 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: Cassava Leaf Disease Classification
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><h2>Acknowledgements</h2>
<p>Thanks to Kaggle and hosts for holding this competition.<br>
Thanks Kaggler!! This is my first silver medal :) </p>
<h2>Result</h2>
<ul>
<li>30th</li>
<li>Private Score 0.9010</li>
<li>Public Score 0.9018</li>
</ul>
<h2>Summary</h2>
<pre><code>My final submission is ensemble of EfficientNetB5 with Noisy Student and ResNext50(32x4d).
</code></pre>
<h2>Datasets</h2>
<pre><code>This competition datasets only. (I don't use 2019 datasets.)
</code></pre>
<h2>Preprocessing</h2>
<pre><code>Image size 512
Augumentations
- ResizeCrop
- Horizontal,VerticalFlip
- OneOf(RandomBrightness, RandomContrast)
- OneOf (RandomBlur,MedianBlur,GaussianBlur)
- ShiftScaleRotate
- Normalize
</code></pre>
<h2>Training</h2>
<pre><code>Optimizer Adam
Loss function CrossEntropyLoss
</code></pre>
<h2>Base Model CV</h2>
<pre><code>CV is StratifiedKFold 5 folds.
</code></pre>
<ul>
<li>EfficientNetB5<ul>
<li>CV average 0.8898</li>
<li>Public 0.894</li>
<li>Private 0.897</li></ul></li>
<li>ResNext50(32x4d)<ul>
<li>CV average 0.8898</li>
<li>Public 0.896</li>
<li>Private 0.894</li></ul></li>
</ul>
<p><a href="https://github.com/kazukim10/kaggle_CasavaLeafDeseaseClassfication" target="_blank">https://github.com/kazukim10/kaggle_CasavaLeafDeseaseClassfication</a></p> |
Cassava Leaf Disease Classification | 10th place solution (23rd 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: Cassava Leaf Disease Classification
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>It was my first Kaggle competition, and my goal was to jump into the top 200 and get a silver medal, but luckily I ended up with gold, and I'm very happy with the result. On the other hand, I understand that it was a lottery, and many participants have better models, but they did not choose it. I decided to select my best LB (0.9079, 23rd) and one of the best CV with a high LB score (0.9066 LB, top-70). The last one, as I expected, gave me 10th place at the private LB, funny that this was my final submission in the competition, and I even called it "good_luck" :)</p>
<p>But anyway, it looks like the guys from 1st place (and probably others, will see) have built something special, and many other solutions in the 0.899-0.903 range are very close. It's also sad that some people who shared good ideas and notebooks didn't get the expected place. I want to thank <a href="https://www.kaggle.com/piantic" target="_blank">@piantic</a> (Heroseo) for the great notebooks and <a href="https://www.kaggle.com/hengck23" target="_blank">@hengck23</a> for so many ideas shared.</p>
<p>Below you can find the key items of my solution. My solution is pretty simple, and I think many participants used a similar approach, but probably someone finds it to be useful.</p>
<h3>Approach (tldr)</h3>
<ul>
<li>Prevent overfitting on noise, but don't clean or re-label the dataset.</li>
<li>Trust your CV, but use public LB as a double-check (but towards the end of the competition, when I saw such close results, I decided to trust CV even more, especially given the number of test samples in LB and CV).</li>
<li>Key things that worked for me: noise removal (~2-3%), OUSM loss, mixup/cutmix, TTA</li>
</ul>
<h3>Submissions</h3>
<h6>Single models (5 folds, 4xTTA)</h6>
<table>
<thead>
<tr>
<th>#</th>
<th>Model</th>
<th>Dataset</th>
<th>CV</th>
<th>LB</th>
<th>Private</th>
</tr>
</thead>
<tbody>
<tr>
<td>model-1</td>
<td>DeiT-base-384</td>
<td>2020 + 2019 data</td>
<td>0.901</td>
<td>0.9043</td>
<td>0.8950</td>
</tr>
<tr>
<td>model-2</td>
<td>EffNet-B4</td>
<td>2020 data</td>
<td>0.901</td>
<td>0.9048</td>
<td>0.8975</td>
</tr>
<tr>
<td>model-3</td>
<td>EffNet-B4</td>
<td>2020 + 2019 data</td>
<td>0.906</td>
<td>0.9025</td>
<td><strong>0.9010</strong></td>
</tr>
</tbody>
</table>
<p>Note: "<em>2020 + 2019 data</em>" means upsampling for minor classes using the 2019 dataset (duplicates were removed, use only 2020 for testing), and model-3 is better not only because of 2019 data, but rather due to mixup/cutmix. And yes, as others have already mentioned, there are many unexpected scores at private LB for models I didn't select, e.g. one of the model-1 fold has 0.899 private score (while 5 folds ensemble 0.895).</p>
<h6>Ensembles</h6>
<table>
<thead>
<tr>
<th>(just avg)</th>
<th>LB</th>
<th>Private</th>
</tr>
</thead>
<tbody>
<tr>
<td>model-1 + model-2 + model-3</td>
<td>0.9066</td>
<td><strong>0.9017</strong></td>
</tr>
<tr>
<td>model-1 + model-2</td>
<td>0.9079</td>
<td>0.8998</td>
</tr>
<tr>
<td>model-1 + model-3 (not selected, CV=0.907)</td>
<td>0.9066</td>
<td>0.9013</td>
</tr>
</tbody>
</table>
<p>Due to my vacation, for the last 2 weeks, I didn't train new models (but there was some potential in improving the 3rd model), but only tried to make an ensemble from what I already had.</p>
<h3>Noisy data</h3>
<p>It was quite obvious that private data is also noisy. After analyzing the dataset and reading various articles on cassava diseases, I assumed that there are different types of noise, so eliminating all of the noise can be risky. My approach was:</p>
<ul>
<li>Remove only ~2-3% of data (noise) using OOF confident predictions to reduce the overall % of noise in the dataset, but keep "useful" noise.</li>
<li>Use part of OUSM loss (without re-weighting) - <a href="https://arxiv.org/pdf/1901.07759.pdf" target="_blank">https://arxiv.org/pdf/1901.07759.pdf</a> . I enable it after N epochs to let the model normally train before it starts to memorize the noise, and I also modified it a little bit to use with a smaller batch size of 16 (i.e. remove a loss even for 1 sample per batch is too much).</li>
<li>Standard but strong augmentations to prevent overfitting (to train longer).</li>
<li>Early stopping. At some point, I noticed that my valid accuracy is still improving slightly, but train accuracy is already too high, it didn't look like classic overfitting. So I tried early-stopping by max train accuracy, and it helped to climb LB with the same CV score. Later, when I added mixup/cutmix, that behavior disappeared (less overfit).</li>
<li>Mixup/Cutmix (I also disable it completely for the last 3 epochs). Unfortunately, I tried it too late… and just trained 2 models with some default parameters. But after looking at the private LB scores it turned out to be an important part of my best model (both CV and private LB). In the mixup paper ( <a href="https://arxiv.org/pdf/1710.09412.pdf" target="_blank">https://arxiv.org/pdf/1710.09412.pdf</a> ) you can also find that it helps in training with corrupted labels.</li>
</ul>
<p>There are other noise-robust losses and loss correction techniques, but I didn't try them due to lack of time.</p>
<h3>TTA</h3>
<p>I rarely use TTA in my work due to performance reasons (except when it is offline processing and it provides significant improvements), so it was a surprise that it can help so much in competitions.<br>
TTA gave me a stable 0.001-0.002 improvement in all experiments for both CV and LB. I used horizontal/vertical flips + zoom (crop 384 -> resize to 512).<br>
"Zoom" augmentation was especially good for both DeiT and EffNet. When I found that, I even tried to build an additional classifier to pre-process all images (both for training&testing) to crop not close-ups samples. The classifier (close-up or not) worked very well, but CV score slightly dropped, so I decided to not proceed with that idea.</p>
<h3>Distillation</h3>
<p>I previously used knowledge distillation, self-distillation, … several times at work <a href="https://towardsdatascience.com/distilling-bert-using-unlabeled-qa-dataset-4670085cc18" target="_blank">https://towardsdatascience.com/distilling-bert-using-unlabeled-qa-dataset-4670085cc18</a> , and it gave me the highest single model CV score (0.91+) in this competition. But I didn't use it because I was afraid of an implicit leak through the soft labels (or weighted soft+ground truth) that I generated from the OOF predictions. But all my distillation experiments were done with a weaker model/teacher, and later I did not try to use it again, perhaps it could help.</p>
<h3>Other things that worked well for me</h3>
<ul>
<li>Label smoothing (0.2 - 0.3)</li>
<li>Sometimes Taylor Loss (+label smoothing) was better than Cross-Entropy, I didn't try Bi-Tempered loss.</li>
</ul>
<h3>Training</h3>
<ul>
<li>GPU: I used my 2080TI and Colab Pro.</li>
<li>PyTorch</li>
<li>Adam, cosine annealing with a warmup, 16 batch size, gradient accumulation, fp16. </li>
</ul>
<p>The most important thing I want to point out is that I learned something useful from this competition - various strategies for dealing with noisy data. I have not tried many of them due to lack of time, but I am sure that knowledge will help in my work.</p>
<p>Thank you to the organizers and all the participants. Let me know if you have any questions and see you in the next competitions! </p> |
Santa 2020 - The Candy Cane Contest | 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: Santa 2020 - The Candy Cane Contest
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>Thank you for hosting this exciting competition ! I'm happy to become a Competition Grandmaster.</p>
<h1>Code</h1>
<p>Source code is available here.<br>
<a href="https://github.com/toshi-k/kaggle-santa-2020" target="_blank">https://github.com/toshi-k/kaggle-santa-2020</a></p>
<h1>Basic Strategy</h1>
<p>In this competition, the reward was decided by comparing the threshold and random generated number. It was easy to calculate the probability of getting reward if we knew the thresholds. But the agents can't see the threshold during the game, we had to estimate it.</p>
<p>Like other teams, I also downloaded the history by Kaggle API and created a dataset for supervised learning. We can see the true value of <code>threshold</code> at each round in the response of API. So, I used it as the target variable.</p>
<p>In the middle of the competition, I found out that quantile regression is much better than conventional L2 regression. I think it can adjust the balance between <strong>Explore</strong> and <strong>Exploit</strong> by the percentile parameter.</p>
<h1>Features</h1>
<p>I made 32 features for training and prediction. I tried some other features, but they didn't work well. Adding unnecessary features sometimes caused time out error, I didn't employ them.</p>
<table>
<thead>
<tr>
<th> # </th>
<th>Name</th>
<th>Explanation</th>
</tr>
</thead>
<tbody>
<tr>
<td>#1</td>
<td>round</td>
<td>number of round in the game (0-1999)</td>
</tr>
<tr>
<td>#2</td>
<td>last_opponent_chosen</td>
<td>whether the opponent agent chose this machine in the last step or not</td>
</tr>
<tr>
<td>#3</td>
<td>second_last_opponent_chosen</td>
<td>whether the opponent agent chose this machine in the second last step or not</td>
</tr>
<tr>
<td>#4</td>
<td>third_last_opponent_chosen</td>
<td>whether the opponent agent chose this machine in the third last step or not</td>
</tr>
<tr>
<td>#5</td>
<td>opponent_repeat_twice</td>
<td>whether the opponent agent continued to choose this machine in the last two rounds (#2 x #3)</td>
</tr>
<tr>
<td>#6</td>
<td>opponent_repeat_three_times</td>
<td>whether the opponent agent continued to choose this machine in the last three rounds (#2 x #3 x #4)</td>
</tr>
<tr>
<td>#7</td>
<td>num_chosen</td>
<td>how many times the opponent and my agent chose this machine</td>
</tr>
<tr>
<td>#8</td>
<td>num_chosen_mine</td>
<td>how many times my agent chose this machine</td>
</tr>
<tr>
<td>#9</td>
<td>num_chosen_opponent</td>
<td>how many time the opponent agent chose this machine (#7 - #8)</td>
</tr>
<tr>
<td>#10</td>
<td>num_get_reward</td>
<td>how many time my agent got rewards from this machine</td>
</tr>
<tr>
<td>#11</td>
<td>num_non_reward</td>
<td>how many time my agent didn't get rewarded from this machine</td>
</tr>
<tr>
<td>#12</td>
<td>rate_mine</td>
<td>ratio of my choices against the total number of choices (#8 / #7)</td>
</tr>
<tr>
<td>#13</td>
<td>rate_opponent</td>
<td>ratio of opponent choices against the total number of choices (#9 / #7)</td>
</tr>
<tr>
<td>#14</td>
<td>rate_get_reward</td>
<td>ratio of my rewarded choices against the total number of choices (#10 / #7)</td>
</tr>
<tr>
<td>#15</td>
<td>empirical_win_rate</td>
<td>posterior expectation of threshold value based on my choices and rewords</td>
</tr>
<tr>
<td>#16</td>
<td>quantile_10</td>
<td>10% point of posterior distribution of threshold based on my choices and rewords</td>
</tr>
<tr>
<td>#17</td>
<td>quantile_20</td>
<td>20% point of posterior distribution of threshold based on my choices and rewords</td>
</tr>
<tr>
<td>#18</td>
<td>quantile_30</td>
<td>30% point of posterior distribution of threshold based on my choices and rewords</td>
</tr>
<tr>
<td>#19</td>
<td>quantile_40</td>
<td>40% point of posterior distribution of threshold based on my choices and rewords</td>
</tr>
<tr>
<td>#20</td>
<td>quantile_50</td>
<td>50% point of posterior distribution of threshold based on my choices and rewords</td>
</tr>
<tr>
<td>#21</td>
<td>quantile_60</td>
<td>60% point of posterior distribution of threshold based on my choices and rewords</td>
</tr>
<tr>
<td>#22</td>
<td>quantile_70</td>
<td>70% point of posterior distribution of threshold based on my choices and rewords</td>
</tr>
<tr>
<td>#23</td>
<td>quantile_80</td>
<td>80% point of posterior distribution of threshold based on my choices and rewords</td>
</tr>
<tr>
<td>#24</td>
<td>quantile_90</td>
<td>90% point of posterior distribution of threshold based on my choices and rewords</td>
</tr>
<tr>
<td>#25</td>
<td>repeat_head</td>
<td>how many times my agent chose this machine before the opponent agent chose this agent for the first time</td>
</tr>
<tr>
<td>#26</td>
<td>repeat_tail</td>
<td>how many times my agent chose this machine after the opponent agent chose this agent last time</td>
</tr>
<tr>
<td>#27</td>
<td>repeat_get_reward_head</td>
<td>how many times my agent got reward from this machine before my agent didn't get rewarded or the opponent agent chose this agent for the first time</td>
</tr>
<tr>
<td>#28</td>
<td>repeat_get_reward_tail</td>
<td>how many times my agent got reward from this machine after my agent didn't get rewarded or the opponent agent chose this agent last time</td>
</tr>
<tr>
<td>#29</td>
<td>repeat_non_reward_head</td>
<td>how many times my agent didn't get rewarded from this machine before my agent got reward or the opponent agent chose this agent for the first time</td>
</tr>
<tr>
<td>#30</td>
<td>repeat_non_reward_tail</td>
<td>how many times my agent didn't get rewarded from this machine after my agent got reward or the opponent agent chose this agent last time</td>
</tr>
<tr>
<td>#31</td>
<td>opponent_repeat_head</td>
<td>how many times the opponent agent chose this machine before my agent chose this machine for the first time</td>
</tr>
<tr>
<td>#32</td>
<td>opponent_repeat_tail</td>
<td>how many times the opponent agent chose this machine after my agent chose this machine last time</td>
</tr>
</tbody>
</table>
<p>The feature importance of my best agent is as below.</p>
<p><img src="https://raw.githubusercontent.com/toshi-k/kaggle-santa-2020/master/src/02_lgbm/importance.png" alt="importance"></p>
<p>It may be interesting the most important feature was the <em>round</em> in the game. I think the agent can change the strategy based on the round, and it was something essential the agent learned from the history.</p>
<p>Some other features related to the opponent agent were also important (<em>num_chosen_opponent</em>, <em>rate_opponent</em>) . ML based agent can utilize the behavior of the opponent agent which can't be handled by conventional approaches.</p>
<h1>Top Agents</h1>
<p>I tried several packages and parameters. It seemed that LightGBM was the best for my settings.</p>
<p>Although some of CatBoost agents achieved similar performance like LightGBM, CatBoost didn't reach the best score of LightGBM. Since all features were numeric variable, it could not utilize the unique feature for categorical variables.</p>
<p>I also tried XGBoost with pairwise loss. It compared the thresholds of machines in the same round. Although I thought it was a natural training setting, the performance of the agents were worse than quantile regression.</p>
<p>NumRound=4000 was almost the maximum number to prevent the time out error. I set NumRound=3000 or NumRound=3500 for some agents as safer settings. I basically tuned learning rate to control the fitness to the dataset.</p>
<table>
<thead>
<tr>
<th>Regressor</th>
<th>Loss</th>
<th>NumRound</th>
<th>LearningRate</th>
<th>LB Score</th>
<th>SubmissionID</th>
</tr>
</thead>
<tbody>
<tr>
<td>LightBGM</td>
<td>Quantile (0.65)</td>
<td>4000</td>
<td>0.05</td>
<td>1449.4</td>
<td><a href="https://www.kaggle.com/c/santa-2020/submissions?dialog=episodes-submission-19318812" target="_blank">19318812</a></td>
</tr>
<tr>
<td>LightBGM</td>
<td>Quantile (0.65)</td>
<td>4000</td>
<td>0.10</td>
<td>1442.1</td>
<td><a href="https://www.kaggle.com/c/santa-2020/submissions?dialog=episodes-submission-19182047" target="_blank">19182047</a></td>
</tr>
<tr>
<td>LightBGM</td>
<td>Quantile (0.65)</td>
<td>3000</td>
<td>0.03</td>
<td>1438.8</td>
<td><a href="https://www.kaggle.com/c/santa-2020/submissions?dialog=episodes-submission-19042049" target="_blank">19042049</a></td>
</tr>
<tr>
<td>LightBGM</td>
<td>Quantile (0.66)</td>
<td>3500</td>
<td>0.04</td>
<td>1433.9</td>
<td><a href="https://www.kaggle.com/c/santa-2020/submissions?dialog=episodes-submission-19137024" target="_blank">19137024</a></td>
</tr>
<tr>
<td>CatBoost</td>
<td>Quantile (0.65)</td>
<td>4000</td>
<td>0.05</td>
<td>1417.6</td>
<td><a href="https://www.kaggle.com/c/santa-2020/submissions?dialog=episodes-submission-19153745" target="_blank">19153745</a></td>
</tr>
<tr>
<td>CatBoost</td>
<td>Quantile (0.67)</td>
<td>3000</td>
<td>0.10</td>
<td>1344.5</td>
<td><a href="https://www.kaggle.com/c/santa-2020/submissions?dialog=episodes-submission-19170829" target="_blank">19170829</a></td>
</tr>
<tr>
<td>LightGBM</td>
<td>MSE</td>
<td>4000</td>
<td>0.03</td>
<td>1313.3</td>
<td><a href="https://www.kaggle.com/c/santa-2020/submissions?dialog=episodes-submission-19093039" target="_blank">19093039</a></td>
</tr>
<tr>
<td>XGBoost</td>
<td>Pairwised</td>
<td>1500</td>
<td>0.10</td>
<td>1173.5</td>
<td><a href="https://www.kaggle.com/c/santa-2020/submissions?dialog=episodes-submission-19269952" target="_blank">19269952</a></td>
</tr>
</tbody>
</table>
<h1>Tips</h1>
<h2>Logarithm transformation for probabilistic calculation</h2>
<p>The chain of multiplication turns into zero because of the precision of floating point. For the calculation of posterior distribution of threshold, logarithm transformation and renormalization solved this problem.</p>
<h2>LRU Cache</h2>
<p>Precise calculation of posterior distribution is time consuming and it can be the cause of time our error. I employed LRU (Least Recently Used) Cache and reused the feature values for the same patterns of the actions and rewards.</p>
<h1>What I should have done (to beat more agents)</h1>
<p>When I calculated the winning rate of the agent for features #15-24, I set the probability approximately like <code>p = threshold ** decay / 101</code>. But I missed one important point here. The random generated in each round was integer, I should have rounded this part like <code>p = round(threshold ** decay) / 101</code>.</p> |
Santa 2020 - The Candy Cane Contest | 409th Place Solution - Copy Opponent Move Unless Win | 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: Santa 2020 - The Candy Cane Contest
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>I didn't really have time to properly explore this competition to the same depth I explored Rock Paper Scissors, so in this competition, I cheated!</p>
<p>My highest scoring original agent was: </p>
<p><strong>Rock Paper Candy - Copy Opponent Move Unless Win (744.8)</strong></p>
<ul>
<li><a href="https://www.kaggle.com/jamesmcguigan/rock-paper-candy-copy-opponent-move-unless-win" target="_blank">https://www.kaggle.com/jamesmcguigan/rock-paper-candy-copy-opponent-move-unless-win</a></li>
</ul>
<p>Does exactly what it says on the tin. Rather than implement my own logic for finding the best handle to pull, I implemented the Little Sister strategy. Little Sister doesn't know how to play the game, she simply runs after her Big Brother and plays whatever move he played last. Unless of course she wins, in which case she keeps pulling the same handle until she loses and then runs after Big Brother again.</p>
<p>I tried a few variations to modify the logic of when to repeat and when to copy, but the original and simplest logic worked best. The result of this strategy was 1.3% below the exact midpoint of the leaderboard!</p>
<p>This approach outperformed all my failed attempts to implement UCB and Multi-Armed-Bandit correctly.</p>
<p>My other approach was to compile a big list of public notebooks, play them against each other, and repeatedly submit the best ones to the competition as my own work, which really feels like cheating now that I have done it!</p>
<ul>
<li><a href="https://www.kaggle.com/jamesmcguigan/santa-2020-agents-comparison" target="_blank">https://www.kaggle.com/jamesmcguigan/santa-2020-agents-comparison</a></li>
</ul>
<p>Shoutouts to:</p>
<p><a href="https://www.kaggle.com/felipefonte99" target="_blank">@felipefonte99</a> </p>
<ul>
<li>Your ensemble model scored 859.7 - 793.0 over 14 submissions, earning me 335th place!</li>
<li><a href="https://www.kaggle.com/felipefonte99/ensemble-pull-vegas-decision-tree-model" target="_blank">https://www.kaggle.com/felipefonte99/ensemble-pull-vegas-decision-tree-model</a></li>
</ul>
<p><a href="https://www.kaggle.com/iehnrtnc" target="_blank">@iehnrtnc</a></p>
<ul>
<li>Your agent3.py notebook scored 823.6 - 781.4 over 6 submissions.</li>
<li><a href="https://www.kaggle.com/iehnrtnc/santa2020" target="_blank">https://www.kaggle.com/iehnrtnc/santa2020</a></li>
</ul>
<p><a href="https://www.kaggle.com/sirishks" target="_blank">@sirishks</a></p>
<ul>
<li>Your advice to "Keep pulling the same bandit as long as reward keeps coming!" helped inspire the Copy Opponent Move Unless Win strategy</li>
<li>Your notebook scored 761.0 with a single submission yet still outperformed my own notebook idea<br>
= <a href="https://www.kaggle.com/sirishks/pull-vegas-slot-machines" target="_blank">https://www.kaggle.com/sirishks/pull-vegas-slot-machines</a></li>
</ul> |
HuBMAP - Hacking the Kidney | 35th solution, seg&yolo | 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: HuBMAP - Hacking the Kidney
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>lb0.933, pb0.946<br>
inference code:<a href="https://www.kaggle.com/kevin1742064161/seg-yolo-final-inference?scriptVersionId=62406590" target="_blank">https://www.kaggle.com/kevin1742064161/seg-yolo-final-inference?scriptVersionId=62406590</a><br>
ensemble of 4 model:unet+b2, unet+b4, unetplusplus+b2, manet+b4<br>
window:1024<br>
overlap:100<br>
size:512<br>
YOLOv5 is used to detect cells. By comparing the area of the bonding box with the area of the segmentation, we can judge whether the segmentation result needs to be filled.<br>
Just trust your CV!</p> |
Santa 2020 - The Candy Cane Contest | 14th Place Solution (Looking for teammates) | 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: Santa 2020 - The Candy Cane Contest
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>We'd like to thank the Kaggle team for hosting the Santa 2020 competition during a tough year. In this competition, I had the pleasure of teaming up with <a href="https://www.kaggle.com/lihuajing" target="_blank">Alex</a>, <a href="https://www.kaggle.com/nischaydnk" target="_blank">Nischay Dhankhar</a>, <a href="https://www.kaggle.com/chaudharypriyanshu" target="_blank">Priyanshu Chaudhary</a>, and <a href="https://www.kaggle.com/soosten" target="_blank">Per von Soosten
(PS)</a>. This is a summary of our team's solution which placed 14th on the leaderboard. Our <a href="https://github.com/soosten/candy-canes/blob/main/agent.py" target="_blank">best agent</a> is relatively simple, with only about 100 lines of code (<a href="https://github.com/soosten/candy-canes" target="_blank">github repo</a>).</p>
<p>TL;DR: We relied on a Bayesian Bandit approach with a few heuristics.</p>
<h3>Local Simulations</h3>
<p>We used a pool of opponents to evaluate our agents. Running a large number of matches against these opponents gave us a rough idea of agent performance, but improvements in local win rate did not always translate well to the leaderboard. Our pool of opponents included some of our own agents and a few agents from public notebooks:</p>
<ul>
<li>opponent_agent.py and submission.py from <a href="https://www.kaggle.com/a763337092/pull-vegas-slot-machines-add-weaken-rate-continue5" target="_blank">pull_vegas_slot_machines add weaken rate continue5</a></li>
<li>thompson.py from <a href="https://www.kaggle.com/xhlulu/santa-2020-thompson-sampling" target="_blank">Santa 2020: Thompson Sampling</a></li>
<li>bayesian_ucb.py from <a href="https://www.kaggle.com/xhlulu/santa-2020-ucb-and-bayesian-ucb-starter" target="_blank">Santa 2020: UCB and Bayesian UCB Starter</a></li>
<li>submission.py from <a href="https://www.kaggle.com/ilialar/simple-multi-armed-bandit" target="_blank">Simple multi-armed bandit</a></li>
</ul>
<p>Thank you to <a href="https://www.kaggle.com/a763337092" target="_blank">Lindada焱焱焱</a>, <a href="https://www.kaggle.com/xhlulu" target="_blank">xhlulu</a> and <a href="https://www.kaggle.com/ilialar" target="_blank">Ilia Larchenko</a> for making these notebooks public. </p>
<h3>Bayesian approach</h3>
<p>The basic logic of our final submission is to maintain a set of distributions reflecting what we know about the current reward probability of each arm. At the outset, these distributions are initialized to a uniform prior. Every time we get a result from our previous pull, we perform a Bayesian update on the corresponding distribution reflecting the result of our previous pull. This is a classical idea for dealing with multi-armed bandits.</p>
<h3>Choosing the next arm</h3>
<p>We decide on which new arm to pull based on a simplified variant of the Bayesian UCB algorithm. We get an optimistic estimate of the reward probability of each arm by adding the mean and the standard deviation of the corresponding distribution and then choose an arm with a maximal estimate. An important part of the game is to understand when the opponent has discovered an arm with a high reward probability before the opponent has exploited that arm enough to dramatically decrease the probability. We tried to incorporate this information by applying some temporary Bayesian updates to the distribution before computing the mean and standard deviation comprising the estimate. More concretely:</p>
<ul>
<li>If the opponent pulled an arm more than twice in the last 10 turns, we assumed all of those pulls resulted in a reward.</li>
<li>If the opponent pulled an arm exactly once in the last 100 turn, we assumed that pull did not result in a reward.</li>
</ul>
<p>Our local simulations indicated that the optimal strategy never pulls on an arm with a reward probability less than 0.22. Therefore, we stopped applying temporary updates to arms for which the true estimate (without any temporary updates) was less than 0.25. This ensured that we did not follow the opponent to arms which we already knew were bad.</p>
<h3>Decaying thresholds</h3>
<p>In principle, the distributions should also reflect the decay in the reward probability after each arm is pulled. However, we noticed that our agents that did not use the opponent's actions to decay their estimates performed surprisingly well. One explanation for this is that not decaying encourages the agent to exploit good machines that the opponent has found, this is especially important early in the game. On the other hand, having correct estimates of the thresholds is important near the end of the game. We attempted to get the best of both worlds by averaging these two estimates (with/without opponent decay) with a weight that favors non-decayed estimates early in the game and decayed estimates later in the game.</p>
<h3>Learning from opponent actions</h3>
<p>Finally, some opponent actions are so indicative of the result their pulls that we conservatively applied some permanent Bayesian updates to the distribution based on them. We hardcoded the logic needed to learn from these opponent actions. This can work well against agents who are greedy with respect to their threshold estimates, but these hardcoded rules are easy to counter by being deceptive. Here are the rules that we used</p>
<ul>
<li>If the opponent repeats a first-time action, assume the first time is a success.</li>
<li>If the opponent doesn't pull a lever for a long time after pulling it for the first time, it is probably because the first time was a failure.</li>
</ul> |
Riiid Answer Correctness Prediction | the simplest numpy solution with a robust 744 | 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: Riiid Answer Correctness Prediction
<|user|>Explain and teach me concepts from Kaggle competition solution write-ups that solved this challenge
<|assistant|><p>New to the platform.<br>
Wanted to share my simple solution.</p>
<p>Interestingly, this few-liner pure stats solution performed better, than the simple LGB I used, which is most probably my bad 😊😊😊</p>
<p><a href="url" target="_blank">https://www.kaggle.com/abdulkadirguner/score-pblb0744</a></p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.