Load and Split a Labelled Dataset
A pretrained model learns a new task from examples: texts, each paired with the right answer, its label. Before any training can start, those examples have to be found, loaded, cut down to the classes the task needs, turned into token IDs, and divided into sets with separate jobs. How this is done decides what the model can learn and whether its scores can be trusted, so it is worth doing carefully and in a way that gives the same data on every run.
Datasets live on the Hub too
The Hugging Face Hub hosts datasets the same way it hosts models. Each dataset is a repository named by its owner and its name, such as cornell-movie-review-data/rotten_tomatoes, a collection of short movie reviews marked as negative or positive. The repository holds the data files (today usually in the Parquet format) and a dataset card: the page that says where the texts come from, how they were labelled, which splits and columns there are, and under which licence the data may be used.
Read the card before you use the data, for the same reason you read a model card. The licence is the part that decides whether you may use the data at all. A licence such as CC BY 4.0 allows almost any use as long as you credit the authors. Some cards give no licence: the card of the movie-review dataset above lists its licence as "unknown", which grants you nothing, so for anything beyond private study you would have to check the original source first.
The datasets library loads a dataset by its repository name with load_dataset. The first call downloads the files; every later call finds them in a local cache and reads them from disk.
- Hub repository owner/name
- Dataset card data, splits, licence
- First load downloads the files
- Local cache ~/.cache/huggingface
- Later loads read from disk
- Hub repository to Dataset card: read first
- Dataset card to First load
- First load to Local cache
- Local cache to Later loads
from datasets import load_dataset
raw = load_dataset("cornell-movie-review-data/rotten_tomatoes")The downloaded files go to ~/.cache/huggingface/hub, and the library writes its own ready-to-read copy (in the Arrow format) to ~/.cache/huggingface/datasets. Setting the environment variable HF_HOME moves both. A dataset repository can change after you first load it, like any repository; passing revision= with a commit hash to load_dataset pins the exact version, which the library's maintainers recommend when results must be reproducible.
True or false?
Running the same load_dataset call a second time downloads the files again.
False. The second call finds the files in the local cache and reuses them. Only an explicit download_mode="force_redownload" fetches them again.
A dataset card that lists no licence lets you use the data freely.
False. No licence means no permission has been granted. You would have to find the terms at the original source before using the data beyond private study.
Splits, columns and class labels
Printing what load_dataset returned shows how a dataset is organised. Without a split argument it returns a DatasetDict: a dictionary of named splits, each a Dataset of rows. The publishers decide which splits exist; this one ships three, while many datasets ship only train and test.
DatasetDict({
train: Dataset({
features: ['text', 'label'],
num_rows: 8530
})
validation: Dataset({
features: ['text', 'label'],
num_rows: 1066
})
test: Dataset({
features: ['text', 'label'],
num_rows: 1066
})
})Every row has the same columns, and every column has a type, which features lists. Here text is a string, and label is a ClassLabel: the type made for class labels. It stores each row's label as an integer, and it keeps the list of class names only once, in the column's type. The integer is the position of the name in that list, so 0 means neg and 1 means pos.
train = raw["train"]
print(train.features)
# {'text': Value('string'), 'label': ClassLabel(names=['neg', 'pos'])}
row = train[0] # one row, as a dict
print(row["label"]) # an integer, 0 or 1
labels = train.features["label"]
print(labels.int2str(1)) # 'pos'
print(labels.str2int("neg")) # 0| stored in each row | kept once in the type |
|---|---|
| 0 | neg |
| 1 | pos |
The integers are what a model needs: its classification head gives one score per class, and the label's integer says which score should be the highest. The names are what people need to read the results. Keeping both in one column type means the mapping between them travels with the data instead of living in a separate note.
True or false?
In a ClassLabel column, each row stores the class name as text.
False. Each row stores an integer. The names are kept once, in the column type, and int2str turns an integer back into its name.
raw["train"][0] returns one row as a dictionary of column names and values.
True. Indexing a Dataset with an integer gives one row as a dict, such as a text and its label integer.
Keep the rows you need, then tokenize them
A published dataset is rarely shaped exactly for your task. It may cover many more classes than you need, or contain rows you do not want. Two operations reshape it, and both return a new dataset instead of changing the old one.
filter keeps the rows for which a function returns True. To keep only some classes of a dataset with many, turn their names into their integers and keep the rows whose label is one of them:
labels = dataset.features["label"]
wanted = ["refund", "delivery", "password_reset"]
keep = {labels.str2int(name) for name in wanted}
kept = dataset.filter(lambda row: row["label"] in keep)Filtering only removes rows. The rows it keeps still carry their original integers, so if those three classes were numbered 4, 17 and 52 in the full dataset, they are still 4, 17 and 52 afterwards. A classification head with three outputs needs the labels 0, 1 and 2, so renumbering them, together with a new list of three names, is a separate step.
map applies one function to every row and adds or replaces columns with what it returns. Its most common use here is tokenization. By default the function gets one row at a time. With batched=True, it gets a batch of rows at once (1,000 by default), given as a dictionary of lists, so batch["text"] is a list of texts. A tokenizer handles a whole list in one call, which is much faster than one text at a time.
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased")
def tokenize(batch):
return tokenizer(batch["text"], truncation=True)
tokenized = kept.map(tokenize, batched=True)- All rows text, label
- filter fewer rows
- map, batched adds columns
- Tokenized rows text, label, token columns
- All rows to filter
- filter to map, batched
- map, batched to Tokenized rows
This tokenizer returns input_ids and attention_mask, plus token_type_ids, a list of zeros that would mark which of two joined texts each token belongs to and that DistilBERT does not use; map adds all three as new columns beside text and label. truncation=True cuts any text longer than the model's maximum length. The library also caches the result: it records a fingerprint of the data and of the function applied, so running the same map again on the same data reads the stored result instead of tokenizing everything again.
True or false?
After filter keeps three classes, their labels are renumbered 0, 1 and 2.
False. filter only removes rows. The kept rows keep their original integers, and renumbering them is a separate step.
With batched=True, the function given to map receives a list of texts under batch["text"].
True. A batched function receives a dictionary of lists, 1,000 rows by default, and returns a dictionary of lists of the same length.
Count the examples in each class
Before splitting or training, count how many examples each class has. A dataset is balanced when every class has about the same number of rows, and imbalanced when some classes have many more than others. Real data is often imbalanced: customers ask some questions far more often than others. Some datasets are imbalanced in training and balanced in testing, so each split is worth counting on its own.
from collections import Counter
counts = Counter(row["label"] for row in kept)
for label_id, n in counts.most_common():
print(labels.int2str(label_id), n)- refund 600
- delivery 250
- password_reset 100
- close_account 50
Uneven counts change what a model learns. Training lowers the loss over all examples, and in the set in the chart 600 of the 1,000 examples say "refund", so answering "refund" whenever a message is unclear pays off most of the time. The model sees many ways of asking for a refund and only 50 ways of asking to close an account, and it learns the small class less well.
Uneven counts also change how results must be read. A model that answers "refund" to every message, without reading it, is right on 600 of these 1,000 messages: 60%. A single overall score therefore says little until you know the class shares, and a model can score well overall while it almost never gets the small class right. Knowing the counts before training tells you which number a result has to be compared with and which classes to watch.
True or false?
On the set in the chart, a model that is right 60% of the time has shown it learned something.
False. Answering refund to every message, without reading any of them, is also right 60% of the time.
Three sets, split the same way every time
Labelled data is divided into three sets with separate jobs. The training set is what the model learns from. The validation set is what you measure on while you work, to compare settings and decide when to stop. The test set is kept closed until the very end and opened once, for the final result. It can only estimate how the model does on new text if nothing was chosen by looking at it: once you pick a setting because it scored better on the test set, that set has influenced the model, and its score becomes too optimistic.
When a dataset ships only train and test, the validation set is cut from the training data, and the published test split stays the test set.
- Published train split
- Published test split
- Training set the model learns from it
- Validation set measured while you work
- Test set opened once, at the end
- Published train split to Training set: most rows
- Published train split to Validation set: a seeded, stratified share
- Published test split to Test set: kept as it is
train_test_split cuts one dataset into two. It shuffles the rows and then takes the share given by test_size (a fraction such as 0.1, or a number of rows) as one part. It always names the two parts train and test, so the held-out part is renamed to validation when the three sets are put together:
from datasets import DatasetDict
parts = raw["train"].train_test_split(
test_size=0.1,
seed=42,
stratify_by_column="label",
)
splits = DatasetDict({
"train": parts["train"],
"validation": parts["test"],
"test": raw["test"],
})The seed makes the split repeat
The shuffle is random. Without a seed, the library draws fresh randomness from the operating system, so every run puts different rows into validation, and two runs can no longer be compared: a better score might come from an easier validation set rather than a better model. A fixed integer seed starts the random generator in the same state, so the same data gives the same split on every run. The value itself does not matter; keeping it the same does.
Stratification keeps every class's share
A plain random cut can by chance take too many rows of one class and too few of another, which matters most for small classes. A stratified split cuts each class separately, so every class keeps about the same share in both parts as in the whole. On the example set of 1,000 messages, a 10% validation set looks like this:
| Class | All rows | Stratified split | One plain random draw |
|---|---|---|---|
| refund | 600 | 60 | 55 |
| delivery | 250 | 25 | 31 |
| password_reset | 100 | 10 | 12 |
| close_account | 50 | 5 | 2 |
In the random draw, close_account has only 2 validation examples. One more or one fewer right answer would move its score by 50 points, and another random draw could even leave a small class out entirely. stratify_by_column needs a ClassLabel column and raises an error for any other type, and every class needs at least two rows so that it can appear on both sides.
True or false?
With the same data and the same seed, train_test_split puts the same rows in each part on every run.
True. The seed fixes the starting state of the random generator, so the shuffle, and therefore the split, repeats.
train_test_split returns a part named validation.
False. It always returns the keys train and test. The held-out part is renamed when the three sets are assembled.
Comparing two settings by their score on the test set keeps the final result honest.
False. Settings are compared on the validation set. A choice made by looking at the test set makes its final score too optimistic.