from fastai.gen_doc.nbdoc import *
from fastai.text import *
from fastai.gen_doc.nbdoc import *
from fastai import *
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.
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:
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.
show_doc(TextLMDataBunch, title_level=3, doc_string=False)
class TextLMDataBunch[source]
TextLMDataBunch(train_dl:DataLoader,valid_dl:DataLoader,test_dl:Optional[DataLoader]=None,device:device=None,tfms:Optional[Collection[Callable]]=None,path:PathOrStr='.',collate_fn:Callable='data_collate') ::TextDataBunch
show_doc(TextLMDataBunch.show_batch)
show_batch[source]
show_batch(rows:int=5,ds_type:DatasetType=<DatasetType.Train: 1>,kwargs)
Show a batch of data in ds_type on a few rows.
show_doc(TextClasDataBunch, title_level=3, doc_string=False)
class TextClasDataBunch[source]
TextClasDataBunch(train_dl:DataLoader,valid_dl:DataLoader,test_dl:Optional[DataLoader]=None,device:device=None,tfms:Optional[Collection[Callable]]=None,path:PathOrStr='.',collate_fn:Callable='data_collate') ::TextDataBunch
Create a DataBunch suitable for a text classifier: all the texts are grouped by length (with a bit of randomness for the training set) then padded.
show_doc(TextClasDataBunch.show_batch)
show_batch[source]
show_batch(rows:int=5,ds_type:DatasetType=<DatasetType.Train: 1>,kwargs)
Show a batch of data in ds_type on a few rows.
show_doc(TextDataBunch, title_level=3, doc_string=False)
class TextDataBunch[source]
TextDataBunch(train_dl:DataLoader,valid_dl:DataLoader,test_dl:Optional[DataLoader]=None,device:device=None,tfms:Optional[Collection[Callable]]=None,path:PathOrStr='.',collate_fn:Callable='data_collate') ::DataBunch
Create a DataBunch with the raw texts. This is only going to work if they all ahve the same lengths.
All those classes have the following factory methods.
show_doc(TextDataBunch.from_folder, doc_string=False)
This function will create a DataBunch from texts placed in path in a train, valid and maybe test folders. Text files in the train and valid folders should be places in subdirectories according to their classes (always the same for a language model) and the ones for the test folder should all be placed there directly. tokenizer will be used to parse those texts into tokens. The shuffle flag will optionally shuffle the texts found.
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).
show_doc(TextDataBunch.from_csv, doc_string=False)
from_csv[source]
from_csv(path:PathOrStr,csv_name,valid_pct:float=0.2,test:Optional[str]=None,tokenizer:Tokenizer=None,vocab:Vocab=None,classes:StrList=None,header='infer',text_cols:Union[int,Collection[int],str,StrList]=1,label_cols:Union[int,Collection[int],str,StrList]=0,label_delim:str=None,kwargs) →DataBunch
This function will create a DataBunch from texts placed in path in a csv file and maybe test csv file opened with header. You can specify txt_cols and lbl_cols or just an integer n_labels in which case the label(s) should be the first column(s). 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).
show_doc(TextDataBunch.from_df, doc_string=False)
from_df[source]
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:Union[int,Collection[int],str,StrList]=1,label_cols:Union[int,Collection[int],str,StrList]=0,label_delim:str=None,kwargs) →DataBunch
This function will create a DataBunch in path from texts in train_df, valid_df and maybe test_df. By default, those are opened with header=infer but you can specify another value in the kwargs. You can specify txt_cols and lbl_cols or just an integer n_labels in which case the label(s) should be the first column(s). 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).
show_doc(TextDataBunch.from_tokens, doc_string=False)
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).
show_doc(TextDataBunch.from_ids, doc_string=False)
from_ids[source]
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
This function will create a DataBunch in path from texts already processed into trn_ids, trn_lbls, val_ids, val_lbls and maybe tst_ids. You can specify the corresponding classes if applciable. You must specify 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.
To avoid losing time preprocessing the text data more than once, you should save/load your TextDataBunch using thse methods.
show_doc(TextDataBunch.load)
load[source]
load(path:PathOrStr,cache_name:PathOrStr='tmp',processor:PreProcessor=None,kwargs)
Load a TextDataBunch from path/cache_name. kwargs are passed to the dataloader creation.
show_doc(TextDataBunch.save)
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')
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.
show_doc(Text, doc_string=False, title_level=3)
Basic item for text data, contains the numericalized ids and the corresponding text.
show_doc(Text.show_xys)
show_xys[source]
show_xys(xs,ys,max_len:int=70)
Show the xs and ys. max_len is the maximum number of tokens displayed.
show_doc(Text.show_xyzs)
show_xyzs[source]
show_xyzs(xs,ys,zs,max_len:int=70)
Show xs (inputs), ys (targets) and zs (predictions). max_len is the maximum number of tokens displayed.
show_doc(TextList, title_level=3)
The basic ItemList for text data in items with the corresponding vocab.
show_doc(TextList.label_for_lm)
show_doc(TextList.from_folder)
from_folder[source]
from_folder(path:PathOrStr='.',extensions:StrList={'.txt'},vocab:Vocab=None,processor:PreProcessor=None,kwargs) →TextList
Get the list of files in path that have a text suffix. recurse determines if we search subfolders.
show_doc(OpenFileProcessor, title_level=3)
class OpenFileProcessor[source]
OpenFileProcessor(ds:Collection=None) ::PreProcessor
Simple Preprocessor that opens the files in items and reads the texts inside them.
show_doc(open_text)
show_doc(TokenizeProcessor, title_level=3)
class TokenizeProcessor[source]
TokenizeProcessor(ds:ItemList=None,tokenizer:Tokenizer=None,chunksize:int=10000,mark_fields:bool=False) ::PreProcessor
Simple PreProcessor that tokenizes the texts in items using tokenizer by bits of chunsize. If mark_fields is True, add field tokens.
show_doc(NumericalizeProcessor, title_level=3, doc_string=False)
class NumericalizeProcessor[source]
NumericalizeProcessor(ds:ItemList=None,vocab:Vocab=None,max_vocab:int=60000,min_freq:int=2) ::PreProcessor
Numericalize the tokens with vocab (if not None) otherwise create one with max_vocab and min_freq from tokens.
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 chuncks of continuous texts. Note that in all NLP tasks, we use the pytoch convention of sequence length being the first dimension (and batch size being the second one) so we transpose that array so that we can read the chunks of texts in columns. Here is an example of batch from our imdb sample dataset.
path = untar_data(URLs.IMDB_SAMPLE)
data = TextLMDataBunch.from_csv(path, 'texts.csv')
x,y = next(iter(data.train_dl))
example = x[:20,:10].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 | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | xxbos | and | - | on | xxmaj | ) | the | worst | . | of |
| 1 | xxfld | severely | life | stage | victor | . | actors | effects | xxmaj | the |
| 2 | 1 | retarded | marching | in | xxmaj | xxmaj | make | ever | may | movie |
| 3 | xxmaj | at | band | a | vargas | from | you | . | not | lying |
| 4 | this | it | whose | very | is | there | believe | xxmaj | be | in |
| 5 | film | 's | xxunk | xxunk | that | , | they | the | spectacular | bed |
| 6 | was | worst | for | environment | he | he | are | xxmaj | , | . |
| 7 | a | . | a | . | 's | is | that | vietnam | but | xxmaj |
| 8 | big | xxmaj | xxmaj | ( | a | xxunk | person | scenes | it | the |
| 9 | disappointment | xxunk | labor | xxmaj | sexually | to | , | are | 's | best |
| 10 | . | xxmaj | xxmaj | with | active | seek | it | shot | concept | actresses |
| 11 | \n\n | xxunk | day | songs | teenager | out | 's | in | is | in |
| 12 | i | was | parade | of | with | a | a | xxunk | pretty | the |
| 13 | take | xxunk | provide | this | a | camp | much | xxunk | xxunk | world |
| 14 | the | the | discipline | strength | xxunk | where | more | , | and | can |
| 15 | opposite | bottom | and | , | the | xxmaj | enjoyable | i | it | not |
| 16 | view | of | purpose | you | size | american | movie | xxunk | delivers | make |
| 17 | of | the | to | do | of | xxunk | ! | ! | in | anything |
| 18 | the | xxunk | their | n't | xxmaj | are | xxbos | xxmaj | the | very |
| 19 | critics | here | lives | need | manhattan | supposedly | xxfld | lou | right | interesting |
Then, as suggested in this article from Stephen Merity et al., we don't use a fixed bptt through the different batches but slightly change it from batch to batch.
iter_dl = iter(data.train_dl)
for _ in range(5):
x,y = next(iter_dl)
print(x.size())
torch.Size([61, 64]) torch.Size([69, 64]) torch.Size([70, 64]) torch.Size([73, 64]) torch.Size([68, 64])
This is all done internally when we use TextLMDataBunch, by creating DataLoader using the following class:
show_doc(LanguageModelLoader, doc_string=False)
Takes the texts from dataset and concatenate them all, then create a big array with bs columns (transposed from the data source so that we read the texts in the columns). Spits batches with a size approximately equal to bptt but changing at every batch. If backwards is True, reverses the original text. If shuffle is True, we shuffle the texts before concatenating them together at the start of each epoch. max_len is the maximum amount we add to bptt.
show_doc(LanguageModelLoader.batchify, doc_string=False)
batchify[source]
batchify(data:ndarray) →LongTensor
Called at the inialization to create the big array of text ids from the data array.
show_doc(LanguageModelLoader.get_batch)
get_batch[source]
get_batch(i:int,seq_len:int) →Tuple[LongTensor,LongTensor]
Create a batch at i of a given seq_len.
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:
PAD token to get all the ones we picked to the same sizePAD 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[:20,-10:]
tensor([[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[ 44, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[ 45, 44, 44, 1, 1, 1, 1, 1, 1, 1],
[ 41, 45, 45, 44, 1, 1, 1, 1, 1, 1],
[ 7, 41, 41, 45, 44, 44, 44, 44, 1, 1],
[378, 2, 2, 41, 45, 45, 45, 45, 44, 44],
[ 0, 15, 48, 2, 41, 41, 41, 41, 45, 45],
[ 12, 22, 382, 57, 2, 13, 2, 2, 41, 41]], device='cuda:0')
This is all done internally when we use TextClasDataBunch, by using the following classes:
show_doc(SortSampler, doc_string=False)
pytorch Sampler to batchify the data_source by order of length of the texts. Used for the validation and (if applicable) the test set.
show_doc(SortishSampler, doc_string=False)
pytorch Sampler to batchify with size bs the data_source by order of length of the texts with a bit of randomness. Used for the training set.
show_doc(pad_collate, doc_string=False)
pad_collate[source]
pad_collate(samples:BatchSamples,pad_idx:int=1,pad_first:bool=True) →Tuple[LongTensor,LongTensor]
Function used by the pytorch DataLoader to collate the samples in batches while adding padding with pad_idx. If pad_first is True, padding is applied at the beginning (before the sentence starts) otherwise it's applied at the end.
show_doc(TextLMDataBunch.create)
create[source]
create(train_ds,valid_ds,test_ds=None,path:PathOrStr='.',kwargs) →DataBunch
Create a TextDataBunch in path from the datasets for language modelling.
show_doc(TextClasDataBunch.create)
show_doc(TextList.new)
new[source]
new(items:Iterator,kwargs) →NumericalizedTextList
show_doc(TextList.get)
get[source]
get(i)
show_doc(TokenizeProcessor.process_one)
process_one[source]
process_one(item)
show_doc(TokenizeProcessor.process)
process[source]
process(ds)
show_doc(OpenFileProcessor.process_one)
process_one[source]
process_one(item)
show_doc(NumericalizeProcessor.process)
process[source]
process(ds)
show_doc(NumericalizeProcessor.process_one)
process_one[source]
process_one(item)
show_doc(Text)
show_doc(TextList.from_folder)
from_folder[source]
from_folder(path:PathOrStr='.',extensions:StrList={'.txt'},vocab:Vocab=None,processor:PreProcessor=None,kwargs) →TextList
Get the list of files in path that have a text suffix. recurse determines if we search subfolders.