AI Hints
Home›Fine-Tuning LLMs Tutorial›Data: Balance, Safety and Practice
Fine-Tuning LLMs · Lesson 79 of 120

Label Balance

Count every class.

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

Imagine ninety percent of our training tickets were complaints. The model would learn a lazy trick. When in doubt, say complaint. So before training, we count every label.

  • Ninety percent complaints?
  • The model learns a lazy trick
  • Count every label

What is balance?

A dataset is balanced when every class has a similar number of examples. A class is one possible label, like stock, or return. When one class is rare, the model sees it too few times to learn it. And it may hardly ever predict it.

keyvalue
Classone possible label
Balancedsimilar counts per class
Rare classlearned badly
Resultrarely predicted

Counting labels

Here's how to count. Counter, from Python's collections module, counts how often each value appears. We count the intents, and the books. Then we print a little bar for each intent. Run it. Our five intents each have just over a hundred examples. Nicely balanced. And even the rarest book appears sixty times.

app.pypython
from collections import Counter
from datasets import load_dataset

data = load_dataset("json", data_files="tickets_train.jsonl")["train"]
intents = Counter(data["intent"])
books = Counter(data["book"])
for name, n in intents.most_common():
    print(f"{name:13} {n:4}  {'#' * (n // 5)}")
print()
print("Books:", len(books), " smallest:", books.most_common()[-1])
Output
stock          108  #####################
price          107  #####################
order_status   105  #####################
return         104  ####################
complaint      103  ####################

Books: 8  smallest: ('Dune', 60)

Fixing imbalance

If your data is not balanced, you have three options. Collect, or generate, more examples of the rare classes. Remove some examples of the common classes. Or repeat the rare examples, which is called oversampling. Collecting more real data is usually best.

keyvalue
Bestcollect more rare examples
Optionremove some common ones
Oversamplerepeat rare examples
Alwayscount again afterwards

Summary

Let's recap. A balanced dataset has similar counts for every class. Rare classes are learned badly. Counter shows the counts in one line. And collecting more rare examples is the best fix. Next, bias and safety.

Key takeaways
  • Count every class
  • Counter
  • Collect more rare examples
Next up: Bias and Safety — what the model should not learn