Core ML Concepts: Trees, Training Loops, Metrics, Embeddings, Attention
Machine LearningModel answerLast updated
A five-part conceptual walkthrough covering ensembles of trees, supervised training, evaluation under imbalance, embeddings, and the basics of transformer attention.
Core ML Concepts: Trees, Training Loops, Metrics, Embeddings, Attention
Imagine a screening conversation for a junior ML engineer. You are not asked for proofs. You are asked to explain ideas accurately, give concrete examples, and discuss trade-offs. Plan on a few minutes per part, and bring up well-known pitfalls (overfitting, leakage, misleading metrics) before anyone asks.
Before answering, decide what you would clarify: the intended depth, whether the task is classification, regression or ranking, and whether the tree discussion is about a single tree, a forest, or boosted trees.
Part 1: Tree models
Describe how a single decision tree is built and used for prediction. Then contrast bagging (random forests) with boosting (gradient-boosted trees). Why do ensembles usually beat one tree, and when would you choose boosting over a forest?
Part 2: Training a supervised model
Walk through the training process. Cover the loss function, gradient descent, train/validation/test splits, regularization, and how you spot and reduce overfitting.
Part 3: Evaluating a model
How do you choose evaluation metrics? Explain why accuracy can mislead, and how class imbalance and the decision threshold change the conclusions you draw.
Part 4: Embeddings
What is an embedding and what does it represent? Why use embeddings instead of raw IDs or one-hot vectors? How are they learned, and where would you apply them?
Part 5: Transformer basics
What does self-attention compute? Why did transformers largely displace RNNs for sequence modeling? What role does positional encoding play?
Hints
Hint 1
For trees, tie each ensemble method to what it fixes: one reduces variance, the other reduces bias. Think about how correlation between trees affects the benefit of averaging.
Hint 2
For training and evaluation, separate three things: the data used to fit parameters, the data used to make decisions (hyperparameters, thresholds), and the data used only for the final estimate. Then ask what happens when these get mixed.
Hint 3
For embeddings and attention, focus on what geometry or weighting the model learns, and what is lost without it (similarity for IDs, word order for attention).
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Tree models
Single tree. A tree partitions feature space recursively. At each node it greedily searches features and thresholds for the split that most reduces impurity: Gini or entropy for classification, variance (MSE) for regression. Leaves predict the majority class or the mean target. Greedy means a chosen split is never revisited. A deep tree has low bias but high variance: small data changes can yield a very different tree.
Bagging (random forest). Train many deep trees independently, each on a bootstrap sample of rows and with a random feature subset considered at each split. Average or vote. For B trees with variance σ² and pairwise correlation ρ, the ensemble variance is ρσ² + (1−ρ)σ²/B. More trees shrink the second term, and feature subsampling lowers ρ, which shrinks the first. Bagging mainly attacks variance.
Boosting (GBDT). Train shallow trees sequentially. Each new tree fits the negative gradient of the loss with respect to the current predictions (residuals for MSE), scaled by a learning rate. Boosting mainly attacks bias.
Why ensembles win: a single tree is unstable and piecewise-constant; averaging decorrelated trees or summing many small corrections gives smoother, more accurate functions.
Choosing: use GBDT (XGBoost, LightGBM) for top accuracy on tabular data, custom or ranking losses, when you can tune and use early stopping. Use a random forest as a low-tuning, parallel, robust baseline, especially with noisy labels, since boosting can chase noise.
Part 2: Training
- Loss: defines "wrong": cross-entropy for classification, MSE/MAE for regression, pairwise or listwise for ranking. It should be differentiable and aligned with the product goal.
- Gradient descent: θ ← θ − η∇L(θ). Mini-batch SGD gives cheap, noisy gradients; Adam adapts per-parameter step sizes. The learning rate is the key knob: too high diverges, too low stalls.
- Splits: train fits parameters; validation tunes hyperparameters and early stopping; test is used once for the final estimate. Repeatedly consulting the test set turns it into a validation set and inflates results. Use time-based splits when data is temporal, and group-based splits when the same user or entity appears many times.
- Regularization: L2/L1 penalties, dropout, early stopping, data augmentation; for trees, max depth, min samples per leaf, subsampling, shrinkage.
- Detecting overfitting: training loss keeps falling while validation loss rises, or learning curves show a large gap. Remedies: more data, stronger regularization, a simpler model, early stopping.
Leakage (raise unprompted): fitting scalers or target encoders on the full dataset before splitting, using features only known after the outcome, or duplicates across splits. Validation looks great, production fails.
Part 3: Evaluation
Pick metrics from the cost of each error type, then check they match the product objective.
- Accuracy misleads under imbalance: with 99% negatives, always predicting negative scores 99% and catches nothing.
- Precision = TP/(TP+FP); recall = TP/(TP+FN); F1 is their harmonic mean.
- ROC-AUC and PR-AUC measure ranking quality independent of threshold. PR-AUC is more informative when positives are rare, because ROC-AUC can look good even with many false positives in absolute terms.
- Log-loss / calibration matter when probabilities feed downstream decisions.
- Threshold is a separate decision: the model outputs scores; choose the cutoff on validation data using costs. Fraud detection may favor recall, while a filter that could block legitimate email may favor precision. Re-tune if class priors shift.
- Other settings: ranking uses NDCG@k, Recall@k, MAP; regression uses RMSE (penalizes large errors) or MAE (robust to outliers).
- Offline is not online: offline metrics are proxies; confirm with an A/B test on the real objective.
Part 4: Embeddings
An embedding maps a discrete entity (word, user, item) to a dense vector, typically 16–512 dimensions, where distance or dot product reflects similarity.
Why not IDs or one-hot: raw IDs impose a false ordering (ID 5 is not between 4 and 6). One-hot vectors are huge, sparse, and mutually equidistant, so nothing generalizes between entities. Embeddings are compact, share statistical strength across similar entities, and support nearest-neighbor retrieval.
How learned: as a lookup table trained by backpropagation on an objective: predict context (word2vec), predict interactions via user·item dot products (matrix factorization, two-tower models), or contrastive learning that pulls positives together and pushes negatives apart.
Example: a two-tower recommender. The user tower encodes history, the item tower encodes content; item vectors are precomputed and indexed with approximate nearest neighbor search (FAISS, ScaNN) for candidate retrieval, then a GBDT or neural ranker reorders candidates.
Pitfalls: cold start for new entities (fall back to content features), popularity bias, and version drift between towers or between training and serving.
Part 5: Transformer basics
Self-attention: each token is projected into query, key, and value vectors (Q = XW_Q, K = XW_K, V = XW_V). Output = softmax(QKᵀ/√d_k)V, so each token becomes a weighted mix of all value vectors, with weights from query-key similarity. Dividing by √d_k keeps dot products from growing with dimension and saturating the softmax. Multi-head attention runs several such maps in parallel to capture different relations.
Why transformers replaced RNNs: (1) parallel computation across positions, versus sequential recurrence, so training scales on GPUs; (2) direct token-to-token paths, so long-range dependencies avoid vanishing gradients; (3) they scale well with data and compute. The cost is O(n²) time and memory in sequence length, which motivates efficient-attention variants.
Positional encoding: attention is permutation-invariant, so without position information "dog bites man" equals "man bites dog". Position is injected via sinusoidal or learned embeddings added to inputs, or via relative schemes such as rotary embeddings. Causal masking additionally prevents decoder tokens from attending to future tokens.
Common mistakes: claiming boosting reduces variance, tuning on the test set, reporting accuracy on imbalanced data, fitting preprocessing before the split, and forgetting that attention needs positional information.