AI Hints
Home›Fine-Tuning LLMs Tutorial›Working with Datasets
Fine-Tuning LLMs · Lesson 26 of 120

map, filter, split

Preparing data.

⏱ 2 min read▶ Video at 42:20🎓 Free
Watch this lesson in the Fine-Tuning LLMs courseWatch on YouTube ↗Full Fine-Tuning LLMs course

Raw data is never quite ready. We need to add columns, remove bad rows, and set some examples aside for testing. Three methods do almost all of this work.

  • Raw data isn't ready
  • Add, remove, set aside
  • Three methods

Three methods

Map runs a function on every row, and can add or change columns. Filter keeps only the rows where a function returns true. And train test split cuts the data into two parts. One for training, and one for testing.

map()change every row
filter()keep some rows
train_test_split()set data aside for testing

All three in action

First, map adds a length column, the number of words in each message. Then filter keeps only messages longer than twelve words. Finally, train test split puts ten percent of the rows aside, as a test set. The seed makes the split the same every time. Run it. The new column is there. Eleven long messages. And the data is now split into four hundred and seventy four rows for training, and fifty three for testing.

app.pypython
from datasets import load_dataset

ds = load_dataset("json", data_files="tickets_train.jsonl", split="train")
ds = ds.map(lambda row: {"length": len(row["message"].split())})
print(ds.column_names)
long = ds.filter(lambda row: row["length"] > 12)
print("Long messages:", len(long))
print(long[0]["message"])
splits = ds.train_test_split(test_size=0.1, seed=42)
print(splits)
Output
['message', 'intent', 'book', 'length']
Long messages: 11
Good morning. How do I return my copy of The Hobbit? Please help.
DatasetDict({
    train: Dataset({
        features: ['message', 'intent', 'book', 'length'],
        num_rows: 474
    })
    test: Dataset({
        features: ['message', 'intent', 'book', 'length'],
        num_rows: 53
    })
})

Why we need a test set

Why set data aside? Because a model can simply memorise its training examples. To know if it really learned the task, we must test it on examples it has never seen. Never train on your test set. Otherwise, your results are too good to be true.

keyvalue
Training setthe model learns from it
Test setnever seen during training
Purposecheck real learning
Rulenever train on the test set

Summary

Let's recap. Map changes every row. Filter keeps some rows. And train test split sets data aside for testing. Always test on examples the model has never seen. Next, a closer look at our project data.

Key takeaways
  • map()
  • filter()
  • train_test_split()
Next up: Our Project Data — Riverside Books messages