ML Fundamentals: Calibration, Features, Tokenization, Optimizers
Machine LearningModel answerLast updated
Demonstrate working knowledge of probability calibration methods and metrics, feature selection strategies including neural approaches, subword tokenizer variants, and Adam optimizer mechanics.
You're in a technical ML interview. The interviewer wants to assess your practical understanding of core ML concepts. Answer the following questions with concrete explanations and examples:
Question 1: Probability Calibration
- When does a production model require calibrated probabilities versus just ranked scores?
- Describe two calibration techniques and when each is appropriate
- What metrics would you use to verify that calibration is working?
Question 2: Feature Selection
- Why would you invest time in feature selection for a production model?
- Compare filter, wrapper, and embedded selection approaches
- How can neural networks be used for feature selection?
Question 3: Tokenization
- What problem do tokenizers solve in NLP systems?
- Compare BPE, WordPiece, and Unigram tokenizers
- What practical considerations affect tokenizer choice?
Question 4: Adam Optimizer
- Explain what statistics Adam tracks during training and why
- When might Adam underperform or require careful tuning?
Your answers should be practical and grounded in real-world use cases.
Hints
Hint 1
For calibration, consider scenarios where the actual probability value matters, not just relative ordering
Hint 2
Feature selection isn't just about accuracy—think about operational costs and model maintenance
Hint 3
Tokenizer choice affects not just model quality but also inference cost and multilingual support
Hint 4
Adam's adaptive learning rates solve some problems but can create others in specific training scenarios
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: ML Fundamentals
Strong candidates structure each answer around: the core concept, when it matters in practice, how to implement it, and how to validate the results.
1) Probability Calibration
When calibration is required
A model is well-calibrated when predicted probabilities match observed frequencies—if you predict 40% probability across many examples, roughly 40% should be positive. Calibration becomes critical when:
- Probabilistic decision-making: In ad bidding systems, you multiply
pCTR × bidto compute auction values. If your CTR predictions are systematically 2x too high, you'll overpay for every impression. - Composition of multiple models: When chaining predictions like
P(click) × P(convert | click), miscalibrated inputs compound errors. - Threshold-based systems: If you set a fixed threshold (e.g., fraud score > 0.7), that threshold needs to mean the same thing as your model evolves.
- Training data adjustments: Negative downsampling and class reweighting systematically distort predicted probabilities.
If you're only ranking (recommendation feeds, search results) and care about AUC or precision@k, calibration doesn't affect ordering and may not matter.
Calibration methods
Always calibrate on a separate held-out set, not training data:
Platt scaling: Fit a logistic regression on the model's logits: σ(a·z + b). This works well when the miscalibration follows a sigmoid pattern and you have limited calibration data.
Isotonic regression: Fit a monotonic piecewise-constant function. This is flexible and works with abundant data but can overfit and create probability ties.
Temperature scaling: For neural networks, divide logits by a learned temperature T before softmax. This preserves the argmax while adjusting confidence. Common in image classification.
Post-processing for downsampling: If you kept negatives at rate w, correct predictions with:
p_true = p_pred / (p_pred + (1 - p_pred) / w)
from sklearn.isotonic import IsotonicRegression
from sklearn.linear_model import LogisticRegression
# Fit on validation set
iso_calibrator = IsotonicRegression(out_of_bounds='clip')
iso_calibrator.fit(val_scores, val_labels)
# Platt scaling on logits
logits = np.log(val_scores / (1 - val_scores + 1e-10))
platt = LogisticRegression()
platt.fit(logits.reshape(-1, 1), val_labels)
Evaluation metrics
- Reliability diagrams: Bin predictions by score, plot mean predicted probability vs. observed frequency. Perfect calibration lies on the diagonal.
- Expected Calibration Error (ECE): Weight each bin's error by its size:
Σ (n_bin / n_total) × |predicted_mean - actual_rate|. Report bin counts since binning strategy affects results. - Brier score and log loss: These proper scoring rules measure both calibration and discrimination.
- Stratified analysis: Check calibration separately by segment (geography, device type, user cohort). Global calibration can hide 30%+ errors in specific slices.
2) Feature Selection
Motivation
Beyond improving generalization, feature selection has operational benefits:
- Reduce serving latency and cost: Fewer features mean faster inference and simpler data pipelines.
- Minimize maintenance burden: Every feature is a dependency that can break, drift, or become stale.
- Prevent overfitting: Especially important when feature count approaches or exceeds sample count.
- Identify and remove leakage: Features that won't be available at serving time or encode the target indirectly.
- Enable interpretability: Simpler models are easier to debug and explain.
Three approaches
Filter methods (model-agnostic, computationally cheap):
- Variance threshold, correlation with target, mutual information, chi-square tests
- Remove highly correlated pairs (|correlation| > 0.95)
- Weakness: miss feature interactions
Wrapper methods (search-based):
- Forward selection, backward elimination, recursive feature elimination (RFE)
- Accurate but expensive—requires training O(n_features) models
- Best used after filtering to a manageable candidate set
Embedded methods (built into training):
- L1 regularization (Lasso) drives coefficients to exactly zero
- Tree-based feature importance from gain/split counts (biased toward high-cardinality features)
- Permutation importance: shuffle one feature and measure validation metric drop (more reliable than tree gain)
Practical workflow: Use embedded importance or permutation importance to shortlist candidates. Validate by ablation testing—retrain without the feature and measure offline metrics. Ideally run A/B tests before removing features from production.
Neural network approaches
-
Input-layer sparsity: Apply group L1/L2 penalty to all weights connected to each input feature. When the penalty drives the group norm to zero, that feature can be pruned.
-
Learnable gating: Multiply each input by a learnable scalar gate
g_j ∈ [0, 1]with sparsity penalty. Use Concrete/Hard-Concrete distributions to make discrete gates differentiable. Features whose gates collapse near zero can be dropped. -
Gradient-based attribution: Compute integrated gradients, gradient×input, or SHAP values across validation examples. Features with consistently low attribution scores are candidates for removal.
-
Permutation at inference: Shuffle or mask individual features during validation (no retraining needed) and measure metric degradation. Cheap and effective.
-
Embedding analysis: In models like DeepFM for CTR prediction, inspect embedding norms or prune entire feature fields whose embeddings contribute minimally.
3) Tokenizers
Purpose
Tokenizers convert raw text into sequences of integer IDs that models can process. The challenge: word-level tokenizers create enormous vocabularies and can't handle unseen words, while character-level tokenizers produce impractically long sequences. Subword tokenization solves both problems.
Three main types
Byte-Pair Encoding (BPE):
- Start with individual characters or bytes
- Iteratively merge the most frequent adjacent pair
- Used by GPT-2, GPT-3, LLaMA
- Byte-level BPE guarantees no unknown tokens since any text decomposes to bytes
WordPiece:
- Similar to BPE but selects merges that maximize training likelihood:
freq(AB) / (freq(A) × freq(B)) - Marks subword continuations with
##prefix - Used by BERT:
"playing" → play ##ing
Unigram Language Model:
- Starts with large vocabulary, iteratively removes tokens that least harm likelihood
- Enables probabilistic segmentation—can sample different splits during training (subword regularization)
- SentencePiece implementation treats spaces as special characters (
▁), removing the need for language-specific preprocessing - Used by T5, mT5, XLNet
Practical considerations
Vocabulary size vs sequence length: Larger vocabularies (100k–250k) create shorter sequences (cheaper self-attention, more fits in context) but increase embedding table size and create rarer tokens. Typical range: 30k–50k for domain-specific models, 100k+ for large multilingual models.
Multilingual efficiency: Underrepresented languages often require 3–5× more tokens per word, increasing cost and reducing effective context length. This creates fairness issues.
Specialized content: Numbers, code, and formatting require careful handling. Poor digit tokenization hurts arithmetic reasoning. Code tokenizers need whitespace preservation.
Normalization tradeoffs: Lowercasing, Unicode normalization (NFKC), and accent removal reduce vocabulary size but lose information. "Apple" vs "apple" might matter.
Transfer learning constraint: Pretrained models require their exact original tokenizer. Custom tokenizers (medical terminology, legal text) require full model retraining or embedding matrix resizing.
4) Adam Optimizer
Core mechanism
Adam maintains two exponential moving averages for each parameter:
First moment (momentum): m_t = β₁ · m_{t-1} + (1 - β₁) · g_t
- Smooths gradient direction
- Helps navigate noisy gradients and escape shallow local minima
- Typical
β₁ = 0.9
Second moment (adaptive learning rates): v_t = β₂ · v_{t-1} + (1 - β₂) · g_t²
- Tracks gradient variance per parameter
- Parameters with consistently large gradients get smaller effective learning rates
- Parameters with small gradients get larger effective learning rates
- Typical
β₂ = 0.999
Update rule after bias correction:
θ_t = θ_{t-1} - α · m̂_t / (√v̂_t + ε)
This adapts learning rates per parameter, making Adam less sensitive to learning rate choice than SGD and effective for sparse gradients.
When Adam struggles
Generalization gap: Adam can converge faster but sometimes generalizes worse than SGD with momentum on vision tasks. The adaptive learning rates may move too aggressively and miss wider minima.
Learning rate warmup requirement: Adam needs careful learning rate warmup on large models (transformers) to prevent early instability from large adaptive steps with insufficient statistics.
Weight decay interaction: Standard weight decay doesn't work correctly with Adam's adaptive rates. Use AdamW (decoupled weight decay) instead.
Non-convex landscapes: The second moment averaging can get stuck if early gradients are very different from later ones. Restarting or reducing β₂ (to 0.99) can help.
Hyperparameter sensitivity: While less sensitive than SGD to base learning rate, Adam still requires tuning β₁, β₂, and ε for some problems, particularly in reinforcement learning.
Memory cost: Maintaining two sets of statistics doubles memory overhead compared to SGD, which matters for very large models.
Common fixes: switch to AdamW, use learning rate scheduling (cosine decay with warmup), try reducing β₂ if training is unstable, or fall back to SGD with momentum for tasks where generalization matters more than convergence speed.