Use Your Model
Scores, top choices, and doubt.
In a real app, one label isn't always enough. Sometimes a message fits two intents. Let's look at the model's top two choices, so our app can tell when the model is unsure.
- One label isn't always enough
- Some messages fit two intents
- Look at the top two
Top two choices
Top k equals two returns the two best labels for each message. Our messages are tricky on purpose. The first is about a double charge, and a refund. The second is about price, and the shop. Run it. For the first, the model says return, but complaint is in second place. For the second, it's torn between stock and price. Neither answer is clearly wrong. These messages really do mix two intents.
from transformers import pipeline
classify = pipeline("text-classification", model="intent-model", top_k=2)
messages = ["I was charged twice for Emma, please refund me",
"Is Circe cheaper if I buy it in the shop?"]
for msg, results in zip(messages, classify(messages)):
print(msg)
for r in results:
print(f" {r['label']:13} {r['score']:.0%}")I was charged twice for Emma, please refund me return 74% complaint 13% Is Circe cheaper if I buy it in the shop? stock 54% price 35%
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)Using scores in an app
Here's a simple pattern for real apps. If the top score is high, act on it automatically. If it's low, or two labels are close, send the message to a person. This way, the model handles the easy cases, and people handle the hard ones.
| key | value |
|---|---|
| High score | act automatically |
| Low or close | send to a person |
| Model | handles easy cases |
| People | handle the hard ones |
Summary
Let's recap. Top k shows more than one choice. Close scores mean the model is unsure. And a good app sends unsure cases to a person. That completes our classifier. Next, fine-tuning a language model, the big goal of this course.
Key takeaways- top_k=2
- Close scores = unsure
- Hand hard cases to people