Process
Last updated
Last updated
🌍 Datasets provides many tools for modifying the structure and content of a dataset. These tools are important for tidying up a dataset, creating additional columns, converting between features and formats, and much more.
This guide will show you how to:
Reorder rows and split the dataset.
Rename and remove columns, and other common column operations.
Apply processing functions to each example in a dataset.
Concatenate datasets.
Apply a custom formatting transform.
Save and export processed datasets.
For more details specific to processing other dataset modalities, take a look at the , the , or the .
The examples in this guide use the MRPC dataset, but feel free to load any dataset of your choice and follow along!
Copied
All processing methods in this guide return a new object. Modification is not done in-place. Be careful about overriding your previous dataset!
There are several functions for rearranging the structure of a dataset. These functions are useful for selecting only the rows you want, creating train and test splits, and sharding very large datasets into smaller chunks.
Copied
Under the hood, this creates a list of indices that is sorted according to values of the column. This indices mapping is then used to access the right rows in the underlying Arrow table.
Copied
Copied
Copied
Copied
Copied
Unless the list of indices to keep is contiguous, those methods also create an indices mapping under the hood.
Copied
The splits are shuffled by default, but you can set shuffle=False
to prevent shuffling.
Copied
After sharding the dataset into four chunks, the first shard will only have 6250 examples:
Copied
The following functions allow you to modify the columns of a dataset. These functions are useful for renaming or removing columns, changing columns to a new set of features, and flattening nested column structures.
Copied
Copied
Copied
Copied
Casting only works if the original feature type and new feature type are compatible. For example, you can cast a column with the feature type Value("int32")
to Value("bool")
if the original column only contains ones and zeros.
Copied
Sometimes a column can be a nested structure of several types. Take a look at the nested structure below from the SQuAD dataset:
Copied
Copied
Notice how the subfields are now their own independent columns: answers.text
and answers.answer_start
.
In the following example, prefix each sentence1
value in the dataset with 'My sentence: '
.
Start by creating a function that adds 'My sentence: '
to the beginning of each sentence. The function needs to accept and output a dict
:
Copied
Copied
Copied
Copied
Copied
The main use-case for rank is to parallelize computation across several GPUs. This requires setting multiprocess.set_start_method("spawn")
. If you don’t you’ll receive the following CUDA error:
Copied
Copied
Split long examples
When examples are too long, you may want to split them into several smaller chunks. Begin by creating a function that:
Splits the sentence1
field into chunks of 50 characters.
Stacks all the chunks together to create the new dataset.
Copied
Copied
Notice how the sentences are split into shorter chunks now, and there are more rows in the dataset.
Copied
Data augmentation
Copied
Create a function to randomly select a word to mask in the sentence. The function should also return the original sentence and the top two replacements generated by RoBERTA.
Copied
Copied
For each original sentence, RoBERTA augmented a random word with three alternatives. The original word distorting
is supplemented by withholding
, suppressing
, and destroying
.
Copied
The following example shows how you can use torch.distributed.barrier
to synchronize the processes:
Copied
Copied
You can also concatenate two datasets horizontally by setting axis=1
as long as the datasets have the same number of rows:
Copied
You can define sampling probabilities for each of the original datasets to specify how to interleave the datasets. In this case, the new dataset is constructed by getting examples one by one from a random dataset until one of the datasets runs out of samples.
Copied
You can also specify the stopping_strategy
. The default strategy, first_exhausted
, is a subsampling strategy, i.e the dataset construction is stopped as soon one of the dataset runs out of samples. You can specify stopping_strategy=all_exhausted
to execute an oversampling strategy. In this case, the dataset construction is stopped as soon as every samples in every dataset has been added at least once. In practice, it means that if a dataset is exhausted, it will return to the beginning of this dataset until the stop criterion has been reached. Note that if no sampling probabilities are specified, the new dataset will have max_length_datasets*nb_dataset samples
.
Copied
For example, create PyTorch tensors by setting type="torch"
:
Copied
Copied
Copied
Copied
Copied
Save your dataset by providing the path to the directory you wish to save it to:
Copied
Copied
🌍 Datasets supports exporting as well so you can work with your dataset in other applications. The following table shows currently supported file formats you can export to:
CSV
JSON
Parquet
SQL
In-memory Python object
For example, export your dataset to a CSV file like this:
Copied
Use to sort column values according to their numerical values. The provided column must be NumPy compatible.
The function randomly rearranges the column values. You can specify the generator
parameter in this function to use a different numpy.random.Generator
if you want more control over the algorithm used to shuffle the dataset.
Shuffling takes the list of indices [0:len(my_dataset)]
and shuffles it to create an indices mapping. However as soon as your has an indices mapping, the speed can become 10x slower. This is because there is an extra step to get the row index to read using the indices mapping, and most importantly, you aren’t reading contiguous chunks of data anymore. To restore the speed, you’d need to rewrite the entire dataset on your disk again using , which removes the indices mapping. Alternatively, you can switch to an and leverage its fast approximate shuffling :
There are two options for filtering rows in a dataset: and .
returns rows according to a list of indices:
returns rows that match a specified condition:
can also filter by indices if you set with_indices=True
:
The function creates train and test splits if your dataset doesn’t already have them. This allows you to adjust the relative proportions or an absolute number of samples in each split. In the example below, use the test_size
parameter to create a test split that is 10% of the original dataset:
🌍 Datasets supports sharding to divide a very large dataset into a predefined number of chunks. Specify the num_shards
parameter in to determine the number of shards to split the dataset into. You’ll also need to provide the shard you want to return with the index
parameter.
For example, the dataset has 25000 examples:
Use when you need to rename a column in your dataset. Features associated with the original column are actually moved under the new column name, instead of just replacing the original column in-place.
Provide with the name of the original column, and the new column name:
When you need to remove one or more columns, provide the column name to remove to the function. Remove more than one column by providing a list of column names:
Conversely, selects one or more columns to keep and removes the rest. This function takes either one or a list of column names:
The function transforms the feature type of one or more columns. This function accepts your new as its argument. The example below demonstrates how to change the and features:
Use the function to change the feature type of a single column. Pass the column name and its new feature type as arguments:
The answers
field contains two subfields: text
and answer_start
. Use the function to extract the subfields into their own separate columns:
Some of the more powerful applications of 🌍 Datasets come from using the function. The primary purpose of is to speed up processing functions. It allows you to apply a processing function to each example in a dataset, independently or in batches. This function can even create new rows and columns.
Now use to apply the add_prefix
function to the entire dataset:
Let’s take a look at another example, except this time, you’ll remove a column with . When you remove a column, it is only removed after the example has been provided to the mapped function. This allows the mapped function to use the content of the columns before they are removed.
Specify the column to remove with the remove_columns
parameter in :
🌍 Datasets also has a function which is faster because it doesn’t copy the data of the remaining columns.
You can also use with indices if you set with_indices=True
. The example below adds the index to the beginning of each sentence:
The also works with the rank of the process if you set with_rank=True
. This is analogous to the with_indices
parameter. The with_rank
parameter in the mapped function goes after the index
one if it is already present.
Multiprocessing significantly speeds up processing by parallelizing processes on the CPU. Set the num_proc
parameter in to set the number of processes to use:
The function supports working with batches of examples. Operate on batches by setting batched=True
. The default batch size is 1000, but you can adjust it with the batch_size
parameter. Batch processing enables interesting applications such as splitting long sentences into shorter chunks and data augmentation.
Apply the function with :
The function could also be used for data augmentation. The following example generates additional words for a masked token in a sentence.
Load and use the model in 🌍 Transformers’ :
Use to apply the function over the whole dataset:
Many datasets have splits that can be processed simultaneously with . For example, tokenize the sentence1
field in the train and test split by:
When you use in a distributed setting, you should also use . This ensures the main process performs the mapping, while the other processes load the results, thereby avoiding duplicate work.
Separate datasets can be concatenated if they share the same column types. Concatenate datasets with :
You can also mix several datasets together by taking alternating examples from each one to create a new dataset. This is known as interleaving, which is enabled by the function. Both and work with regular and objects. Refer to the guide for an example of how to interleave objects.
The function changes the format of a column to be compatible with some common data formats. Specify the output you’d like in the type
parameter and the columns you want to format. Formatting is applied on-the-fly.
The function also changes the format of a column, except it returns a new object:
🌍 Datasets also provides support for other common data formats such as NumPy, Pandas, and JAX. Check out the guide for more details on how to efficiently create a TensorFlow dataset.
If you need to reset the dataset to its original format, use the function:
The function applies a custom formatting transform on-the-fly. This function replaces any previously specified format. For example, you can use this function to tokenize and pad tokens on-the-fly. Tokenization is only applied when examples are accessed:
You can also use the function to decode formats not supported by . For example, the feature uses - a fast and simple library to install - but it does not provide support for less common audio formats. Here is where you can use to apply a custom decoding transform on the fly. You’re free to use any library you like to decode the audio files.
The example below uses the package to open an audio format not supported by soundfile
:
Once you are done processing your dataset, you can save and reuse it later with .
Use the function to reload the dataset:
Want to save your dataset to a cloud storage provider? Read our guide to learn how to save your dataset to AWS or Google Cloud Storage.
or