Evaluate It
Beyond one number.
One hundred percent sounds perfect. But our test messages look a lot like the training ones. A good engineer always asks. What happens with messages that are different?
- 100% sounds perfect
- Test data looks familiar
- What about different messages?
Messages it has never seen
The model was already trained, and saved, in a folder called intent model. Pipeline loads it for classification. We write four new messages. Messy text. A long sentence. A book that's not in our data. And a question that fits no intent at all. Run it. The first three are right. But look at the last one. Visiting the shop isn't one of our five intents. The model still picks one, stock, and it's seventy percent sure. A classifier always picks one of its labels.
from transformers import pipeline
classify = pipeline("text-classification", model="intent-model")
messages = ["hiya, has my copy of Dune shipped??",
"The book came with a coffee stain, I want my money back",
"do u have any Agatha Christie books",
"Is it possible to visit the shop on Sunday?"]
for msg, result in zip(messages, classify(messages)):
print(f"{result['label']:13} {result['score']:.0%} {msg}")order_status 57% hiya, has my copy of Dune shipped?? return 67% The book came with a coffee stain, I want my money back stock 80% do u have any Agatha Christie books stock 70% Is it possible to visit the shop on Sunday?
Also uses _setup.py
from train import trainer
trainer.train()
trainer.save_model("intent-model")Also uses prep.py
from datasets import load_dataset
from transformers import AutoTokenizer
INTENTS = ["order_status", "return", "price", "stock", "complaint"]
label2id = {name: i for i, name in enumerate(INTENTS)}
id2label = {i: name for i, name in enumerate(INTENTS)}
MODEL = "distilbert/distilbert-base-uncased"
tok = AutoTokenizer.from_pretrained(MODEL)
def prepare(row):
enc = tok(row["message"], truncation=True, max_length=32)
enc["label"] = label2id[row["intent"]]
return enc
data = load_dataset("json", data_files={"train": "tickets_train.jsonl",
"test": "tickets_test.jsonl"})
data = data.map(prepare, remove_columns=["message", "intent", "book"])Also uses train.py
import numpy as np
from transformers import (AutoModelForSequenceClassification, DataCollatorWithPadding,
Trainer, TrainingArguments)
from prep import tok, data, MODEL, label2id, id2label
model = AutoModelForSequenceClassification.from_pretrained(
MODEL, num_labels=5, id2label=id2label, label2id=label2id)
args = TrainingArguments(output_dir="intent-model", num_train_epochs=2,
per_device_train_batch_size=16, learning_rate=5e-5,
eval_strategy="epoch", logging_strategy="epoch",
save_strategy="no", report_to="none")
def accuracy(pred):
return {"accuracy": (np.argmax(pred.predictions, -1) == pred.label_ids).mean()}
trainer = Trainer(model=model, args=args, train_dataset=data["train"],
eval_dataset=data["test"], data_collator=DataCollatorWithPadding(tok),
compute_metrics=accuracy)Lessons from this test
So what did we learn? Test data should include hard, and unusual, cases. A high score on easy data can hide problems. And a classifier can't say I don't know, unless you give it an other label, with examples. We'll come back to good evaluation later in the course.
| key | value |
|---|---|
| Test hard cases | messy, long, unusual |
| Easy tests | hide problems |
| Unknown requests | add an 'other' label |
| Later | a whole section on evaluation |
Summary
Let's recap. Always test with messages unlike your training data. Scores are confidence, not truth. And a classifier always picks one of its labels. Next, overfitting, and how to spot it.
Key takeaways- Test unusual cases
- Score ≠ correct
- No 'I don't know'