Basic dataset for NLP tasks and helper functions to create a DataBunch

NLP datasets

This module contains the TextDataset class, which is the main dataset you should use for your NLP tasks. It automatically does the preprocessing steps described in text.transform. It also contains all the functions to quickly get a TextDataBunch ready.

Quickly assemble your data

You should get your data in one of the following formats to make the most of the fastai library and use one of the factory methods of one of the TextDataBunch classes:

  • raw text files in folders train, valid, test in an ImageNet style,
  • a csv where some column(s) gives the label(s) and the following one the associated text,
  • a dataframe structured the same way,
  • tokens and labels arrays,
  • ids, vocabulary (correspondence id to word) and labels.

If you are assembling the data for a language model, you should define your labels as always 0 to respect those formats. The first time you create a DataBunch with one of those functions, your data will be preprocessed automatically. You can save it, so that the next time you call it is almost instantaneous.

Below are the classes that help assembling the raw data in a DataBunch suitable for NLP.

class TextLMDataBunch[source][test]

TextLMDataBunch(train_dl:DataLoader, valid_dl:DataLoader, fix_dl:DataLoader=None, test_dl:Optional[DataLoader]=None, device:device=None, dl_tfms:Optional[Collection[Callable]]=None, path:PathOrStr='.', collate_fn:Callable='data_collate', no_check:bool=False) :: TextDataBunch

Tests found for TextLMDataBunch:

Some other tests where TextLMDataBunch is used:

  • pytest -sv tests/test_text_data.py::test_from_csv_and_from_df [source]
  • pytest -sv tests/test_text_data.py::test_should_load_backwards_lm_1 [source]
  • pytest -sv tests/test_text_data.py::test_should_load_backwards_lm_2 [source]

To run tests please refer to this guide.

Create a TextDataBunch suitable for training a language model.

All the texts in the datasets are concatenated and the labels are ignored. Instead, the target is the next word in the sentence.

create[source][test]

create(train_ds, valid_ds, test_ds=None, path:PathOrStr='.', no_check:bool=False, bs=64, val_bs:int=None, num_workers:int=0, device:device=None, collate_fn:Callable='data_collate', dl_tfms:Optional[Collection[Callable]]=None, bptt:int=70, backwards:bool=False, **dl_kwargs) → DataBunch

No tests found for create. To contribute a test please refer to this guide and this discussion.

Create a TextDataBunch in path from the datasets for language modelling. Passes **dl_kwargs on to DataLoader()

class TextClasDataBunch[source][test]

TextClasDataBunch(train_dl:DataLoader, valid_dl:DataLoader, fix_dl:DataLoader=None, test_dl:Optional[DataLoader]=None, device:device=None, dl_tfms:Optional[Collection[Callable]]=None, path:PathOrStr='.', collate_fn:Callable='data_collate', no_check:bool=False) :: TextDataBunch

Tests found for TextClasDataBunch:

Some other tests where TextClasDataBunch is used:

  • pytest -sv tests/test_text_data.py::test_backwards_cls_databunch [source]
  • pytest -sv tests/test_text_data.py::test_from_csv_and_from_df [source]
  • pytest -sv tests/test_text_data.py::test_from_ids_works_for_equally_length_sentences [source]
  • pytest -sv tests/test_text_data.py::test_from_ids_works_for_variable_length_sentences [source]
  • pytest -sv tests/test_text_data.py::test_load_and_save_test [source]

To run tests please refer to this guide.

Create a TextDataBunch suitable for training an RNN classifier.

create[source][test]

create(train_ds, valid_ds, test_ds=None, path:PathOrStr='.', bs:int=32, val_bs:int=None, pad_idx=1, pad_first=True, device:device=None, no_check:bool=False, backwards:bool=False, **dl_kwargs) → DataBunch

No tests found for create. To contribute a test please refer to this guide and this discussion.

Function that transform the datasets in a DataBunch for classification. Passes **dl_kwargs on to DataLoader()

