Lesson 4: Practical Deep Learning for Coders 2022

Lesson 4: Practical Deep Learning for Coders 2022

Introduction

In this lesson, we will cover natural language processing (NLP) using Transformers and Hugging Face library. We will fine-tune a pre-trained NLP model to learn how to use the library.

Using Different Libraries for NLP

  • The course will cover NLP using Transformers instead of fast.ai library.
  • Hugging Face Transformers is the state-of-the-art in NLP and worth knowing.
  • Using different libraries helps understand concepts applied in different ways.

Fine-Tuning Pre-Trained Model

  • Fine-tuning is the process of taking pre-trained parameters that have already been fitted and tuning them further.
  • Pre-trained models have some parameters that are already confident while others are not. Fine-tuning involves focusing on those with no idea what they should be at all and trying to get them right.

Benefits of Lower-Level Libraries

  • Lower-level libraries like Hugging Face Transformers require more work but help go deeper into understanding concepts.
  • The rest of the course will get deeper, so it's good to start learning now.

Understanding Pre-Trained Models

This section explains pre-trained models and how they can be used for fine-tuning.

Example with Sliders

  • Imagine having sliders where some values are known while others are not. Tuning these sliders would be easier since you know which ones need more attention than others.

Pre-Trained Models for Fine-Tuning

  • A pre-trained model has parameters that have already been fitted, where some are confident while others aren't. Fine-tuning involves focusing on those with no idea what they should be at all and trying to get them right.

ULMFiT: Universal Language Model Fine-tuning

In this section, Jeremy Howard discusses the basic process of ULMFiT and how it was used to build a language model.

Building a Language Model

  • The first step in building a language model is to use nearly all of Wikipedia to predict the next word of a Wikipedia article.
  • This is difficult because some articles contain information about math or history that requires understanding beyond just language structure.
  • To be good at predicting the next word, the neural network has to understand how language works and what it's talking about.
  • The pre-trained model could predict more than 30% of the time correctly what the next word of a Wikipedia article would be.

Creating a Sentiment Analysis Model

  • A second language model was created using IMDb movie reviews to determine whether they were positive or negative sentiment.
  • The pre-trained model was trained on IMDb movie reviews and then fine-tuned for predicting sentiment analysis.
  • This approach did not require any labels, only text from Wikipedia and movie reviews themselves.

Transformers Masked Language Model Approach

  • Transformers were developed as an alternative architecture for NLP that can take advantage of modern accelerators like Google's TPUs.
  • They replaced ULMFiT's RNN approach with a Transformer model and its language model approach with what's called a masked language model.
  • Instead of predicting the next word, chunks of text are deleted at random and the model predicts which words were deleted.

Q&A

  • Jeremy answers a question about how to go from a model trained to predict the next word to a model that can be used for classification.

Overview of Neural Networks

In this section, the speaker provides an overview of neural networks and how they work.

Layers in a Neural Network

  • A neural network consists of multiple layers.
  • Layer One detects edges and color gradients.
  • Layer Two combines the outputs from Layer One to detect corners and circles.
  • By Layer Five, the network can detect more complex objects like bird and lizard eyeballs, dog faces, and flowers.

Fine-tuning a Neural Network

In this section, the speaker explains how to fine-tune a pre-trained neural network for a specific task.

Fine-tuning Process

  • The last layer of the pre-trained network is removed.
  • A new random matrix is added to the end of the remaining layers.
  • This new matrix is trained to predict the desired output category.
  • Gradual training is applied to all layers.

Introduction to NLP Classification

In this section, the speaker introduces natural language processing (NLP) classification.

Classifying Documents with NLP

  • NLP classification involves identifying what category a document belongs to based on its text content.
  • A document can be any length or size containing text input.

Introduction to Classification

In this section, the speaker introduces classification as a rich area in NLP and suggests it as a good starting point for those interested in trying out NLP in real life. The speaker then explains how the Kaggle competition is related to classification.

Classification and Kaggle Competition

  • Classification is a rich area in NLP that involves putting things into categories based on whether they are similar or different.
  • The Kaggle competition involves determining which anchor and target pairs are talking about the same thing by guessing their score. It can be turned into something like a classification problem by choosing a category of meaning similarity: “Different” “Similar” or “Identical”.
  • To turn this similarity problem into something that looks like a classification problem, we can concatenate three pieces together (anchor, target, context), call that a document, and then try to train a model that can predict these categories.

Using Kaggle for the Competition

In this section, the speaker talks about using Kaggle for the competition and provides some tips on how to use it effectively.

