Sub topic 4
Preparing and Splitting the Dataset
Assume you know Python functions and dictionaries, understand training, validation, and test sets, and have basic familiarity with Hugging Face Datasets. This chapter prepares labeled text for fine-tuning. It does not train the model yet.
A dataset for text classification usually has one text column and one label column. A label is the target category the model should predict. For example, an IMDb review can have the label 0 for negative or 1 for positive.
Why split the data?
A single dataset is divided into separate subsets so that each subset answers a different question:
| Subset | Purpose | Used to update model weights? |
|---|---|---|
| Training set | Learn patterns from examples | Yes |
| Validation set | Choose settings and checkpoints | No |
| Test set | Estimate final performance | No |
The test set must remain untouched until the end. If you repeatedly inspect test results while changing the model, the test set indirectly influences your decisions. The final score then becomes optimistic.
A validation set is usually carved out of the original training set. The original test set stays separate.
Loading and splitting the data
The Hugging Face datasets library provides dataset loading and splitting methods. IMDb is already divided into training and test portions, with 25,000 examples in each portion.
from datasets import load_dataset
raw = load_dataset("imdb")
split = raw["train"].train_test_split(test_size=0.1, seed=42)
train_ds = split["train"]
val_ds = split["test"]
test_ds = raw["test"]
print(train_ds)
print(val_ds)
print(test_ds)Here, test_size=0.1 places 10 percent of the original training data into the validation set. The name split["test"] refers to the result of this splitting operation. It is a validation set in our workflow, not the final test set.
The seed makes the random split repeatable. Without it, each run may select different examples, making comparisons harder.
Checking the data
Inspect the column names, an example, and the label distribution before tokenization.
print(train_ds.column_names)
print(train_ds[0])
counts = {}
for label in train_ds["label"]:
counts[label] = counts.get(label, 0) + 1
print(counts)The text should be present and the labels should be valid integers. For a binary task, labels should normally be 0 and 1. Check for missing text, unexpected labels, and duplicate or near-duplicate documents.
If examples from the same source appear in both training and validation data, the validation score may be misleading. For instance, several messages from one user or several pages from one document should usually stay in the same split. This is called group leakage.
Tokenizing each split
A tokenizer converts text into token IDs that the transformer can process. Apply the same tokenizer and settings to every split. Truncation limits long texts to a fixed maximum length. Padding is postponed until batches are created so that each batch can use only the padding it needs.
from transformers import AutoTokenizer
checkpoint = "distilbert-base-uncased"
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)
print(train_ds[0].keys())The batched=True option passes several texts to the function at once. This is faster than processing one row at a time. The tokenizer adds fields such as input_ids and attention_mask. The attention mask tells the model which positions contain real tokens.
Dynamic padding will be configured later with a data collator. Padding all examples to the maximum length before batching wastes memory.
Exercise
Why should the original test set remain untouched while you tune the model?
Show answer
Using it during tuning lets its examples influence decisions, so its final score no longer represents an independent estimate.