Lesson3 Imdb
IMDB
Preparing the data
First let's download the dataset we are going to study. The dataset has been curated by Andrew Maas et al. and contains a total of 100,000 reviews on IMDB. 25,000 of them are labelled as positive and negative for training, another 25,000 are labelled for testing (in both cases they are highly polarized). The remaning 50,000 is an additional unlabelled data (but we will find a use for it nonetheless).
We'll begin with a sample we've prepared for you, so that things run quickly before going over the full dataset.
(#8) [Path('/home/sgugger/.fastai/data/imdb_sample/texts.csv'),Path('/home/sgugger/.fastai/data/imdb_sample/export_lm.pkl'),Path('/home/sgugger/.fastai/data/imdb_sample/models'),Path('/home/sgugger/.fastai/data/imdb_sample/data_save.pkl'),Path('/home/sgugger/.fastai/data/imdb_sample/export.pkl'),Path('/home/sgugger/.fastai/data/imdb_sample/export_clas.pkl'),Path('/home/sgugger/.fastai/data/imdb_sample/data_clas_export.pkl'),Path('/home/sgugger/.fastai/data/imdb_sample/data_lm_export.pkl')] It only contains one csv file, let's have a look at it.
'This is a extremely well-made film. The acting, script and camera-work are all first-rate. The music is good, too, though it is mostly early in the film, when things are still relatively cheery. There are no really superstars in the cast, though several faces will be familiar. The entire cast does an excellent job with the script.<br /><br />But it is hard to watch, because there is no good end to a situation like the one presented. It is now fashionable to blame the British for setting Hindus and Muslims against each other, and then cruelly separating them into two countries. There is some merit in this view, but it\'s also true that no one forced Hindus and Muslims in the region to mistreat each other as they did around the time of partition. It seems more likely that the British simply saw the tensions between the religions and were clever enough to exploit them to their own ends.<br /><br />The result is that there is much cruelty and inhumanity in the situation and this is very unpleasant to remember and to see on the screen. But it is never painted as a black-and-white case. There is baseness and nobility on both sides, and also the hope for change in the younger generation.<br /><br />There is redemption of a sort, in the end, when Puro has to make a hard choice between a man who has ruined her life, but also truly loved her, and her family which has disowned her, then later come looking for her. But by that point, she has no option that is without great pain for her.<br /><br />This film carries the message that both Muslims and Hindus have their grave faults, and also that both can be dignified and caring people. The reality of partition makes that realisation all the more wrenching, since there can never be real reconciliation across the India/Pakistan border. In that sense, it is similar to "Mr & Mrs Iyer".<br /><br />In the end, we were glad to have seen the film, even though the resolution was heartbreaking. If the UK and US could deal with their own histories of racism with this kind of frankness, they would certainly be better off.'
It contains one line per review, with the label ('negative' or 'positive'), the text and a flag to determine if it should be part of the validation set or the training set.
First, we need to tokenize the texts in our dataframe, which means separate the sentences in individual tokens (often words).
Tokenization
The first step of processing we make the texts go through is to split the raw sentences into words, or more exactly tokens. The easiest way to do this would be to split the string on spaces, but we can be smarter:
- we need to take care of punctuation
- some words are contractions of two different words, like isn't or don't
- we may need to clean some parts of our texts, if there's HTML code for instance
The texts are truncated at 100 tokens for more readability. We can see that it did more than just split on space and punctuation symbols:
- the "'s" are grouped together in one token
- the contractions are separated like this: "did", "n't"
- content has been cleaned for any HTML symbol and lower cased
- there are several special tokens (all those that begin by xx), to replace unknown tokens (see below) or to introduce different text fields (here we only have one).
Numericalization
Once we have extracted tokens from our texts, we convert to integers by creating a list of all the words used. We only keep the ones that appear at least twice with a maximum vocabulary size of 60,000 (by default) and replace the ones that don't make the cut by the unknown token UNK.
This is done automatically behind the scenes if we use a facotry method of TextDataLoaders.
And if we look at what a what's in our datasets, we'll see the numericalized text as a representation:
(tensor([ 2, 8, 21, 29, 2190, 47, 138, 44, 14, 9, 111, 908, , 126, 33, 178, 136, 11, 8, 237, 21, 269, 51, 9, 196, , 20, 33, 206, 37, 114, 1488, 57, 0, 14, 21, 792, 11, , 8, 17, 222, 201, 27, 13, 219, 14, 4512, 282, 71, 15, , 3306, 812, 57, 39, 33, 38, 1065, 15, 1173, 60, 14, 9, , 29, 12, 248, 71, 9, 377, 33, 58, 1578, 11, 8, 59, , 33, 61, 37, 197, 15, 252, 0, 33, 227, 793, 155, 21, , 587, 32, 12, 2042, 13, 175, 288, 14, 1655, 28, 9, 177, , 691, 10, 45, 178, 46, 136, 139, 482, 10, 31, 112, 33, , 1023, 45, 174, 211, 1578, 186, 13, 224, 14, 377, 15, 61, , 21, 12, 33, 227, 1355, 1655, 28, 118, 58, 50, 33, 178, , 378, 257, 28, 9, 32, 11, 19, 206, 37, 158, 35, 208, , 56, 21, 587, 29, 10, 110, 222, 156, 20, 8, 1774, 8, , 2043, 74, 42, 116, 12, 18, 20, 376, 17, 1356, 74, 42, , 107, 41, 1174, 11, 26, 8, 15, 345, 33, 38, 746, 15, , 793, 155, 49, 813, 493, 9, 1175, 14, 86, 33, 178, 123, , 136, 120, 535, 10, 21, 173, 66, 211, 15, 43, 483, 253, , 255, 11, 8, 35, 349, 14, 20, 17, 16, 3824, 10, 27, , 15, 1579, 20, 33, 9, 588, 83, 39, 301, 11, 8, 112, , 91, 1024, 8, 508, 11, 8, 0, 12, 9, 0, 14, 389, , 449, 235, 0, 10, 17, 16, 27, 59, 40, 16, 5470, 2929, , 15, 100, 449, 35, 15, 9, 29, 2930, 5471, 501, 11, 8, , 624, 91, 1024, 8, 1489, 8, 0, 10, 53, 19, 3825, 423, , 34, 12, 40, 95, 41, 147, 39, 15, 5472, 18, 21, 31, , 1416, 40, 95, 11, 8, 112, 269, 9, 2191, 2044, 10, 8, , 3826, 8, 5473, 509, 49, 1176, 260, 10, 432, 385, 213, 55, , 8, 3826, 8, 5473, 16, 39, 13, 70, 1289, 710, 12, 856, , 73, 0, 235, 570, 18, 126, 10, 18, 82, 589, 165, 73, , 149, 909, 15, 126, 14, 9, 8, 294, 3827, 674, 11, 26, , 8, 46, 18, 46, 33, 58, 223, 197, 15, 88, 21, 28, , 613, 72, 17, 269, 60, 35, 348, 10, 19, 144, 20, 19, , 211, 13, 2405, 60, 14, 17, 10, 19, 473, 1656, 46, 43, , 1290, 142, 10, 515, 110, 5474, 15, 0, 18, 9, 4513, 14, , 350, 11]),)
The correspondence is stored in the vocab attribute of our DataLoaders
['xxunk', , 'xxpad', , 'xxbos', , 'xxeos', , 'xxfld', , 'xxrep', , 'xxwrep', , 'xxup', , 'xxmaj', , 'the', , ',', , '.', , 'and', , 'a', , 'of', , 'to', , 'is', , 'it', , 'in', , 'i']
With the data block API
We can use the data block API with NLP and have a lot more flexibility than what the default factory methods offer. In the previous example for instance, the data was randomly split between train and validation instead of reading the third column of the csv.
With the data block API though, we have to manually call the tokenize and numericalize steps. This allows more flexibility, and if you're not using the defaults from fastai, the various arguments to pass will appear in the step they're revelant, so it'll be more readable.
Language model
Note that language models can use a lot of GPU, so you may need to decrease batchsize here.
Now let's grab the full dataset for what follows.
(#7) [Path('/home/sgugger/.fastai/data/imdb/unsup'),Path('/home/sgugger/.fastai/data/imdb/imdb.vocab'),Path('/home/sgugger/.fastai/data/imdb/tmp_lm'),Path('/home/sgugger/.fastai/data/imdb/train'),Path('/home/sgugger/.fastai/data/imdb/test'),Path('/home/sgugger/.fastai/data/imdb/README'),Path('/home/sgugger/.fastai/data/imdb/tmp_clas')] (#4) [Path('/home/sgugger/.fastai/data/imdb/train/pos'),Path('/home/sgugger/.fastai/data/imdb/train/unsupBow.feat'),Path('/home/sgugger/.fastai/data/imdb/train/labeledBow.feat'),Path('/home/sgugger/.fastai/data/imdb/train/neg')] The reviews are in a training and test set following an imagenet structure. The only difference is that there is an unsup folder on top of train and test that contains the unlabelled data.
We're not going to train a model that classifies the reviews from scratch. Like in computer vision, we'll use a model pretrained on a bigger dataset (a cleaned subset of wikipedia called wikitext-103). That model has been trained to guess what the next word is, its input being all the previous words. It has a recurrent structure and a hidden state that is updated each time it sees a new word. This hidden state thus contains information about the sentence up to that point.
We are going to use that 'knowledge' of the English language to build our classifier, but first, like for computer vision, we need to fine-tune the pretrained model to our particular dataset. Because the English of the reviews left by people on IMDB isn't the same as the English of wikipedia, we'll need to adjust the parameters of our model by a little bit. Plus there might be some words that would be extremely common in the reviews dataset but would be barely present in wikipedia, and therefore might not be part of the vocabulary the model was trained on.
This is where the unlabelled data is going to be useful to us, as we can use it to fine-tune our model. Let's create our data object with the data block API (next line takes a few minutes the first minute you run it).
We have to use a special kind of TextDataLoaders for the language model, that ignores the labels (that's why we put 0 everywhere), will shuffle the texts at each epoch before concatenating them all together (only for training, we don't shuffle for the validation set) and will send batches that read that text in order with targets that are the next word in the sentence.
The line before being a bit long, we want to load quickly the final ids by using the following cell.
We can then put this in a learner object very easily with a model loaded with the pretrained weights. They'll be downloaded the first time you'll execute the following line and stored in ~/.fastai/models/ (or elsewhere if you specified different paths in your config file).
60008
LR Finder is complete, type {learner_name}.recorder.plot() to see the graph.
To complete the fine-tuning, we can then unfeeze and launch a new training.
How good is our model? Well let's try to see what it predicts after a few given words.
I liked this movie because of the cool scenery and the high level of xxmaj british hunting . xxmaj the only thing this movie has going for it is the horrible acting and no script . xxmaj the movie was a big disappointment . xxmaj I liked this movie because it was one of the few movies that made me laugh so hard i did n't like it . xxmaj it was a hilarious film and it was very entertaining . xxmaj the acting was great , i 'm
We have to save not only the model, but also its encoder, the part that's responsible for creating and updating the hidden state. For the next part, we don't care about the part that tries to guess the next word.
Classifier
Now, we'll create a new data object that only grabs the labelled data and keeps those labels. Again, this line takes a bit of time.
We can then create a model to classify those reviews and load the encoder we saved before.
<fastai.text.learner.RNNLearner at 0x7f033cb75f10>
('pos', tensor(1), tensor([1.4426e-04, 9.9986e-01]))