All the texts are grouped by length (with a bit of randomness for the training set) then padded so that the samples have the same length to get in a batch.

class TextDataBunch[source][test]

TextDataBunch(train_dl:DataLoader, valid_dl:DataLoader, fix_dl:DataLoader=None, test_dl:Optional[DataLoader]=None, device:device=None, dl_tfms:Optional[Collection[Callable]]=None, path:PathOrStr='.', collate_fn:Callable='data_collate', no_check:bool=False) :: DataBunch

No tests found for TextDataBunch. To contribute a test please refer to this guide and this discussion.

General class to get a DataBunch for NLP. Subclassed by TextLMDataBunch and TextClasDataBunch.

Factory methods (TextDataBunch)

All those classes have the following factory methods.

from_folder[source][test]

from_folder(path:PathOrStr, train:str='train', valid:str='valid', test:Optional[str]=None, classes:ArgStar=None, tokenizer:Tokenizer=None, vocab:Vocab=None, chunksize:int=10000, max_vocab:int=60000, min_freq:int=2, mark_fields:bool=False, include_bos:bool=True, include_eos:bool=False, **kwargs)

Tests found for from_folder:

Some other tests where from_folder is used:

  • pytest -sv tests/test_text_data.py::test_filter_classes [source]
  • pytest -sv tests/test_text_data.py::test_from_folder [source]

To run tests please refer to this guide.

Create a TextDataBunch from text files in folders.

The floders are scanned in path with a train, valid and maybe test folders. Text files in the train and valid folders should be places in subdirectories according to their classes (not applicable for a language model). tokenizer will be used to parse those texts into tokens.

You can pass a specific vocab for the numericalization step (if you are building a classifier from a language model you fine-tuned for instance). kwargs will be split between the TextDataset function and to the class initialization, you can precise there parameters such as max_vocab, chunksize, min_freq, n_labels (see the TextDataset documentation) or bs, bptt and pad_idx (see the sections LM data and classifier data).

from_csv[source][test]

from_csv(path:PathOrStr, csv_name, valid_pct:float=0.2, test:Optional[str]=None, tokenizer:Tokenizer=None, vocab:Vocab=None, classes:StrList=None, delimiter:str=None, header='infer', text_cols:IntsOrStrs=1, label_cols:IntsOrStrs=0, label_delim:str=None, chunksize:int=10000, max_vocab:int=60000, min_freq:int=2, mark_fields:bool=False, include_bos:bool=True, include_eos:bool=False, **kwargs) → DataBunch

Tests found for from_csv:

  • pytest -sv tests/test_text_data.py::test_from_csv_and_from_df [source]

To run tests please refer to this guide.

Create a TextDataBunch from texts in csv files. kwargs are passed to the dataloader creation.

This method will look for csv_name, and optionally a test csv file, in path. These will be opened with header, using delimiter. You can specify which are the text_cols and label_cols; by default a single label column is assumed to come before a single text column. If your csv has no header, you must specify these as indices. If you're training a language model and don't have labels, you must specify the text_cols. If there are several text_cols, the texts will be concatenated together with an optional field token. If there are several label_cols, the labels will be assumed to be one-hot encoded and classes will default to label_cols (you can ignore that argument for a language model). label_delim can be used to specify the separator between multiple labels in a column.

You can pass a tokenizer to be used to parse the texts into tokens and/or a specific vocab for the numericalization step (if you are building a classifier from a language model you fine-tuned for instance). Otherwise you can specify parameters such as max_vocab, min_freq, chunksize for the Tokenizer and Numericalizer (processors). Other parameters (e.g. bs, val_bs and num_workers, etc.) will be passed to LabelLists.databunch() documentation) (see the LM data and classifier data sections for more info).

from_df[source][test]

from_df(path:PathOrStr, train_df:DataFrame, valid_df:DataFrame, test_df:OptDataFrame=None, tokenizer:Tokenizer=None, vocab:Vocab=None, classes:StrList=None, text_cols:IntsOrStrs=1, label_cols:IntsOrStrs=0, label_delim:str=None, chunksize:int=10000, max_vocab:int=60000, min_freq:int=2, mark_fields:bool=False, include_bos:bool=True, include_eos:bool=False, **kwargs) → DataBunch

