Five ML Concepts: Gradients, Penalties, Dropout, Similarity, Encoding
Machine LearningModel answerLast updated
Answer five conceptual ML questions covering loss gradients, L1 vs L2 penalties, activations and dropout, cosine vs Euclidean similarity, and encoding high-cardinality categorical features.
Applied ML Concepts: Short-Answer Set
Imagine you are asked to talk through the following five topics. For each one, give the underlying mechanism rather than a bare definition, and back it with a short equation or a concrete example.
1. Loss gradients and training behavior
Show how the derivative of the squared-error loss leads to the weight-update rule in gradient descent. Then explain how switching from squared error to cross-entropy changes the way a classifier trains.
2. Taming overfitting with penalties
A model fits the training set very well but does poorly on held-out data. Contrast L1 and L2 penalties on the weights. When would you choose one over the other, and how do they differ geometrically in how they constrain the weight vector?
3. Hidden-layer building blocks
Why must hidden layers use non-linear activations such as ReLU rather than linear ones? Also describe how dropout works during training, why it regularizes, and how it behaves differently when the model is used for prediction.
4. Measuring closeness
When is cosine similarity a better choice than Euclidean distance, for example in recommenders or clustering? Give a small example in which Euclidean distance gives a misleading answer.
5. Encoding many-valued categories
You have a categorical column with thousands of distinct values, such as postal codes. What goes wrong with one-hot encoding here, and what other encodings could you use?
Hints
Hint 1
For topic 1, write the gradient with respect to the pre-activation of a sigmoid output under each loss and see which factor appears in one but cancels in the other.
Hint 2
For topic 2, compare the size of the penalty's pull on a weight as the weight gets small, and picture the shape of each constraint region (round vs. pointed).
Hint 3
For topics 4 and 5, build a tiny numeric example: two vectors pointing the same way with different lengths, and a category appearing only a handful of times. Think about leakage when you use the target to encode.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
The goal in each section is to explain what the technique does to the gradient, the loss surface, or the model's capacity.
1. Loss gradients and training behavior
Squared error to update rule. For a linear model ŷᵢ = wᵀxᵢ with L(w) = (1/n) Σ (yᵢ − ŷᵢ)²:
- Gradient: ∇L = −(2/n) Σ (yᵢ − ŷᵢ) xᵢ
- Update: w ← w − η∇L = w + η(2/n) Σ (yᵢ − ŷᵢ) xᵢ
Each weight moves in proportion to residual times input, so large errors give large steps and influential features get corrected more. The loss is convex in w for a linear model, so a suitable step size η converges to the global minimum.
Cross-entropy vs. squared error for classification. With p = σ(z), z = wᵀx:
- Squared error: ∂L/∂z = (p − y) · p(1 − p)
- Binary cross-entropy: ∂L/∂z = (p − y)
The p(1 − p) factor vanishes when the sigmoid saturates. A model that is confidently wrong (p ≈ 0.001 with y = 1) receives almost no gradient under squared error and learns slowly. Cross-entropy cancels the factor, so the gradient scales with the error. Further points: cross-entropy is the negative log-likelihood of a Bernoulli/categorical model, it punishes confident mistakes heavily (−log p → ∞), and squared error through a sigmoid is non-convex in w.
2. L1 vs. L2 penalties
- L1 (Lasso): adds λ‖w‖₁, subgradient λ·sign(w).
- L2 (Ridge): adds λ‖w‖₂², gradient 2λw.
Mechanism. L2's pull is proportional to the weight, so weights shrink smoothly toward zero but rarely reach it (weight decay). L1 pulls with constant magnitude, so any weight whose usefulness to the data loss is below λ is driven exactly to zero.
Geometry. In the constrained view (minimize loss subject to ‖w‖ ≤ t), the L2 region is a sphere and loss contours typically touch it at a point where no coordinate is zero. The L1 region is a diamond with corners on the axes, and elliptical contours tend to hit a corner first, producing sparse weights.
Choosing.
- Prefer L1 when you believe few features matter, want built-in feature selection, or need a compact interpretable model.
- Prefer L2 when many features contribute a little or are correlated. L1 picks one member of a correlated group somewhat arbitrarily and unstably, whereas L2 spreads weight across them.
- Elastic Net mixes both for sparsity with stability.
Bayesian view: L2 equals a Gaussian prior on weights, L1 a Laplace prior peaked at zero.
3. Activations and dropout
Why non-linearity. Stacked linear layers collapse: W₂(W₁x + b₁) + b₂ = W′x + b′. Without non-linear activations, depth adds no expressive power. With them, networks can approximate a very broad class of functions.
Why ReLU. It is cheap, does not saturate for positive inputs (gradient 1), and yields sparse activations. The caveat is "dying" units stuck in the negative region, which Leaky ReLU or GELU mitigate.
Dropout in training. Each unit is zeroed independently with probability p. This blocks co-adaptation, forcing redundant, robust features, and approximates training a large ensemble of weight-sharing sub-networks.
Training vs. inference.
- Training: random units dropped; with inverted dropout, survivors are scaled by 1/(1 − p) so expected activations are unchanged.
- Inference: dropout is off (e.g.
model.eval()), all units active, no extra scaling. In the original formulation, weights were instead scaled by (1 − p) at test time. - Forgetting to switch modes is a classic bug that produces noisy predictions.
4. Cosine similarity vs. Euclidean distance
Cosine, a·b / (‖a‖‖b‖), captures direction only; Euclidean distance is also affected by magnitude. Use cosine when magnitude is a nuisance: document length, a user's overall activity, embedding norms. It also works better in high-dimensional sparse spaces where Euclidean distances concentrate.
Example. Word counts over [ml, data, cooking]:
| Item | Vector |
|---|---|
| A | [1, 1, 0] |
| B (same content, 10× longer) | [10, 10, 0] |
| C (different topic) | [0, 1, 1] |
- A–B: Euclidean ≈ 12.7, cosine = 1.0
- A–C: Euclidean ≈ 1.41, cosine = 0.5
Euclidean says A is closer to C, which is wrong. The same happens with a heavy and a light user who share tastes.
Use Euclidean when magnitude carries meaning (physical coordinates, k-means on standardized features). For L2-normalized vectors, ‖a − b‖² = 2 − 2cos(a, b), so both rank neighbors identically.
5. High-cardinality categoricals
One-hot pitfalls.
- Thousands of sparse columns: memory and compute cost.
- Rare categories get noisy coefficients and overfit.
- Unseen categories at inference have no column.
- No notion of similarity: neighboring zip codes look as unrelated as distant ones.
- Tree models must make weak one-vs-rest splits.
Alternatives.
- Target (mean) encoding: replace each category with its target mean, smoothed toward the global mean: (nᵢȳᵢ + mȳ)/(nᵢ + m). Compute it out-of-fold, otherwise the target leaks into the feature and inflates validation scores.
- Frequency/count encoding: cheap and often informative.
- Feature hashing: fixed dimensionality, handles unseen values, at the cost of collisions.
- Learned embeddings: a dense vector per category trained with the model, capturing similarity. Best with enough data.
- Grouping and enrichment: collapse rare values into "other", or replace with hierarchical or geographic features (region, city, latitude/longitude, demographics).
Common mistakes
- Claiming L1 "always" beats L2 for feature selection, ignoring correlated features.
- Forgetting the inference-mode switch for dropout.
- Using target encoding on the full dataset, which leaks labels.
- Using cosine similarity when magnitude actually matters.