r/MachineLearning • u/__data_science__ • Mar 23 '21
Discussion [D] Advanced Takeaways from fast.ai book
I recently read the Fast AI deep learning book and wanted to summarise some of the many advanced takeaways & tricks I got from it. I’m going to leave out the basic things because there’s enough posts about them, i’m just focusing on what I found new or special in the book.
I’ve also put the insights into a deck on save all to help you remember them over the long-term. I would massively recommend using a spaced repetition app like anki or save all for the things you learn otherwise you’ll just forget so much of what is important. Here’s the takeaways:
Neural Network Training Fundamentals
Always start an ML project by producing simple baselines
If is binary classification then could even be as simple as predicting the most common class in the training dataset
Other baselines: linear regression, random forest, boosting etc…
Then you can use your baseline to clean your data by looking at the datapoints it gets most incorrect and checking to see if they are actually classified correctly in the data
In general you can also leverage your baselines to help debug your models
e.g. if you make your neural network 1 layer then it should be able to match the performance of a linear regression baseline, if it doesn’t then you have a bug!
e.g. if adding a feature improves the performance of linear regression then it should probably also improve the performance of your neural net unless you have a bug!
Hyperparameter optimisation can help a bit (especially for the learning rate) but in general there are default hyperparameters that can do quite well and so closely optimising the hyperparameters should be one of the last things you try rather than the first
If you know something about the problem then try to inject it as an inductive bias into the training process
e.g. if some of your features are related in a sequential way then incorporate them into training separately using an RNN
e.g. if you know the output should only be between -3 and 3 then use sigmoid to design the final layer so that it forces the output of the network to be in this range
Transfer Learning
Always use transfer learning if you can by finding a model pre-trained for a similar task and then fine-tune that model for your particular task
e.g. see huggingface for help with this in NLP
Gradual unfreezing and discriminative learning rates work well when fine-tuning a transfer learned model
Gradual unfreezing = freeze earlier layers and train the later layers only, then gradually unfreeze the earlier layers one by one
Discriminative learning rates = having different learning rates per layer of your network (usually earlier layers have smaller learning rates than later layers)
Tricks to Deal with Overfitting
Best way to deal with overfitting is by getting more data. Exhaust this first before you start regularising with other methods
Data augmentation is really powerful and now possible with text as well as images:
Image data augmentation - crop, pad, squish and resize images
Text data augmentation - negate words, replace words with similes, perturb word embeddings (nice github repo for this)
Mixup regularisation = create new data by averaging together training datapoints
Backwards training (NLP only): train an additional separate model that is fed text backwards and then average the outputs of your two models to get your final prediction
Other Tricks to Improve Performance
Test time augmentation = at test time, use the average prediction from many augmented versions of the input as your prediction rather than just the prediction from the true input
1 cycle training = when you increase and reduce the learning rate throughout training in a circular fashion (usually makes a huge difference)
Learning rate finder algorithm = algorithm that Fast AI provide to help you automatically discover roughly the best learning rate
Never use one-hot encodings, use embeddings instead, even in tabular data!
Using AdamW instead of Adam can help a little bit
Lower precision training can help and on pytorch lightning is just a simple flag you can set
For regression problems if you know the output should be within a range then its good to use sigmoid to force the neural net output to be within this range
I.e. make the network output: min_value + sigmoid(output) * (max_value - min_value)
Clustering your features can help you identify which ones are the most redundant and then removing the can help performance
Label smoothing = use 0.1 and 0.9 instead of 0 and 1 for label targets (can smoothen training)
Don’t dichotomise your data, if your output is continuous then its better to train the network to predict continuous values rather than turning it into a classification problem
Progressive resizing = train model on smaller resolution images first, then increase resolution gradually (can speed up training a lot)
Strategically using bottleneck layers to force the network to form more compact representations of the data at different points can be helpful
Try using skip connections as they can help smooth out the loss surface
Please let me know if you found this helpful and if there are any other training tricks you use that we should also know about?
17
u/Raz4r PhD Mar 23 '21
> For regression problems if you know the output should be within a range then its good to use sigmoid to force the neural net output to be within this range
I.e. make the network output: min_value + sigmoid(output) * (max_value - min_value)
Your network may have difficulties predicting the max_value if this is in your output layer.
7
u/__data_science__ Mar 23 '21
Yeah good point, in the book they actually suggest you make the possible range slightly wider than the true range to deal with that problem, I should have mentioned that
2
u/thunder_jaxx ML Engineer Mar 23 '21
I agree with this. Scaling affects the loss fn and can mess up the optimization because the bounds of max/min can change through the training process. It's better to not scale at all till training is finished. Once trained one can easily scale as sigmoid outputs are bounded.
1
u/BorisMarjanovic Mar 24 '21
I think you could make the min/max learnable to address this issue.
1
u/thunder_jaxx ML Engineer Mar 24 '21
What does a learned max/min mean? What are the training dynamics for such a representation?
1
u/BorisMarjanovic Mar 24 '21
I was thinking something like this (implemented in PyTorch):
class SigmoidRange(nn.Module):
def __init__(self, low=-1., high=1.):
super().__init__()
self.low = nn.Parameter(torch.tensor(low))
self.high = nn.Parameter(torch.tensor(high))
self.sigmoid = nn.Sigmoid()
def forward(self, x):
return self.sigmoid(x) * (self.high - self.low) + self.lowIf you add this piece of code after your output layer, the model will learn what the min/max should be.
But now that I think about it it's not an optimal solution. You could still encounter out of sample examples that don't fit the learned min/max treshold.
1
u/thunder_jaxx ML Engineer Mar 24 '21
Don't u think you need a loss for the
self.loworself.high? If we assume that we are fittingself.sigmoid(x) * (self.high - self.low) + self.lowthen just the supervised loss on the quantity won't be enough as the learnedself.high/self.loware not guaranteed to be bounded.
4
u/szybe Mar 23 '21
God bless you for sharing this. I am a newbie when it comes to ML and this helped me make two more forward steps in my journey.
2
3
3
u/anax4096 Mar 24 '21
This paper has a bunch of tips I've found valuable: https://arxiv.org/abs/1812.01187
The most effective has been learning rate warmups. Just cannot overstate how effective that has been, particularly on small dataset problems.
1
0
Apr 08 '21
[deleted]
2
u/anax4096 Apr 09 '21
yes, very much so. I usually have a batch size of one (no batches?) due to memory limitations on the GPU. Even with larger memory areas, the batch size might be limited to 8 volume images, etc.
Broadly, I treat batches as an optimisation of training which work by "averaging out" the error from specific examples: when the batch size is small (<8) you are more exposed to bad data, when the batch size is large (>512) the bad data responses will be "averaged out" but may raise your training bias. In both cases, k-folds can help you identify bad data.
Hope that helps.
5
2
u/reddit_wisd0m Mar 24 '21
What's the idea behind label smoothing? I don't see the advantage.
2
u/__data_science__ Mar 24 '21
2
u/reddit_wisd0m Mar 24 '21
Thx. So, if I understand it correctly, it's a trick to prevent overfitting.
2
u/Deeppop Mar 24 '21
This was very helpful! Please make this into an anki deck (if you use anki) and share it!
1
u/__data_science__ Mar 24 '21 edited Nov 20 '21
i don't use anki anymore but i've made it into a saveall public deck that you can use, it's quite fun as the questions are multiple choice
1
u/DancesWithWhales May 01 '21
Thanks so much for sharing this! The saveall link says "Deck not found". Do you have a new link? I'm new to spaced repetition apps, so if you're using something else, I'd love to hear your recommendation.
2
u/__data_science__ May 01 '21 edited Nov 20 '21
Apologies, the deck link in the post became out of date. This is the link now, let me know if it doesn't work? To start using the deck you have to click copy, you might also have to create an account first
1
u/DancesWithWhales May 02 '21
Thank you! Sadly that link doesn't work either, though. I went to the "public decks" section, and found it there!
2
33
u/DataPlug Mar 24 '21
As much as people get into the hickory depths of dealing with text/image data. We fail to recognize that the most type of data being dealt with is tabular followed by time series. I can barely find great resources on time series with neural nets or seq2seq or lstm but if I do a flimsy search on those keywords Im always met with the most advanced guides dealing with images/text and even audio.
I dont mean to rant but I just wish there was a plethora of easy-to-follow tips/tricks/guides on time series data just as there is images/text.
Great post nonetheless OP!
8
u/ToucheMonsieur Mar 24 '21
As someone who works with time series on the daily, I feel your pain. One difficulty is that techniques may differ depending on the source, frequency and seasonality of the time series. For example, an RNN/Transformer might work well for financial data collected daily, but not for sub-ms sensor data (where it might be better to use a CNN). In terms of searching, my tip would be to use time series first instead of searching by technique names like LSTMs, since you'll inevitably miss more novel approaches like Neural ODEs. Also have a read through a) papers that reference benchmark datasets like http://www.timeseriesclassification.com/index.php and https://mimic.physionet.org/ (more of a domain-specific example, but one I'm personally familiar with), and b) the prior work section from methods papers like the Neural ODE one.
1
u/MrHyperbowl Mar 24 '21
If your problem is low dimensional (is this what you mean by tabular?), Then graph it and use standard statistics, not deep learning. That's why there are so few resources available. If you have time series data, tough luck that shit is hard to deal with as a general case and you should look to see if someone has done something for exactly your use case.
-2
u/nraw Mar 24 '21
"the most type of data being dealt with" - based on what did you make this statement?
4
u/DataPlug Mar 24 '21
Sorry I didn’t post resources. This is based on the Google Cloud ML summit 2020. https://ibb.co/8dZHt6H
8
u/CoffeeIntrepid Mar 23 '21
Sure it might usually be better to train regression on continuous data but I’ve always wondered about the in between cases like ordinal classification where things have a integer scale like disease severity level 1-10 stages or something similar.
2
u/sobe86 Mar 24 '21
https://en.wikipedia.org/wiki/Ordinal_regression
Company I work for does this for predicting time rounded to the nearest hour. Sometimes it works better than straight regression, sometimes not - if the numbers are mostly small it's a good bet.
1
u/wzx0925 Mar 24 '21
classification where things have a integer scale like
Rounding not work?
1
u/CoffeeIntrepid Mar 24 '21
I meant more like do you run a regression or classification fit for a non continuous but ordinal scale.
20
Mar 23 '21
For the very basics, fast.ai actually gives good advice. The strong baseline tips are so often overlooked it's actually embarrassing for the ML community.
However, take anything of theirs which is not basic common sense with a huge grain of salt. You may lose precious experimental time with their rules-of-thumb which more often than not simply don't work.
2
u/THE_REAL_ODB Mar 24 '21
Transfer Learning Always use transfer learning if you can by finding a model pre-trained for a similar task and then fine-tune that model for your particular task e.g. see huggingface for help with this in NLP Gradual unfreezing and discriminative learning rates work well when fine-tuning a transfer learned model Gradual unfreezing = freeze earlier layers and train the later layers only, then gradually unfreeze the earlier layers one by one Discriminative learning rates = having different learning rates per layer of your network (usually earlier layers have smaller learning rates than later layers)
thnx for the heads up. Would the above advice be a bad one? I'm interested in implementing this, but dont wanna spent too much time on it if it wont work.
6
Mar 24 '21
Those only apply to deep models (i.e. mostly transformer-based). See, that's the problem overall with the more "fancy" advice from fast.ai - they shift the focus from the actual good advice. Remember the strong baseline? Before even trying those, use BoW, LSA/LDA or Word2Vec/GloVe for starters. If you already did, there are a handful of possible outcomes:
You got some pretty good results, which means you should be skeptical of any further gains with more complex models;
You got pretty bad results, which means you either have issues in your code/data (fast.ai advice is to debug with simpler models) or your problem is actually infeasible to be solved with textual features at all (and thus, it is almost certain that more complex models will do nothing for you).
You got lukewarm results - this is the best (and often the only) case for more complex models.
Then, and only then, you should check my 2cents on fine-tuning transformer-based LMs or end2end models:
Start by using BERT/GPT/whatever as a simple feature extractor and re-apply the "strong baseline" steps. Be aware of differences between token-level and sequence-level features, and double-check if what you are extracting is what you really want.
After everything done until here, you may then check pre-trained models on similar tasks. Prioritize more basic transfer learning strategies (either using intermediate layers as features or changing the output layer and fine-tuning it entirely).
Finally, IMHO, gradual unfreezing and discriminative learning rates have a horrible "return-of-invested-time" due to the extensive metaparameter search in DL. What's worse, is that your cognitive biases will start kicking in after so much time invested in optimizing your model, and you may overlook data leakages and faulty protocols, only to convince yourself that you had some "consistent gain".
2
u/pitrucha ML Engineer Mar 24 '21
that's pretty much a to-go-to strategy in the NLP when your data is in one of more popular languages (i.e. Wikipedia in this language is big enough so someone already trained a Transformer on it)
2
u/THE_REAL_ODB Mar 24 '21
My bad. I meant the gradual unfreezing and learning rate part for transfer learning. I know using pretrained models are helpful.
2
u/pitrucha ML Engineer Mar 24 '21
That's one helpful as well. However, it is usually very hard to evaluate the training as it happens. Saving checkpoints and later training it on the real downstream task partially solves it but may take sometime.
14
u/lugiavn Mar 23 '21
Tricks that might be incorrect/bad in the list:
Never use one-hot encodings, use embeddings instead, even in tabular data!
Label smoothing = use 0.1 and 0.9 instead of 0 and 1 for label targets (can smoothen training)
Don’t dichotomise your data, if your output is continuous then its better to train the network to predict continuous values rather than turning it into a classification problem
2
u/analytical_1 Mar 23 '21
Can you explain the label smoothing part?
1
u/lugiavn Mar 23 '21
I guess it's a regularization technique, but like stuffs such as dropout, you don't know if it does help (e.g. increase your accuracy or AUC or whatever) or not until you try it (well good chance that it doesn't)
You can use it to smoothen the output for sure but that is usually not too important
1
u/thunder_jaxx ML Engineer Mar 23 '21
Don’t dichotomise your data, if your output is continuous then its better to train the network to predict continuous values rather than turning it into a classification problem
This one is arguable as it depends on the problem being optimized for. Sometimes dichotomizing can actually help.
1
u/maxToTheJ Mar 24 '21
e.g. if adding a feature improves the performance of linear regression then it should probably also improve the performance of your neural net unless you have a bug!
Also this one isn't necessarily true if the new improved feature is just some simple transformation your NN will pick up anyways. Feature can just be a transformation of a signal you already have in your NN. To be more accurate the new "feature" should be some completely new "signal" source
5
u/Mefaso Mar 23 '21
if you make your neural network 1 layer then it should be able to match the performance of a linear regression baseline, if it doesn’t then you have a bug!
Or convergence issues
1
u/eschibli Mar 24 '21
I.e. make the network output: min_value + sigmoid(output) * (max_value - min_value)
This seems questionable given the very large gradient near intermediate values of output
2
u/__data_science__ Mar 24 '21
Yeah so they also suggest making the range slightly wider than what you need to deal with that problem. I should have mentioned that
1
u/physnchips ML Engineer Mar 24 '21
I’m surprised a linear activation with a min and max clamp isn’t what fastai would suggest.
1
u/__data_science__ Mar 24 '21
A clamp would make it non-differentiable?
1
u/physnchips ML Engineer Mar 24 '21
No more than relu already is
1
u/__data_science__ Mar 26 '21
i think its ok with relu earlier in the network but not when its the activitation directly before going into the loss function as you need the loss function to be much more sensitive to changes. would have to try it out to see though
3
2
2
u/gabegabe6 Mar 24 '21
RemindMe! Tomorrow
1
u/RemindMeBot Mar 24 '21
I will be messaging you in 1 day on 2021-03-25 05:33:25 UTC to remind you of this link
CLICK THIS LINK to send a PM to also be reminded and to reduce spam.
Parent commenter can delete this message to hide from others.
Info Custom Your Reminders Feedback
1
u/Sahil_1776 Mar 22 '22
Can anyone please explain how to implement Adam optimizer in fastai? It is just not working. I am training a resnet with multi-label classification. I am using learn = cnn_learner(...) . Please share some code if you can help, I would highly appreciate that.
0
u/Deeppop Mar 24 '21
Here's an ankiweb version of the deck, suitable for use in the anki open source apps:
https://ankiweb.net/shared/info/1195573595
Thanks to __data_science__!
0
12
2
66
u/[deleted] Mar 23 '21
Can you explain this one Never use one-hot encodings, use embeddings instead, even in tabular data!