Load
Load
Your data can be stored in various places; they can be on your local machineβs disk, in a Github repository, and in in-memory data structures like Python dictionaries and Pandas DataFrames. Wherever a dataset is stored, π Datasets can help you load it.
This guide will show you how to load a dataset from:
The Hub without a dataset loading script
Local loading script
Local files
In-memory data
Offline
A specific slice of a split
For more details specific to loading other dataset modalities, take a look at the load audio dataset guide, the load image dataset guide, or the load text dataset guide.
BOINC AI Hub
Datasets are loaded from a dataset loading script that downloads and generates the dataset. However, you can also load a dataset from any dataset repository on the Hub without a loading script! Begin by creating a dataset repository and upload your data files. Now you can use the load_dataset() function to load the dataset.
For example, try loading the files from this demo repository by providing the repository namespace and dataset name. This dataset repository contains CSV files, and the code below loads the dataset from the CSV files:
Copied
>>> from datasets import load_dataset
>>> dataset = load_dataset("lhoestq/demo1")Some datasets may have more than one version based on Git tags, branches, or commits. Use the revision parameter to specify the dataset version you want to load:
Copied
Refer to the Upload a dataset to the Hub tutorial for more details on how to create a dataset repository on the Hub, and how to upload your data files.
A dataset without a loading script by default loads all the data into the train split. Use the data_files parameter to map data files to splits like train, validation and test:
Copied
If you donβt specify which data files to use, load_dataset() will return all the data files. This can take a long time if you load a large dataset like C4, which is approximately 13TB of data.
You can also load a specific subset of the files with the data_files or data_dir parameter. These parameters can accept a relative path which resolves to the base path corresponding to where the dataset is loaded from.
Copied
The split parameter can also map a data file to a specific split:
Copied
Local loading script
You may have a π Datasets loading script locally on your computer. In this case, load the dataset by passing one of the following paths to load_dataset():
The local path to the loading script file.
The local path to the directory containing the loading script file (only if the script file has the same name as the directory).
Copied
Edit loading script
You can also edit a loading script from the Hub to add your own modifications. Download the dataset repository locally so any data files referenced by a relative path in the loading script can be loaded:
Copied
Make your edits to the loading script and then load it by passing its local path to load_dataset():
Copied
Local and remote files
Datasets can be loaded from local files stored on your computer and from remote files. The datasets are most likely stored as a csv, json, txt or parquet file. The load_dataset() function can load each of these file types.
CSV
π Datasets can read a dataset made up of one or several CSV files (in this case, pass your CSV files as a list):
Copied
For more details, check out the how to load tabular datasets from CSV files guide.
JSON
JSON files are loaded directly with load_dataset() as shown below:
Copied
JSON files have diverse formats, but we think the most efficient format is to have multiple JSON objects; each line represents an individual row of data. For example:
Copied
Another JSON format you may encounter is a nested field, in which case youβll need to specify the field argument as shown in the following:
Copied
To load remote JSON files via HTTP, pass the URLs instead:
Copied
While these are the most common JSON formats, youβll see other datasets that are formatted differently. π Datasets recognizes these other formats and will fallback accordingly on the Python JSON loading methods to handle them.
Parquet
Parquet files are stored in a columnar format, unlike row-based files like a CSV. Large datasets may be stored in a Parquet file because it is more efficient and faster at returning your query.
To load a Parquet file:
Copied
To load remote Parquet files via HTTP, pass the URLs instead:
Copied
Arrow
Arrow files are stored in an in-memory columnar format, unlike row-based formats like CSV and uncompressed formats like Parquet.
To load an Arrow file:
Copied
To load remote Arrow files via HTTP, pass the URLs instead:
Copied
Arrow is the file format used by π Datasets under the hood, therefore you can load a local Arrow file using Dataset.from_file() directly:
Copied
Unlike load_dataset(), Dataset.from_file() memory maps the Arrow file without preparing the dataset in the cache, saving you disk space. The cache directory to store intermediate processing results will be the Arrow file directory in that case.
For now only the Arrow streaming format is supported. The Arrow IPC file format (also known as Feather V2) is not supported.
SQL
Read database contents with from_sql() by specifying the URI to connect to your database. You can read both table names and queries:
Copied
For more details, check out the how to load tabular datasets from SQL databases guide.
Multiprocessing
When a dataset is made of several files (that we call βshardsβ), it is possible to significantly speed up the dataset downloading and preparation step.
You can choose how many processes youβd like to use to prepare a dataset in parallel using num_proc. In this case, each process is given a subset of shards to prepare:
Copied
In-memory data
π Datasets will also allow you to create a Dataset directly from in-memory data structures like Python dictionaries and Pandas DataFrames.
Python dictionary
Load Python dictionaries with from_dict():
Copied
Python list of dictionaries
Load a list of Python dictionaries with from_list():
Copied
Python generator
Create a dataset from a Python generator with from_generator():
Copied
This approach supports loading data larger than available memory.
You can also define a sharded dataset by passing lists to gen_kwargs:
Copied
Pandas DataFrame
Load Pandas DataFrames with from_pandas():
Copied
For more details, check out the how to load tabular datasets from Pandas DataFrames guide.
Offline
Even if you donβt have an internet connection, it is still possible to load a dataset. As long as youβve downloaded a dataset from the Hub repository before, it should be cached. This means you can reload the dataset from the cache and use it offline.
If you know you wonβt have internet access, you can run π Datasets in full offline mode. This saves time because instead of waiting for the Dataset builder download to time out, π Datasets will look directly in the cache. Set the environment variable HF_DATASETS_OFFLINE to 1 to enable full offline mode.
Slice splits
You can also choose only to load specific slices of a split. There are two options for slicing a split: using strings or the ReadInstruction API. Strings are more compact and readable for simple cases, while ReadInstruction is easier to use with variable slicing parameters.
Concatenate a train and test split by:
Copied
Select specific rows of the train split:
Copied
Or select a percentage of a split with:
Copied
Select a combination of percentages from each split:
Copied
Finally, you can even create cross-validated splits. The example below creates 10-fold cross-validated splits. Each validation dataset is a 10% chunk, and the training dataset makes up the remaining complementary 90% chunk:
Copied
Percent slicing and rounding
The default behavior is to round the boundaries to the nearest integer for datasets where the requested slice boundaries do not divide evenly by 100. As shown below, some slices may contain more examples than others. For instance, if the following train split includes 999 records, then:
Copied
If you want equal sized splits, use pct1_dropremainder rounding instead. This treats the specified percentage boundaries as multiples of 1%.
Copied
pct1_dropremainder rounding may truncate the last examples in a dataset if the number of examples in your dataset donβt divide evenly by 100.
Troubleshooting
Sometimes, you may get unexpected results when you load a dataset. Two of the most common issues you may encounter are manually downloading a dataset and specifying features of a dataset.
Manual download
Certain datasets require you to manually download the dataset files due to licensing incompatibility or if the files are hidden behind a login page. This causes load_dataset() to throw an AssertionError. But π Datasets provides detailed instructions for downloading the missing files. After youβve downloaded the files, use the data_dir argument to specify the path to the files you just downloaded.
For example, if you try to download a configuration from the MATINF dataset:
Copied
If youβve already downloaded a dataset from the Hub with a loading script to your computer, then you need to pass an absolute path to the data_dir or data_files parameter to load that dataset. Otherwise, if you pass a relative path, load_dataset() will load the directory from the repository on the Hub instead of the local directory.
Specify features
When you create a dataset from local files, the Features are automatically inferred by Apache Arrow. However, the datasetβs features may not always align with your expectations, or you may want to define the features yourself. The following example shows how you can add custom labels with the ClassLabel feature.
Start by defining your own labels with the Features class:
Copied
Next, specify the features parameter in load_dataset() with the features you just created:
Copied
Now when you look at your dataset features, you can see it uses the custom labels you defined:
Copied
Metrics
Metrics is deprecated in π Datasets. To learn more about how to use metrics, take a look at the library π Evaluate! In addition to metrics, you can find more tools for evaluating models and datasets.
When the metric you want to use is not supported by π Datasets, you can write and use your own metric script. Load your metric by providing the path to your local metric loading script:
Copied
See the Metrics guide for more details on how to write your own metric loading script.
Load configurations
It is possible for a metric to have different configurations. The configurations are stored in the config_name parameter in MetricInfo attribute. When you load a metric, provide the configuration name as shown in the following:
Copied
Distributed setup
When working in a distributed or parallel processing environment, loading and computing a metric can be tricky because these processes are executed in parallel on separate subsets of the data. π Datasets supports distributed usage with a few additional arguments when you load a metric.
For example, imagine you are training and evaluating on eight parallel processes. Hereβs how you would load a metric in this distributed setting:
Define the total number of processes with the
num_processargument.Set the process
rankas an integer between zero andnum_process - 1.Load your metric with load_metric() with these arguments:
Copied
Once youβve loaded a metric for distributed usage, you can compute the metric as usual. Behind the scenes, Metric.compute() gathers all the predictions and references from the nodes, and computes the final metric.
In some instances, you may be simultaneously running multiple independent distributed evaluations on the same server and files. To avoid any conflicts, it is important to provide an experiment_id to distinguish the separate evaluations:
Copied
Last updated