When using Hugging Face models, the key metrics depend on the task. For text classification, accuracy is common because it shows how often the model predicts the right label. For tasks like question answering or translation, metrics like F1 score or BLEU are important because they measure quality beyond exact matches. Choosing the right metric helps you know if the model is truly learning and useful.
Hugging Face integration basics in PyTorch - Model Metrics & Evaluation
Actual \ Predicted | Positive | Negative
-------------------|----------|---------
Positive | 40 | 10
Negative | 5 | 45
This matrix shows 40 true positives (TP), 45 true negatives (TN), 5 false negatives (FN), and 10 false positives (FP). From this, we calculate precision, recall, and accuracy to understand model performance.
Imagine a spam detector using a Hugging Face model. If it marks too many emails as spam (high recall), it might block good emails (low precision). If it only marks very sure spam (high precision), some spam gets through (low recall). Depending on your goal, you adjust the model or threshold to balance these. For example, in medical text classification, missing a disease mention (low recall) is worse than a few false alarms.
For Hugging Face text classification models:
- Good: Accuracy above 85%, Precision and Recall above 80%, F1 score balanced and high.
- Bad: Accuracy near random chance (e.g., 50% for two classes), Precision or Recall very low (below 50%), or large difference between Precision and Recall indicating imbalance.
Good metrics mean the model predicts well and is reliable for your task.
- Accuracy paradox: High accuracy can be misleading if classes are imbalanced. For example, 90% accuracy if 90% data is one class but model ignores minority class.
- Data leakage: If test data leaks into training, metrics look unrealistically good.
- Overfitting: Very high training accuracy but low test accuracy means model memorizes instead of learning.
- Ignoring task-specific metrics: Using accuracy for tasks like translation where BLEU or ROUGE are better.
Your Hugging Face text classification model has 98% accuracy but only 12% recall on the positive class (e.g., fraud). Is it good for production? Why or why not?
Answer: No, it is not good. The low recall means the model misses most positive cases, which is critical in fraud detection. Even with high accuracy, the model fails to catch fraud, making it unreliable for production.
Practice
AutoTokenizer class in Hugging Face integration with PyTorch?Solution
Step 1: Understand the role of tokenization
Tokenization breaks down raw text into smaller pieces called tokens, which models use as input.Step 2: Identify what AutoTokenizer does
AutoTokenizer automatically loads the correct tokenizer for a given pretrained model to convert text into tokens.Final Answer:
To convert raw text into tokens that the model can understand -> Option BQuick Check:
AutoTokenizer = text to tokens [OK]
- Confusing tokenizer with model training
- Thinking tokenizer saves model weights
- Assuming tokenizer visualizes outputs
Solution
Step 1: Recall the correct method to load pretrained models
Hugging Face uses thefrom_pretrainedmethod to load pretrained weights and configuration.Step 2: Match the correct syntax
The correct syntax isAutoModel.from_pretrained('model_name').Final Answer:
model = AutoModel.from_pretrained('bert-base-uncased') -> Option AQuick Check:
Load model with from_pretrained() [OK]
- Using .load() instead of .from_pretrained()
- Calling AutoModel like a function
- Using non-existent .pretrained() method
outputs.last_hidden_state?
from transformers import AutoTokenizer, AutoModel
import torch
tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
model = AutoModel.from_pretrained('bert-base-uncased')
inputs = tokenizer('Hello world!', return_tensors='pt')
outputs = model(**inputs)
Solution
Step 1: Understand the tokenizer output
The tokenizer returns input IDs with shape [batch_size, sequence_length]. Here batch_size=1 and sequence_length=5 (tokens: [CLS], 'hello', 'world', '!', [SEP]).Step 2: Understand model output shape
The model outputs last_hidden_state with shape [batch_size, sequence_length, hidden_size]. For BERT base, hidden_size=768.Final Answer:
[1, 5, 768] -> Option CQuick Check:
Output shape = [batch, tokens, features] = [1, 5, 768] [OK]
- Confusing sequence length with batch size
- Ignoring hidden size dimension
- Assuming output shape is 2D instead of 3D
from transformers import AutoTokenizer, AutoModel
tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
model = AutoModel.from_pretrained('bert-base-uncased')
inputs = tokenizer('Test input', return_tensors='pt')
outputs = model(inputs)
print(outputs)Solution
Step 1: Check how model is called
The model expects keyword arguments, so inputs must be unpacked with ** to pass input_ids and attention_mask correctly.Step 2: Identify the fix
Changemodel(inputs)tomodel(**inputs)to avoid errors.Final Answer:
Model should be called with unpacked inputs: model(**inputs) -> Option DQuick Check:
Use **inputs when calling model [OK]
- Passing inputs as a single dict argument
- Confusing PyTorch and TensorFlow tensor types
- Thinking AutoModel can't load BERT
Solution
Step 1: Understand model output for classification
Models output raw scores called logits for each class, which are not probabilities.Step 2: Convert logits to probabilities
Applyingtorch.softmaxon logits converts them into probabilities summing to 1.Final Answer:
Apply torch.softmax on the model's logits output -> Option AQuick Check:
Softmax = logits to probabilities [OK]
- Using argmax on inputs instead of outputs
- Confusing model.eval() with probability conversion
- Normalizing inputs instead of outputs
Ready to prove it?
Pass the test and this pattern moves unknown