Tips for Using Kaggle

  • To use Kaggle effectively, click on the accelerator button and choose GPU to make sure you're using a GPU.
  • If you're not on Kaggle and don't have the data yet, download it. If you're on Kaggle, the data will already be there for you.
  • While Kaggle has many Python packages installed, it may not have all of them. For example, at the time of writing this transcript, Hugging Faces datasets package was not available on Kaggle.

Understanding the Kaggle Competition Data

In this section, the speaker explains the data used in the Kaggle competition and how it can be turned into a classification problem.

The Kaggle Competition Data

  • The data used in the Kaggle competition contains an anchor, target, context, and score. The goal is to determine which anchor and target pairs are talking about the same thing by guessing their score.
  • The “anchor” and “target” are from patents and refer to things that need to be filled in on a patent.
  • The score ranges from 0 to 1 and determines whether two anchors or targets are talking about the same thing.
  • Whether two anchors or targets count as similar or not depends on what category they were filed under.

Turning Similarity Problem into Classification Problem

  • To turn this similarity problem into something that looks like a classification problem, we can concatenate three pieces together (anchor, target, context), call that a document, and then try to train a model that can predict these categories.
  • Deep learning often involves taking problems that look novel and different and turning them into problems that look familiar.

Introduction to the Competition and Libraries

In this section, Jeremy Howard introduces the competition and libraries used in the course.

Libraries for Data Science

  • The four key libraries for data science in Python are numpy, matplotlib, pandas, and pytorch.
  • The book "Python for Data Analysis" by Wes McKinney covers these libraries comprehensively.

Introduction to the Competition

  • The first step when looking at a competition is to understand what data is available. This includes looking at the CSV files provided as well as reading any information provided on the competition website.
  • CSV files can be read using pandas which creates a DataFrame that represents a table of data.
  • Describing a DataFrame using the describe method with include='object' provides useful information about non-numeric fields such as unique values and repetition.

Understanding the Dataset

In this section, Jeremy Howard discusses how to understand and work with the dataset.

Key Features of Dataset

  • Each document in this dataset is very short with only three or four words per document. There is a lot of repetition in this dataset which means there isn't much unique data available.
  • Creating a single string that contains some kind of field separator plus context, target, and anchor can help us work with this dataset more easily.

Working with Pandas DataFrame

  • When working with pandas DataFrame we can use square brackets or dot notation to refer to columns but it's important to note that there are two ways of referring to a column in pandas.
  • We can use the value_counts method to count the number of occurrences of each unique value in a column.

Introduction to NLP and Tokenization

In this section, the speaker introduces the concept of natural language processing (NLP) and explains how neural networks work with numbers. The speaker also discusses the two steps involved in NLP: tokenization and numericalization.

Neural Networks and Numbers

  • Neural networks work with numbers.
  • Matrices are multiplied by numbers, negatives are replaced with zeros, and everything is added up.
  • This process is repeated a few times to create a neural network.

Tokenization

  • The first step in NLP is tokenization.
  • Tokenization involves splitting text into tokens or words.
  • Some languages like Chinese do not have space-separated words, so tokenizing can be challenging.
  • Instead of using words, people tend to tokenize into subwords which are pieces of words.

Hugging Face Transformers

  • Hugging Face transformers is a library that has hundreds of pre-trained models for NLP tasks.
  • Each model can be trained on different corpuses for solving different problems.
  • Deberta-v3 is one of the generally good models that works for many tasks.

Introduction to Tokenization and Numericalization

In this section, Jeremy explains the process of tokenization and numericalization in NLP. He introduces the AutoTokenizer dictionary and how it is used to tokenize a string into words. He also explains how these tokens are turned into numbers using numericalization.

Tokenization

  • The deberta-v3 model is a good starting point for NLP tasks.
  • AutoTokenizer is a dictionary that maps models to their respective tokenizers.
  • Passing a string through the tokenizer splits it into tokens, including punctuation marks and underscores.
  • Tokens represent unique words in the vocabulary created during training.

Numericalization

  • Numericalization converts tokens into numbers by looking them up in the vocabulary.
  • Dataset.map() can be used to parallelize tokenization across multiple documents.
  • The resulting dataset contains both the original input and its corresponding numericalized version.

Tokenization and Handling Long Documents

In this section, the speaker discusses how to choose keywords and the order of fields for tokenization. They also explain that it is arbitrary and flexible as long as the information is present. The speaker then talks about handling long documents in ULMFiT.

Choosing Keywords and Order of Fields

  • The choice of keywords and order of fields for tokenization is arbitrary.
  • It's important to have headers before each field so that the model can learn from them.
  • Neural nets are flexible, so it doesn't matter how you give them information as long as it's there.

