text

Application to NLP, including ULMFiT fine-tuning

Text models, data, and training

The text module of the fastai library contains all the necessary functions to define a Dataset suitable for the various NLP (Natural Language Processing) tasks and quickly generate models you can use for them. Specifically:

  • text.transform contains all the scripts to preprocess your data, from raw text to token ids,
  • text.data contains the definition of TextDataBunch, which is the main class you’ll need in NLP,
  • text.learner contains helper functions to quickly create a language model or an RNN classifier.

Have a look at the links above for full details of the API of each module, or read on for a quick overview.

Quick Start: Training an IMDb sentiment model with ULMFiT

Let’s start with a quick end-to-end example of training a model. We’ll train a sentiment classifier on a sample of the popular IMDb data, showing 4 steps:

  1. Reading and viewing the IMDb data
  2. Getting your data ready for modeling
  3. Fine-tuning a language model
  4. Building a classifier

Reading and viewing the IMDb data

First let’s import everything we need for text.

  1. from fastai.text import *

Contrary to images in Computer Vision, text can’t directly be transformed into numbers to be fed into a model. The first thing we need to do is to preprocess our data so that we change the raw texts to lists of words, or tokens (a step that is called tokenization) then transform these tokens into numbers (a step that is called numericalization). These numbers are then passed to embedding layers that will convert them in arrays of floats before passing them through a model.

You can find on the web plenty of Word Embeddings to directly convert your tokens into floats. Those word embeddings have generally be trained on a large corpus such as wikipedia. Following the work of ULMFiT, the fastai library is more focused on using pre-trained Language Models and fine-tuning them. Word embeddings are just vectors of 300 or 400 floats that represent different words, but a pretrained language model not only has those, but has also been trained to get a representation of full sentences and documents.

That’s why the library is structured around three steps:

  1. Get your data preprocessed and ready to use in a minimum amount of code,
  2. Create a language model with pretrained weights that you can fine-tune to your dataset,
  3. Create other models such as classifiers on top of the encoder of the language model.

To show examples, we have provided a small sample of the IMDB dataset which contains 1,000 reviews of movies with labels (positive or negative).

  1. path = untar_data(URLs.IMDB_SAMPLE)
  2. path
  1. PosixPath('/home/ubuntu/.fastai/data/imdb_sample')

Creating a dataset from your raw texts is very simple if you have it in one of those ways

  • organized in folders in an ImageNet style
  • organized in a csv file with labels columns and a text column

Here, the sample from imdb is in a texts csv file that looks like this:

  1. df = pd.read_csv(path/'texts.csv')
  2. df.head()
labeltextis_valid
0negativeUn-bleeping-believable! Meg Ryan doesn’t even …False
1positiveThis is a extremely well-made film. The acting…False
2negativeEvery once in a long while a movie will come a…False
3positiveName just says it all. I watched this movie wi…False
4negativeThis movie succeeds at being one of the most u…False

Getting your data ready for modeling

To get a DataBunch quickly, there are also several factory methods depending on how our data is structured. They are all detailed in text.data, here we’ll use the method from_csv of the TextLMDataBunch (to get the data ready for a language model) and TextClasDataBunch (to get the data ready for a text classifier) classes.

  1. # Language model data
  2. data_lm = TextLMDataBunch.from_csv(path, 'texts.csv')
  3. # Classifier model data
  4. data_clas = TextClasDataBunch.from_csv(path, 'texts.csv', vocab=data_lm.train_ds.vocab, bs=32)

This does all the necessary preprocessing behind the scene. For the classifier, we also pass the vocabulary (mapping from ids to words) that we want to use: this is to ensure that data_clas will use the same dictionary as data_lm.

Since this step can be a bit time-consuming, it’s best to save the result with:

  1. data_lm.save('data_lm_export.pkl')
  2. data_clas.save('data_clas_export.pkl')

This will create a ‘tmp’ directory where all the computed stuff will be stored. You can then reload those results with:

  1. data_lm = load_data(path, 'data_lm_export.pkl')
  2. data_clas = load_data(path, 'data_clas_export.pkl', bs=16)

Note that you can load the data with different DataBunch parameters (batch size, bptt,…)

Fine-tuning a language model