Tests found for from_df:

  • pytest -sv tests/test_text_data.py::test_from_csv_and_from_df [source]

Some other tests where from_df is used:

  • pytest -sv tests/test_text_data.py::test_backwards_cls_databunch [source]
  • pytest -sv tests/test_text_data.py::test_load_and_save_test [source]
  • pytest -sv tests/test_text_data.py::test_regression [source]
  • pytest -sv tests/test_text_data.py::test_should_load_backwards_lm_1 [source]
  • pytest -sv tests/test_text_data.py::test_should_load_backwards_lm_2 [source]

To run tests please refer to this guide.

Create a TextDataBunch from DataFrames. kwargs are passed to the dataloader creation.

This method will use train_df, valid_df and optionally test_df to build the TextDataBunch in path. You can specify text_cols and label_cols; by default a single label column comes before a single text column. If you're training a language model and don't have labels, you must specify the text_cols. If there are several text_cols, the texts will be concatenated together with an optional field token. If there are several label_cols, the labels will be assumed to be one-hot encoded and classes will default to label_cols (you can ignore that argument for a language model).

You can pass a tokenizer to be used to parse the texts into tokens and/or a specific vocab for the numericalization step (if you are building a classifier from a language model you fine-tuned for instance). Otherwise you can specify parameters such as max_vocab, min_freq, chunksize for the default Tokenizer and Numericalizer (processors). Other parameters (e.g. bs, val_bs and num_workers, etc.) will be passed to LabelLists.databunch() documentation) (see the LM data and classifier data sections for more info).

from_tokens[source][test]

from_tokens(path:PathOrStr, trn_tok:Tokens, trn_lbls:Collection[Union[int, float]], val_tok:Tokens, val_lbls:Collection[Union[int, float]], vocab:Vocab=None, tst_tok:Tokens=None, classes:ArgStar=None, max_vocab:int=60000, min_freq:int=3, **kwargs) → DataBunch

No tests found for from_tokens. To contribute a test please refer to this guide and this discussion.

Create a TextDataBunch from tokens and labels. kwargs are passed to the dataloader creation.

This function will create a DataBunch from trn_tok, trn_lbls, val_tok, val_lbls and maybe tst_tok.

You can pass a specific vocab for the numericalization step (if you are building a classifier from a language model you fine-tuned for instance). kwargs will be split between the TextDataset function and to the class initialization, you can precise there parameters such as max_vocab, chunksize, min_freq, n_labels, tok_suff and lbl_suff (see the TextDataset documentation) or bs, bptt and pad_idx (see the sections LM data and classifier data).

from_ids[source][test]

from_ids(path:PathOrStr, vocab:Vocab, train_ids:Collection[Collection[int]], valid_ids:Collection[Collection[int]], test_ids:Collection[Collection[int]]=None, train_lbls:Collection[Union[int, float]]=None, valid_lbls:Collection[Union[int, float]]=None, classes:ArgStar=None, processor:PreProcessor=None, **kwargs) → DataBunch

Tests found for from_ids:

  • pytest -sv tests/test_text_data.py::test_from_ids_works_for_equally_length_sentences [source]
  • pytest -sv tests/test_text_data.py::test_from_ids_works_for_variable_length_sentences [source]

To run tests please refer to this guide.

Create a TextDataBunch from ids, labels and a vocab. kwargs are passed to the dataloader creation.

Texts are already preprocessed into train_ids, train_lbls, valid_ids, valid_lbls and maybe test_ids. You can specify the corresponding classes if applicable. You must specify a path and the vocab so that the RNNLearner class can later infer the corresponding sizes in the model it will create. kwargs will be passed to the class initialization.

Load and save

To avoid losing time preprocessing the text data more than once, you should save and load your TextDataBunch using DataBunch.save and load_data.