Handling Long Documents in ULMFiT

  • Long documents do not require special consideration in ULMFiT.
  • Transformers have to process the whole document at once, while ULMFiT can split it into multiple pieces and read it gradually.
  • If working with documents over 2,000 words, ULMFiT may be a better approach than transformers.

Test Sets and Overfitting

In this section, the speaker explains the importance of having separate training, validation, and test data sets. They use an example function called plot_poly to demonstrate overfitting.

Importance of Separate Data Sets

  • A test set is used to identify and control for overfitting.
  • Having separate training, validation, and test data sets is perhaps the most important idea in machine learning.

Example: Plot_Poly Function

  • The plot_poly function allows us to pass in the degree of a polynomial.
  • The function is used to demonstrate overfitting by fitting a line to data that doesn't fit well.
  • Overfitting occurs when a model fits too closely to the training data and does not generalize well to new data.

Polynomial Regression

In this section, the speaker discusses polynomial regression and the issues of underfitting and overfitting.

Underfitting and Overfitting

  • An underfit model is one that lacks complexity to match the data. It is systematically biased.
  • A common misunderstanding is that simpler models are more reliable, but models that are too simple will be systematically incorrect.
  • An overfit model fits too closely to the training data and does not generalize well to new data. It predicts values that are way above or below what we would expect in real life.
  • To determine whether a model is underfit or overfit, we can remove some of our original dataset (validation set), fit our model using only those points we haven't removed, then measure how good it is by looking at only the points we removed.

Validation Set

  • The validation set is the data that we take away from our training set and don't let the model see when it's training.
  • Creating a good validation set is not generally as simple as just randomly pulling some of your data out of your model. Instead, you should truncate and remove the last couple of weeks if you're working with time series data like dates and sales. This will test whether you can use this to predict future rather than past events.

Understanding Validation and Test Sets

In this section, the speaker explains the importance of validation and test sets in machine learning models. He also discusses how to avoid overfitting and why it is important to use a test set.

Importance of Validation Set

  • Beginners on Kaggle often overfit their models.
  • It's important to get a visceral feeling of overfitting by participating in real competitions on Kaggle.
  • In real-world scenarios, you may not even know that you have overfitted your model, which can silently destroy value for your organization.
  • To avoid overfitting, it's essential to find a good validation set and interpret it correctly.

Examples of Overfitting

  • The distracted driver competition on Kaggle had people in the test set who didn't exist in the competition data used for training the model.
  • The Kaggle fisheries competition had boats that didn't appear in the pictures. Some participants accidentally figured out what fish were present by looking at the boat instead of focusing on the fish.
  • Cross-validation is not about building a good validation set.

Understanding Test Set

  • A test set is another validation set that you don't use for tracking accuracy while building your model.
  • On Kaggle, there are two test sets: one that gives feedback during the competition and another that you don't see until after it ends.
  • If you try too many models during your model-building process, you may accidentally find one that works well by coincidence. This is why having a held-out test set is crucial.

What if Your Model Fails?

  • If your model fails after spending months working on it, starting again from scratch might be necessary.
  • It's better to know than not know whether your model works or not.

Timestamps are provided at various points throughout this section.

Turn any video into a summary like this

YouTube links, meetings, lectures. With transcripts, search, and chat.

Video description

00:00:00 - Using Huggingface 00:03:24 - Finetuning pretrained model 00:05:14 - ULMFit 00:09:15 - Transformer 00:10:52 - Zeiler & Fergus 00:14:47 - US Patent Phrase to Phase Matching Kaggle competition 00:16:10 - NLP Classification 00:20:56 - Kaggle configs, insert python in bash, read competition website 00:24:51 - Pandas, numpy, matplotlib, & pytorch 00:29:26 - Tokenization 00:33:20 - Huggingface model hub 00:36:40 - Examples of tokenized sentences 00:38:47 - Numericalization 00:41:13 - Question: rationale behind how input data was formatted 00:43:20 - ULMFit fits large documents easily 00:45:55 - Overfitting & underfitting 00:50:45 - Splitting the dataset 00:52:31 - Creating a good validation set 00:57:13 - Test set 00:59:00 - Metric vs loss 01:01:27 - The problem with metrics 01:04:10 - Pearson correlation 01:10:27 - Correlation is sensitive to outliers 01:14:00 - Training a model 01:19:20 - Question: when is it ok to remove outliers? 01:22:10 - Predictions 01:25:30 - Opportunities for research and startups 01:26:16 - Misusing NLP 01:33:00 - Question: isn’t the target categorical in this case? Transcript thanks to wyquek, jmp, bencoman, fmussari, mike.moloch, amr.malik, kurianbenoy, gagan, and Raymond Wu on forums.fast.ai. Timestamps thanks to RogerS49 and Wyquek on forums.fast.ai.