We can use the data_lm object we created earlier to fine-tune a pretrained language model. fast.ai has an English model with an AWD-LSTM architecture available that we can download. We can create a learner object that will directly create a model, download the pretrained weights and be ready for fine-tuning.

  1. learn = language_model_learner(data_lm, AWD_LSTM, drop_mult=0.5)
  2. learn.fit_one_cycle(1, 1e-2)
epochtrain_lossvalid_lossaccuracytime
04.3191743.8823610.28815500:13

Like a computer vision model, we can then unfreeze the model and fine-tune it.

  1. learn.unfreeze()
  2. learn.fit_one_cycle(1, 1e-3)
epochtrain_lossvalid_lossaccuracytime
03.9356073.8110580.29726200:16

To evaluate your language model, you can run the Learner.predict method and specify the number of words you want it to guess.

  1. learn.predict("This is a review about", n_words=10)
  1. 'This is a review about what was worth a word of reading , where some'

It doesn’t make much sense (we have a tiny vocabulary here and didn’t train much on it) but note that it respects basic grammar (which comes from the pretrained model).

Finally we save the encoder to be able to use it for classification in the next section.

  1. learn.save_encoder('ft_enc')

Building a classifier

We now use the data_clas object we created earlier to build a classifier with our fine-tuned encoder. The learner object can be done in a single line.

  1. learn = text_classifier_learner(data_clas, AWD_LSTM, drop_mult=0.5)
  2. learn.load_encoder('ft_enc')
  1. data_clas.show_batch()
texttarget
xxbos xxmaj raising xxmaj victor xxmaj vargas : a xxmaj review n n xxmaj you know , xxmaj raising xxmaj victor xxmaj vargas is like sticking your hands into a big , steaming bowl of xxunk . xxmaj it ‘s warm and gooey , but you ‘re not sure if it feels right . xxmaj try as i might , no matter how warm and gooey xxmaj raising xxmajnegative
xxbos xxup the xxup shop xxup around xxup the xxup corner is one of the xxunk and most feel - good romantic comedies ever made . xxmaj there ‘s just no getting around that , and it ‘s hard to actually put one ‘s feeling for this film into words . xxmaj it ‘s not one of those films that tries too hard , nor does it come up withpositive
xxbos xxmaj now that xxmaj che(2008 ) has finished its relatively short xxmaj australian cinema run ( extremely limited xxunk screen in xxmaj sydney , after xxunk ) , i can xxunk join both xxunk of “ xxmaj at xxmaj the xxmaj movies “ in taking xxmaj steven xxmaj soderbergh to task . n n xxmaj it ‘s usually satisfying to watch a film director change his style /negative
xxbos xxmaj this film sat on my xxmaj tivo for weeks before i watched it . i dreaded a self - indulgent xxunk flick about relationships gone bad . i was wrong ; this was an xxunk xxunk into the screwed - up xxunk of xxmaj new xxmaj yorkers . n n xxmaj the format is the same as xxmaj max xxmaj xxunk ‘ “ xxmaj la xxmaj rondepositive
xxbos i really wanted to love this show . i truly , honestly did . n n xxmaj for the first time , gay viewers get their own version of the “ xxmaj the xxmaj bachelor “ . xxmaj with the help of his obligatory “ hag “ xxmaj xxunk , xxmaj james , a good looking , well - to - do thirty - something has the chancenegative
  1. learn.fit_one_cycle(1, 1e-2)
epochtrain_lossvalid_lossaccuracytime
00.6033500.5315860.74129400:23

Again, we can unfreeze the model and fine-tune it.

  1. learn.freeze_to(-2)
  2. learn.fit_one_cycle(1, slice(5e-3/2., 5e-3))
epochtrain_lossvalid_lossaccuracytime
00.5038330.4440840.80099500:29
  1. learn.unfreeze()
  2. learn.fit_one_cycle(1, slice(2e-3/100, 2e-3))
epochtrain_lossvalid_lossaccuracytime
00.4104220.3632260.85074600:42

Again, we can predict on a raw text by using the Learner.predict method.

  1. learn.predict("This was a great movie!")
  1. (Category positive, tensor(1), tensor([0.0049, 0.9951]))

Company logo

©2021 fast.ai. All rights reserved.
Site last generated: Jan 5, 2021