NLP Evaluation Metrics
Choosing the right evaluation metric is critical for measuring model performance and guiding improvement. Different NLP tasks require different evaluation approaches.
Metric Selection Framework
| Task Type | Primary Metric | Secondary Metrics | When to Use |
|---|---|---|---|
| Classification | F1 / Accuracy | Precision, Recall, AUC | Balanced/imbalanced data |
| Named Entity Recognition | Token-level F1 | Span-level F1, Exact Match | Sequence labeling |
| Machine Translation | BLEU | METEOR, chrF, COMET | Translation quality |
| Summarization | ROUGE | BERTScore, SummaC | Content coverage |
| Question Answering | Exact Match | F1, BERTScore | Extractive/generative |
| Language Modeling | Perplexity | Bits per byte | Fluency assessment |
Classification Metrics
Confusion Matrix Metrics
from sklearn.metrics import (
accuracy_score, precision_score, recall_score, f1_score,
classification_report, confusion_matrix, roc_auc_score
)
import numpy as np
def comprehensive_classification_metrics(y_true, y_pred, y_prob=None, average="macro"):
"""Compute comprehensive classification metrics."""
metrics = {
"accuracy": accuracy_score(y_true, y_pred),
"precision": precision_score(y_true, y_pred, average=average, zero_division=0),
"recall": recall_score(y_true, y_pred, average=average, zero_division=0),
"f1": f1_score(y_true, y_pred, average=average, zero_division=0),
}
if y_prob is not None:
try:
metrics["auc_roc"] = roc_auc_score(y_true, y_prob, multi_class="ovr")
except ValueError:
metrics["auc_roc"] = None
# Per-class metrics
report = classification_report(y_true, y_pred, output_dict=True, zero_division=0)
metrics["per_class"] = report
# Confusion matrix
metrics["confusion_matrix"] = confusion_matrix(y_true, y_pred).tolist()
return metrics
# Example
y_true = [0, 1, 1, 0, 2, 1, 0, 2]
y_pred = [0, 1, 0, 0, 2, 2, 1, 2]
results = comprehensive_classification_metrics(y_true, y_pred)
print(f"Accuracy: {results['accuracy']:.4f}")
print(f"F1 (macro): {results['f1']:.4f}")
Macro vs Micro vs Weighted Averaging
| Strategy | Formula | Best For |
|---|---|---|
| Macro | Equal class importance | |
| Micro | Sample-level importance | |
| Weighted | Proportional to support |
Perplexity
Perplexity measures how well a language model predicts a sample.
import torch
import math
def compute_perplexity(model, tokenizer, text, max_length=512):
"""Compute perplexity of text using a language model."""
encodings = tokenizer(text, return_tensors="pt", max_length=max_length, truncation=True)
input_ids = encodings.input_ids.to(model.device)
with torch.no_grad():
outputs = model(input_ids, labels=input_ids)
neg_log_likelihood = outputs.loss
return math.exp(neg_log_likelihood.item())
def compute_dataset_perplexity(model, tokenizer, texts, max_length=512):
"""Compute average perplexity over a dataset."""
perplexities = []
for text in texts:
ppl = compute_perplexity(model, tokenizer, text, max_length)
perplexities.append(ppl)
return {
"mean_ppl": np.mean(perplexities),
"std_ppl": np.std(perplexities),
"median_ppl": np.median(perplexities),
"min_ppl": min(perplexities),
"max_ppl": max(perplexities),
}
BLEU Score
BLEU measures n-gram precision between generated and reference translations.
| BLEU Range | Quality | Typical Use |
|---|---|---|
| 0-10 | Poor | Random/baseline outputs |
| 10-20 | Below average | Weak models |
| 20-30 | Adequate | Production baselines |
| 30-40 | Good | Strong models |
| 40-50 | Excellent | Near-human quality |
| 50+ | Outstanding | Domain-specific tasks |
ROUGE Metrics
| Metric | Measures | Formula | Best For |
|---|---|---|---|
| ROUGE-1 | Unigram overlap | Unigram recall/precision | Content coverage |
| ROUGE-2 | Bigram overlap | Bigram recall/precision | Fluency |
| ROUGE-L | LCS-based | Longest common subsequence | Structure similarity |
BERTScore
BERTScore computes semantic similarity using contextual embeddings.
Metric Comparison
| Metric | Level | Semantic | Speed | Correlation with Human | Use Case |
|---|---|---|---|---|---|
| Accuracy | Sample | No | Fast | Moderate | Balanced classification |
| F1 | Sample | No | Fast | Moderate | Imbalanced classification |
| Perplexity | Token | Partial | Moderate | Low-Moderate | Language modeling |
| BLEU | N-gram | No | Fast | Moderate | Translation |
| ROUGE | N-gram | No | Fast | Moderate | Summarization |
| BERTScore | Embedding | Yes | Slow | High | Text generation |
| METEOR | Token | Partial | Moderate | Moderate-High | Translation |
| COMET | Embedding | Yes | Slow | Very High | Translation |
Error Analysis Metrics
def error_analysis(y_true, y_pred, texts, labels):
"""Detailed error analysis for classification."""
errors = []
for i, (true, pred, text) in enumerate(zip(y_true, y_pred, texts)):
if true != pred:
errors.append({
"index": i,
"text": text,
"true_label": labels[true],
"predicted_label": labels[pred],
})
# Confusion pairs
confusion_pairs = {}
for error in errors:
pair = (error["true_label"], error["predicted_label"])
confusion_pairs[pair] = confusion_pairs.get(pair, 0) + 1
# Sort by frequency
sorted_pairs = sorted(confusion_pairs.items(), key=lambda x: -x[1])
return {
"total_errors": len(errors),
"error_rate": len(errors) / len(y_true),
"top_confusion_pairs": sorted_pairs[:10],
"error_examples": errors[:20],
}
Best Practices
- Match metric to task - No single metric works for all NLP tasks
- Report multiple metrics - Avoid relying on a single number
- Consider class imbalance - Use macro-F1 or weighted metrics
- Include confidence intervals - Report means with standard deviations
- Validate with human evaluation - Automatic metrics are proxies, not ground truth
Key Takeaways
- F1 score is the standard metric for classification tasks with imbalanced classes
- Perplexity measures language model quality but correlates poorly with downstream task performance
- BLEU remains the standard for translation despite known limitations
- BERTScore captures semantic similarity better than surface-level metrics
- Always report multiple metrics and include statistical significance tests
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type â Always start by categorizing the problem
- Incorrect formula application â Verify the formula applies to your specific case
- Unit errors â Always check units are consistent throughout
- Sign errors â Pay careful attention to positive and negative values
- Rounding too early â Keep full precision until the final answer
- Forgetting constraints â Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic â Build on the foundation laid here
- Next Topic â See how this concept extends to more advanced material
- Practice Problems â Additional exercises with solutions
- Video Explanation â Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions