{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Text models, data, and training" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hide_input": true }, "outputs": [], "source": [ "from fastai.gen_doc.nbdoc import *" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The [`text`](/text.html#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:\n", "- [`text.transform`](/text.transform.html#text.transform) contains all the scripts to preprocess your data, from raw text to token ids,\n", "- [`text.data`](/text.data.html#text.data) contains the definition of [`TextDataset`](/text.data.html#TextDataset), which the main class you'll need in NLP,\n", "- [`text.learner`](/text.learner.html#text.learner) contains helper functions to quickly create a language model or an RNN classifier.\n", "\n", "Have a look at the links above for full details of the API of each module, of read on for a quick overview." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Quick Start: Training an IMDb sentiment model with *ULMFiT*" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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:\n", "\n", "1. Reading and viewing the IMDb data\n", "1. Getting your data ready for modeling\n", "1. Fine-tuning a language model\n", "1. Building a classifier" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Reading and viewing the IMDb data" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "First let's import everything we need for text." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from fastai import *\n", "from fastai.text import * " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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 wil convert them in arrays of floats before passing them through a model.\n", "\n", "You can find on the web plenty of [Word Embeddings](https://en.wikipedia.org/wiki/Word_embedding) 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](https://arxiv.org/abs/1801.06146), 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.\n", "\n", "That's why the library is structured around three steps:\n", "\n", "1. Get your data preprocessed and ready to use in a minimum amount of code,\n", "1. Create a language model with pretrained weights that you can fine-tune to your dataset,\n", "1. Create other models such as classifiers on top of the encoder of the language model.\n", "\n", "To show examples, we have provided a small sample of the [IMDB dataset](https://www.imdb.com/interfaces/) which contains 1,000 reviews of movies with labels (positive or negative)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "PosixPath('/home/ubuntu/.fastai/data/imdb_sample')" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "path = untar_data(URLs.IMDB_SAMPLE)\n", "path" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Creating a dataset from your raw texts is very simple if you have it in one of those ways\n", "- organized it in folders in an ImageNet style\n", "- organized in a csv file with labels columns and a text columns\n", "\n", "Here, the sample from imdb is in a texts csv files that looks like this:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
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
\n", "
" ], "text/plain": [ " label text is_valid\n", "0 negative Un-bleeping-believable! Meg Ryan doesn't even ... False\n", "1 positive This is a extremely well-made film. The acting... False\n", "2 negative Every once in a long while a movie will come a... False\n", "3 positive Name just says it all. I watched this movie wi... False\n", "4 negative This movie succeeds at being one of the most u... False" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df = pd.read_csv(path/'texts.csv')\n", "df.head()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Getting your data ready for modeling" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hide_input": true }, "outputs": [], "source": [ "for file in ['train_tok.npy', 'valid_tok.npy']:\n", " if os.path.exists(path/'tmp'/file): os.remove(path/'tmp'/file)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To get a [`DataBunch`](/basic_data.html#DataBunch) quickly, there are also several factory methods depending on how our data is structured. They are all detailed in [`text.data`](/text.data.html#text.data), here we'll use the method from_csv of the [`TextLMDataBunch`](/text.data.html#TextLMDataBunch) (to get the data ready for a language model) and [`TextClasDataBunch`](/text.data.html#TextClasDataBunch) (to get the data ready for a text classifier) classes." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Language model data\n", "data_lm = TextLMDataBunch.from_csv(path, 'texts.csv')\n", "# Classifier model data\n", "data_clas = TextClasDataBunch.from_csv(path, 'texts.csv', vocab=data_lm.train_ds.vocab, bs=32)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This does all the necessary preprocessing behing 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`.\n", "\n", "Since this step can be a bit time-consuming, it's best to save the result with:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data_lm.save()\n", "data_clas.save()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This will create a 'tmp' directory where all the computed stuff will be stored. You can then reload those results with:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data_lm = TextLMDataBunch.load(path)\n", "data_clas = TextClasDataBunch.load(path, bs=32)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that you can load the data with different [`DataBunch`](/basic_data.html#DataBunch) parameters (batch size, `bptt`,...)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Fine-tuning a language model" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can use the `data_lm` object we created earlier to fine-tune a pretrained language model. [fast.ai](http://www.fast.ai/) has an English model 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." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Total time: 00:18\n", "epoch train_loss valid_loss accuracy\n", "1 4.720662 4.227249 0.246503 (00:18)\n", "\n" ] } ], "source": [ "learn = language_model_learner(data_lm, pretrained_model=URLs.WT103, drop_mult=0.5)\n", "learn.fit_one_cycle(1, 1e-2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Like a computer vision model, we can then unfreeze the model and fine-tune it." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Total time: 00:22\n", "epoch train_loss valid_loss accuracy\n", "1 4.450525 4.127853 0.253167 (00:22)\n", "\n" ] } ], "source": [ "learn.unfreeze()\n", "learn.fit_one_cycle(1, 1e-3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To evaluate your language model, you can run the [`Learner.predict`](/basic_train.html#Learner.predict) method and specify the number of words you want it to guess." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Total time: 00:00\n", "\n" ] }, { "data": { "text/plain": [ "'This is a review about the first way to climb to overcome the best robert'" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "learn.predict(\"This is a review about\", n_words=10)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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).\n", "\n", "Finally we save the encoder to be able to use it for classification in the next section." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "learn.save_encoder('ft_enc')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Building a classifier" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Total time: 00:26\n", "epoch train_loss valid_loss accuracy\n", "1 0.686503 0.632651 0.701493 (00:26)\n", "\n" ] } ], "source": [ "learn = text_classifier_learner(data_clas, drop_mult=0.5)\n", "learn.load_encoder('ft_enc')\n", "learn.fit_one_cycle(1, 1e-2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Again, we can unfreeze the model and fine-tune it." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Total time: 00:33\n", "epoch train_loss valid_loss accuracy\n", "1 0.612237 0.542365 0.706468 (00:33)\n", "\n" ] } ], "source": [ "learn.freeze_to(-2)\n", "learn.fit_one_cycle(1, slice(5e-3/2., 5e-3))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Total time: 00:55\n", "epoch train_loss valid_loss accuracy\n", "1 0.510760 0.479997 0.791045 (00:55)\n", "\n" ] } ], "source": [ "learn.unfreeze()\n", "learn.fit_one_cycle(1, slice(2e-3/100, 2e-3))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Again, we can predict on a raw text by using the [`Learner.predict`](/basic_train.html#Learner.predict) method." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "('positive', tensor(0), tensor([0.8558, 0.1442]))" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "learn.predict(\"This was a great movie!\")" ] } ], "metadata": { "jekyll": { "keywords": "fastai", "summary": "Application to NLP, including ULMFiT fine-tuning", "title": "text" }, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 2 }