load[source][test]

load(path:PathOrStr, cache_name:PathOrStr='tmp', processor:PreProcessor=None, **kwargs)

No tests found for load. To contribute a test please refer to this guide and this discussion.

Load a TextDataBunch from path/cache_name. kwargs are passed to the dataloader creation.

Example

Untar the IMDB sample dataset if not already done:

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

Since it comes in the form of csv files, we will use the corresponding text_data method. Here is an overview of what your file you should look like:

pd.read_csv(path/'texts.csv').head()
label text is_valid
0 negative Un-bleeping-believable! Meg Ryan doesn't even ... False
1 positive This is a extremely well-made film. The acting... False
2 negative Every once in a long while a movie will come a... False
3 positive Name just says it all. I watched this movie wi... False
4 negative This movie succeeds at being one of the most u... False

And here is a simple way of creating your DataBunch for language modelling or classification.

data_lm = TextLMDataBunch.from_csv(Path(path), 'texts.csv')
data_clas = TextClasDataBunch.from_csv(Path(path), 'texts.csv')

The TextList input classes

Behind the scenes, the previous functions will create a training, validation and maybe test TextList that will be tokenized and numericalized (if needed) using PreProcessor.

class Text[source][test]

Text(ids, text) :: ItemBase

No tests found for Text. To contribute a test please refer to this guide and this discussion.

Basic item for text data in numericalized ids.

class TextList[source][test]

TextList(items:Iterator[T_co], vocab:Vocab=None, pad_idx:int=1, **kwargs) :: ItemList

Tests found for TextList:

Some other tests where TextList is used:

  • pytest -sv tests/test_text_data.py::test_filter_classes [source]
  • pytest -sv tests/test_text_data.py::test_from_folder [source]
  • pytest -sv tests/test_text_data.py::test_regression [source]

To run tests please refer to this guide.

Basic ItemList for text data.

vocab contains the correspondence between ids and tokens, pad_idx is the id used for padding. You can pass a custom processor in the kwargs to change the defaults for tokenization or numericalization. It should have the following form:

processor = [TokenizeProcessor(tokenizer=SpacyTokenizer('en')), NumericalizeProcessor(max_vocab=30000)]

See below for all the arguments those tokenizers can take.

label_for_lm[source][test]

label_for_lm(**kwargs)

No tests found for label_for_lm. To contribute a test please refer to this guide and this discussion.

A special labelling method for language models.

from_folder[source][test]

from_folder(path:PathOrStr='.', extensions:StrList={'.txt'}, vocab:Vocab=None, processor:PreProcessor=None, **kwargs) → TextList

Tests found for from_folder:

Some other tests where from_folder is used:

  • pytest -sv tests/test_text_data.py::test_filter_classes [source]
  • pytest -sv tests/test_text_data.py::test_from_folder [source]

To run tests please refer to this guide.

Get the list of files in path that have a text suffix. recurse determines if we search subfolders.

show_xys[source][test]

show_xys(xs, ys, max_len:int=70)

No tests found for show_xys. To contribute a test please refer to this guide and this discussion.

Show the xs (inputs) and ys (targets). max_len is the maximum number of tokens displayed.

show_xyzs[source][test]

show_xyzs(xs, ys, zs, max_len:int=70)

No tests found for show_xyzs. To contribute a test please refer to this guide and this discussion.

Show xs (inputs), ys (targets) and zs (predictions). max_len is the maximum number of tokens displayed.

class OpenFileProcessor[source][test]

OpenFileProcessor(ds:Collection[T_co]=None) :: PreProcessor

No tests found for OpenFileProcessor. To contribute a test please refer to this guide and this discussion.

PreProcessor that opens the filenames and read the texts.

open_text[source][test]

open_text(fn:PathOrStr, enc='utf-8')

No tests found for open_text. To contribute a test please refer to this guide and this discussion.

Read the text in fn.

class TokenizeProcessor[source][test]

