Sub topic 4
Preparing and splitting the dataset
This chapter covers how to load a labeled text dataset, check it, split it into training, validation and test sets, and tokenize each split. It assumes you can read Python with dictionaries, know what training, validation and test sets are, and have seen the Hugging Face datasets and transformers libraries at least once. The previous chapter covered tokenization on its own. Here the tokenizer is applied to whole datasets.
Why the split matters more than the model
A fine-tuned transformer can fit a few thousand examples very closely. Your only protection against fooling yourself is a clean split. Each split has one job:
| Split | Used for | Touched how often |
|---|---|---|
| Train | Updating the model weights | Every step |
| Validation | Choosing epochs, learning rate, checkpoint | Every epoch, many runs |
| Test | One final report of expected quality | Once, at the end |
The validation set gets "used up" over time. Each time you pick a setting because it scored well on validation, a little information leaks from validation into your choices. The test set stays untouched so that its score is still an honest estimate.
The overall data flow
Loading and inspecting the data
The IMDB dataset ships with a train split of 25,000 reviews and a test split of 25,000 reviews. It has no validation split, so you create one. Before splitting, look at what you have.
from collections import Counter
from datasets import load_dataset
raw = load_dataset("imdb")
print(raw)
print(raw["train"].features)
print(Counter(raw["train"]["label"]))
print(raw["train"][0]["text"][:200])Check four things at this stage:
- Column names and types. The Trainer expects a label column named
label(orlabels). If your data uses another name, rename it withdataset.rename_column("sentiment", "label"). - Label values. They must be integers from 0 to
num_labels - 1. If labels are strings, convert them withClassLabel(shown below). - Label balance. The
Counteroutput tells you whether accuracy will be a meaningful metric. A later chapter covers imbalance in detail. - Text quality. Look for empty strings, duplicated rows and markup such as
<br />, which IMDB reviews contain.
Converting string labels
If your CSV has labels like "positive" and "negative", convert them to integers and keep the mapping in the dataset schema:
from datasets import Dataset, ClassLabel
data = Dataset.from_dict({
"text": ["great film", "dull and slow", "loved it", "awful"],
"label": ["positive", "negative", "positive", "negative"],
})
data = data.class_encode_column("label")
print(data.features["label"])
print(data.features["label"].names)class_encode_column turns the column into a ClassLabel feature. The names are sorted alphabetically, so negative becomes 0 and positive becomes 1. You can later reuse data.features["label"].names to build id2label for the model.
Removing bad rows and duplicates
Duplicates are the most common silent source of inflated scores. If the same review appears in both training and test data, the model is graded on something it has memorized. Filter empty rows and drop exact duplicates before splitting:
def clean(dataset):
dataset = dataset.filter(lambda ex: ex["text"] is not None and len(ex["text"].strip()) > 0)
seen = set()
keep = []
for i, text in enumerate(dataset["text"]):
if text not in seen:
seen.add(text)
keep.append(i)
return dataset.select(keep)
train_clean = clean(raw["train"])
print(len(raw["train"]), "->", len(train_clean))Deduplicating inside one split does not catch overlap between splits. To check for leakage between train and test, compare the text sets directly:
train_texts = set(train_clean["text"])
overlap = [t for t in raw["test"]["text"] if t in train_texts]
print("test examples that also appear in train:", len(overlap))If the overlap is not zero, remove those rows from the training data, not the test data. The test set should represent the data you expect to see in production.
Creating the validation split
train_test_split shuffles and divides a dataset. The version used in this tutorial holds out 10% of the training data:
from datasets import load_dataset
from transformers import AutoTokenizer
checkpoint = "distilbert-base-uncased"
raw = load_dataset("imdb")
# Hold out part of the training set for validation; keep the test set untouched.
split = raw["train"].train_test_split(test_size=0.1, seed=42)
train_ds, val_ds, test_ds = split["train"], split["test"], raw["test"]The result is a DatasetDict with keys train and test. Here the key test of split holds the validation data, so assign it to val_ds right away to avoid confusing it with the real test set.
Three details deserve attention:
- Seed.
seed=42makes the shuffle repeatable. Without it, each run gets a different validation set, and scores from two runs are not comparable. - Stratification. A plain random split can give a validation set whose label ratio differs from the training set. This matters most for small or imbalanced data. Pass
stratify_by_column="label"to keep ratios equal. That option requires the column to be aClassLabel, which is why the earlierclass_encode_columnstep is useful. - Size. Ten percent of 25,000 is 2,500 examples, which gives a stable estimate. With 500 examples in total, a 10% validation set has 50 rows, and one wrong prediction moves accuracy by two points. In that case use a larger fraction or cross-validation.
A stratified version looks like this:
split = raw["train"].train_test_split(
test_size=0.1, seed=42, stratify_by_column="label"
)
print(Counter(split["train"]["label"]), Counter(split["test"]["label"]))Grouped data
Random splitting assumes rows are independent. If several rows come from the same author, product or document, a random split puts siblings on both sides, and the model scores well by recognizing style or topic rather than the label. In that case split by group. A simple approach is to split the list of group IDs and then filter rows by membership:
import random
def group_split(dataset, group_column, val_fraction=0.1, seed=42):
groups = sorted(set(dataset[group_column]))
random.Random(seed).shuffle(groups)
n_val = max(1, int(len(groups) * val_fraction))
val_groups = set(groups[:n_val])
train = dataset.filter(lambda ex: ex[group_column] not in val_groups)
val = dataset.filter(lambda ex: ex[group_column] in val_groups)
return train, valTokenizing each split
Models consume token IDs, not strings. The map method applies a function to every split. With batched=True the function receives a dictionary of lists, which is much faster than processing one row at a time because the fast tokenizer works on batches in Rust.
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
def tokenize(batch):
return tokenizer(batch["text"], truncation=True, max_length=256)
train_ds = train_ds.map(tokenize, batched=True)
val_ds = val_ds.map(tokenize, batched=True)
test_ds = test_ds.map(tokenize, batched=True)Two choices here are deliberate.
Truncation without padding. truncation=True, max_length=256 cuts long reviews to 256 tokens. The function does not pad. Padding is left to DataCollatorWithPadding, which pads each batch to the length of its longest member. This is called dynamic padding. If you padded everything to 256 up front, a batch of short reviews would waste compute on padding tokens.
One tokenizer for all splits. The same tokenizer, with the same settings, must process train, validation and test data. Mixing settings changes the inputs the model sees at evaluation time compared with training.
After mapping, each row has the original text and label columns plus input_ids and attention_mask. The Trainer removes columns the model does not accept, such as text, automatically (remove_unused_columns=True by default). You can confirm what a row looks like:
print(train_ds.column_names)
print(len(train_ds[0]["input_ids"]))Choosing max_length
Truncation loses information. Check how many examples it affects before settling on a length:
import numpy as np
lengths = np.array([len(ids) for ids in val_ds["input_ids"]])
print("median:", np.median(lengths), "95th percentile:", np.percentile(lengths, 95))Because max_length=256 already truncated these lengths, none exceeds 256. To measure real length, tokenize a sample without truncation and count:
sample = raw["train"].shuffle(seed=0).select(range(1000))
full_lengths = np.array([len(tokenizer(t)["input_ids"]) for t in sample["text"]])
print("share longer than 256 tokens:", (full_lengths > 256).mean())If a large share is cut, consider a longer max_length, up to the model's limit of 512 for DistilBERT. Memory and time grow with sequence length, so raise it only if the tail of the text carries signal. For some tasks the beginning and end of a review carry most of the sentiment, and a head-plus-tail truncation scheme is worth trying.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `KeyError: 'label'` or loss not computed | Label column has another name | `rename_column(..., "label")` |
| `ValueError: Target ... out of bounds` | Labels are not in `0..num_labels-1` | Re-encode labels, check `num_labels` |
| `stratify_by_column` raises an error | Column is not a `ClassLabel` | Use `class_encode_column` first |
| Validation score is suspiciously high | Duplicates or group leakage across splits | Deduplicate, split by group |
| Tensor size mismatch when batching | Padded in `map` but collator not used, or no truncation | Truncate in `map`, pad in the collator |
| Out-of-memory on the first batch | `max_length` too large for the batch size | Lower `max_length` or batch size |
| Different scores between runs | Split not seeded | Set `seed` in `train_test_split` |
Keeping the work reproducible
Tokenizing a large dataset takes time. The datasets library caches map results on disk, so a repeated run with the same function and data is fast. Be aware of two behaviors. If you change the tokenizer or the function, the cache is invalidated and the data is processed again. If you want to keep the prepared data for later, save it:
from datasets import DatasetDict
prepared = DatasetDict({"train": train_ds, "validation": val_ds, "test": test_ds})
prepared.save_to_disk("imdb-tokenized")Load it later with datasets.load_from_disk("imdb-tokenized"). Record the checkpoint name, max_length and split seed alongside it. A tokenized dataset is only valid for the tokenizer that produced it.
What you have now
You hold three tokenized splits: train_ds for fitting, val_ds for model selection, and test_ds for the final report. They are free of empty rows, checked for overlap, and share one tokenizer configuration. The next chapters define the metrics and pass these splits to the Trainer.
Exercise
You have 4,000 customer emails labeled as "urgent" (about 8%) or "normal" (about 92%). Several emails come from the same customer. Describe how you would build train, validation and test splits, and name two problems a plain train_test_split(test_size=0.1) could cause here.
Show answer
First deduplicate and drop empty emails. Then split by customer ID so that no customer appears in more than one split, and check that the "urgent" share is close to 8% in each split (stratify where the tooling allows it, or adjust the group assignment). Keep a test set aside that is used once at the end. A plain random split could (1) put emails from the same customer in both train and validation, so the model is rewarded for recognizing the customer's style, which inflates scores, and (2) produce a validation set whose urgent share drifts away from 8%. With only about 400 urgent examples, a 10% validation set holds roughly 40, so a few examples change the metrics noticeably.
Exercise
A colleague pads every example to 512 tokens inside the map function and also passes DataCollatorWithPadding to the Trainer. Training is slow, though the average review is about 230 tokens. What is wrong, and what do you change?
Show answer
Padding in map makes every sequence 512 tokens long, so the collator has nothing left to do and every batch computes over 512 positions, mostly padding. Remove padding from the tokenizer call, keep truncation=True with a suitable max_length, and let DataCollatorWithPadding pad each batch to its longest example. Batches of shorter reviews then use fewer positions, which reduces time and memory.