TokenizeProcessor(ds:ItemList=None, tokenizer:Tokenizer=None, chunksize:int=10000, mark_fields:bool=False, include_bos:bool=True, include_eos:bool=False) :: PreProcessor

No tests found for TokenizeProcessor. To contribute a test please refer to this guide and this discussion.

PreProcessor that tokenizes the texts in ds.

tokenizer is used on bits of chunksize. If mark_fields=True, add field tokens between each parts of the texts (given when the texts are read in several columns of a dataframe). See more about tokenizers in the transform documentation.

class NumericalizeProcessor[source][test]

NumericalizeProcessor(ds:ItemList=None, vocab:Vocab=None, max_vocab:int=60000, min_freq:int=3) :: PreProcessor

No tests found for NumericalizeProcessor. To contribute a test please refer to this guide and this discussion.

PreProcessor that numericalizes the tokens in ds.

Uses vocab for this (if not None), otherwise create one with max_vocab and min_freq from tokens.

Language Model data

A language model is trained to guess what the next word is inside a flow of words. We don't feed it the different texts separately but concatenate them all together in a big array. To create the batches, we split this array into bs chunks of continuous texts. Note that in all NLP tasks, we don't use the usual convention of sequence length being the first dimension so batch size is the first dimension and sequence length is the second. Here you can read the chunks of texts in lines.

path = untar_data(URLs.IMDB_SAMPLE)
data = TextLMDataBunch.from_csv(path, 'texts.csv')
x,y = next(iter(data.train_dl))
example = x[:15,:15].cpu()
texts = pd.DataFrame([data.train_ds.vocab.textify(l).split(' ') for l in example])
texts
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
0 xxbos xxmaj name just says it all . i watched this movie with my dad
1 going to see anything you 'll remember . xxbos xxmaj evidently when you offer a
2 of the xxunk xxunk xxmaj superbly shot , this thrilling adult adventure certainly contains some
3 \n\n xxmaj one bright light in the midst of this is xxmaj fred xxmaj xxunk
4 leave you xxunk that you watched it . i feel really bad for those xxmaj
5 xxmaj ginger 's blonde hair ) has a couple of emotional solo numbers , including
6 . xxmaj this is what really attracted me to this film . i was impressed
7 into the hype that one you are somehow white or superior ... you are not
8 come unintentionally , like when they try to explain that an invisible man 's xxunk
9 just watch the movie , and i dear say you 'll see things a bit
10 for the reform movement and meets xxmaj eponine . xxmaj except ... not xxmaj eponine
11 xxmaj well , given the target audience , that may not have been too bad
12 gets roles in movies , in my opinion though she should stick to movies of
13 its share , though far smaller than xxunk even including a basic view of the
14 ruins - scene is xxup almost european - like cinema ( the movie is eager

This is all done internally when we use TextLMDataBunch, by wrapping the dataset in the following pre-loader before calling a DataLoader.

class LanguageModelPreLoader[source][test]

LanguageModelPreLoader(dataset:LabelList, lengths:Collection[int]=None, bs:int=32, bptt:int=70, backwards:bool=False, shuffle:bool=False) :: Callback

No tests found for LanguageModelPreLoader. To contribute a test please refer to this guide and this discussion.

Transforms the tokens in dataset to a stream of contiguous batches for language modelling.

LanguageModelPreLoader is an internal class uses for training a language model. It takes the sentences passed as a jagged array of numericalised sentences in dataset and returns contiguous batches to the pytorch dataloader with batch size bs and a sequence length bptt.

  • lengths can be provided for the jagged training data else lengths is calculated internally
  • backwards=True will reverses the sentences.
  • shuffle=True, will shuffle the order of the sentences, at the start of each epoch - except the first

The following description is usefull for understanding the implementation of LanguageModelPreLoader:

  • idx: instance of CircularIndex that indexes items while taking the following into account 1) shuffle, 2) direction of indexing, 3) wraps around to head (reading forward) or tail (reading backwards) of the ragged array as needed in order to fill the last batch(s)

  • ro: index of the first rag of each row in the batch to be extract. Returns as index to the next rag to be extracted

  • ri: Reading forward: index to the first token to be extracted in the current rag (ro). Reading backwards: one position after the last token to be extracted in the rag

  • overlap: overlap between batches is 1, because we only predict the next token

Classifier data

When preparing the data for a classifier, we keep the different texts separate, which poses another challenge for the creation of batches: since they don't all have the same length, we can't easily collate them together in batches. To help with this we use two different techniques:

  • padding: each text is padded with the PAD token to get all the ones we picked to the same size
  • sorting the texts (ish): to avoid having together a very long text with a very short one (which would then have a lot of PAD tokens), we regroup the texts by order of length. For the training set, we still add some randomness to avoid showing the same batches at every step of the training.

Here is an example of batch with padding (the padding index is 1, and the padding is applied before the sentences start).

path = untar_data(URLs.IMDB_SAMPLE)
data = TextClasDataBunch.from_csv(path, 'texts.csv')
iter_dl = iter(data.train_dl)
_ = next(iter_dl)
x,y = next(iter_dl)
x[-10:,:20]
tensor([[   1,    1,    1,    1,    1,    1,    1,    2,   18,  310,    9,    0,
           11,    0,    9,   48,    8,    0,   11, 2301],
        [   1,    1,    1,    1,    1,    1,    1,    2,    4, 1427,   15,    8,
          521,   10,    4,   90,  131,    9, 1427,  242],
        [   1,    1,    1,    1,    1,    1,    1,    2,   18,  175,   55, 2063,
         4677,   14,    8,  209,   22, 1343,   26,   20],
        [   1,    1,    1,    1,    1,    1,    1,    1,    2,    4,   20,   30,
           24,    8,  110,  616,   30,  164,  745,   18],
        [   1,    1,    1,    1,    1,    1,    1,    1,    2,   18,   24, 3560,
           14,  130,    8,   30,   26,   85,  193,    9],
        [   1,    1,    1,    1,    1,    1,    1,    1,    2,   18,  101,    0,
           20,  153,   71,   18,   24, 4055,   17,    4],
        [   1,    1,    1,    1,    1,    1,    1,    1,    2,    4, 1998,  256,
            4,    0,    4,    0,  273,   34,    8,    0],
        [   1,    1,    1,    1,    1,    1,    1,    1,    1,    2,    4,   20,
           24,   12,  119,   30,   19,   83,   12,  202],
        [   1,    1,    1,    1,    1,    1,    1,    1,    1,    2,    4,    8,
           79, 1031,  185,   13,   20,   30,   24,    8],
        [   1,    1,    1,    1,    1,    1,    1,    1,    1,    1,    2,   18,
           61,   36,  143,  104,   20,   30, 1408,   51]], device='cuda:0')

This is all done internally when we use TextClasDataBunch, by using the following classes:

class SortSampler[source][test]

SortSampler(data_source:NPArrayList, key:KeyFunc) :: Sampler

No tests found for SortSampler. To contribute a test please refer to this guide and this discussion.

Go through the text data by order of length.

This pytorch Sampler is used for the validation and (if applicable) the test set.

class SortishSampler[source][test]

SortishSampler(data_source:NPArrayList, key:KeyFunc, bs:int) :: Sampler

Tests found for SortishSampler:

  • pytest -sv tests/test_text_data.py::test_sortish_sampler [source]

To run tests please refer to this guide.

Go through the text data by order of length with a bit of randomness.

This pytorch Sampler is generally used for the training set.

pad_collate[source][test]

pad_collate(samples:BatchSamples, pad_idx:int=1, pad_first:bool=True, backwards:bool=False) → Tuple[LongTensor, LongTensor]

No tests found for pad_collate. To contribute a test please refer to this guide and this discussion.

Function that collect samples and adds padding. Flips token order if needed

This will collate the samples in batches while adding padding with pad_idx. If pad_first=True, padding is applied at the beginning (before the sentence starts) otherwise it's applied at the end.