Model Fit, CNNs, RNNs, Transformers and Ensembles: ML Fundamentals
Machine LearningModel answerLast updated
A broad machine-learning fundamentals question covering model fit diagnostics, augmentation, CNNs, RNNs, transformer encoders, dropout and ensemble methods.
You are in a screening conversation on core machine-learning concepts, with a lean toward computer vision. Answer each part concisely, as you would aloud in a minute or two.
- Model fit: How do underfitting and overfitting differ? How would you recognize each one in practice, and what would you do to fix it?
- Data augmentation: What is it, and why does it help? Give concrete examples for images, including cases where an augmentation would be harmful.
- CNNs: What are the main building blocks of a convolutional network, and what is each one for?
- RNNs: How does a recurrent network consume a sequence, and what goes wrong when training it?
- Transformer encoder: Explain the roles of positional embeddings, self-attention, residual connections and the feed-forward sublayer.
- Dropout: What does it do during training and at inference, and why does it improve generalization?
- Bagging vs. boosting: Compare them in terms of bias, variance and how the algorithms actually behave.
A strong answer ties each technique back to the bias-variance trade-off, gives a mechanism rather than just a definition, and mentions a practical diagnostic or pitfall.
Hints
Hint 1
Start from the decomposition of expected error into bias squared, variance and irreducible noise, and use it as the thread connecting most of the parts.
Hint 2
For diagnostics, think about what training versus validation curves look like, and how they change as you add data or model capacity.
Hint 3
For the architecture questions, say what problem each component solves (parameter sharing, order information, gradient flow, per-token nonlinearity) before describing the mechanics.
Hint 4
For bagging versus boosting, contrast how the base learners are trained (independent and parallel versus sequential and error-focused) and which error term each mainly reduces.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing
This is a breadth question. For each part, give a definition, the mechanism, and one practical detail. The common thread is the bias-variance trade-off: expected test error = bias² + variance + irreducible noise.
1. Underfitting vs. overfitting
- Underfitting (high bias): the model is too simple or too under-trained to capture the signal. Training error is high and validation error is similar. Example: a linear model on a quadratic relationship.
- Overfitting (high variance): the model fits noise in the training set. Training error is low but validation error is much higher. Example: a deep unpruned decision tree.
Diagnosis
- Compare training and validation metrics, ideally with k-fold cross-validation.
- Learning curves (error vs. training-set size): both curves plateau high means underfitting, and more data will not help. A large gap that shrinks with more data means overfitting, and more data will help.
- Validation curves (error vs. complexity or epochs): validation loss falls, then rises past the optimum.
Fixes for underfitting: add capacity (layers, features, polynomial terms), train longer, tune the learning rate, reduce regularization, engineer better features.
Fixes for overfitting: more data or augmentation, L2/L1 regularization, dropout, early stopping, pruning or fewer parameters, bagging, feature selection, label smoothing.
Common mistake: adding regularization to a model that is actually underfitting, or collecting more data when the learning curves show a bias problem.
2. Data augmentation
Apply label-preserving transformations to training examples. This enlarges the effective dataset and encodes invariances you believe the task has, which reduces variance without new labels. Apply it at training time only (test-time augmentation is a separate, optional technique).
Image examples
- Geometric: random crop and resize, horizontal flip, rotation, scale, translation.
- Photometric: brightness, contrast, hue jitter, blur, noise.
- Occlusion: Cutout, random erasing.
- Mixing: Mixup (blend images and labels), CutMix (paste a patch, mix labels by area).
- Learned policies: AutoAugment, RandAugment.
Pitfalls: the transformation must preserve the label. Vertical flips corrupt "6 vs. 9" and most street scenes. In detection and segmentation, boxes and masks must be transformed together with the image.
3. Convolutional networks
A CNN learns hierarchical spatial features with far fewer parameters than a fully connected network, thanks to local connectivity, weight sharing and translation equivariance.
- Convolution layers: learned k×k filters slid across the input (with stride and padding) produce feature maps. Early layers find edges and textures, deeper ones parts and objects, and the receptive field grows with depth.
- Nonlinearity (ReLU): lets the stack represent non-linear functions.
- Pooling or strided convolution: downsamples, cuts computation, adds local invariance.
- Normalization (batch norm): stabilizes and speeds up training.
- Head: global average pooling, then fully connected layer and softmax.
- Residual connections: make very deep networks trainable.
4. RNNs
An RNN processes tokens one at a time, carrying a hidden state:
h_t = tanh(W_x x_t + W_h h_{t-1} + b)
Weights are shared across time, so variable-length input is fine, and h_t is a compressed memory of the prefix. Training uses backpropagation through time. Repeated multiplication by W_h causes vanishing or exploding gradients: clip gradients for the latter, use gated cells (LSTM, GRU) for the former. LSTMs add input/forget/output gates and an additive cell state that preserves long-range information.
Limitations: sequential computation cannot be parallelized across time, and very long dependencies stay hard. This motivated transformers.
5. Transformer encoder
- Positional embeddings: self-attention is permutation-invariant, so order must be injected. Use sinusoidal or learned absolute embeddings added to token embeddings, or relative/rotary schemes inside attention.
- Self-attention: project tokens to Q, K, V and compute softmax(QKᵀ/√d_k)V. Each token aggregates information from all others, with O(1) path length between positions and full parallelism, at O(n²) cost in sequence length. The √d_k scaling prevents softmax saturation. Multiple heads capture different relations in different subspaces.
- Residual connections (with LayerNorm): each sublayer computes x + Sublayer(x). The identity path carries gradients, so deep stacks train, and each layer learns a refinement.
- Feed-forward network: a per-token MLP, typically d → 4d → d with GELU/ReLU. Attention mixes information across tokens, while the FFN transforms features within each token and supplies much of the nonlinearity and parameter count.
6. Dropout
During training, each activation is zeroed with probability p, and with inverted dropout the survivors are scaled by 1/(1−p). At inference, dropout is off and no rescaling is needed.
Why it works
- Prevents co-adaptation, forcing redundant and robust features.
- Approximates averaging an exponentially large ensemble of weight-sharing subnetworks.
- Acts as noise injection, lowering variance.
Typical p is 0.1–0.5. It is common in dense layers and transformers, and less so in convolutional blocks that already use batch norm. Too much dropout causes underfitting.
7. Bagging vs. boosting
| Aspect | Bagging | Boosting |
|---|---|---|
| Training | Independent learners on bootstrap samples, in parallel | Sequential learners, each focusing on previous errors |
| Base learner | Low-bias, high-variance (deep trees) | High-bias, low-variance (shallow trees or stumps) |
| Mainly reduces | Variance | Bias (and some variance) |
| Combination | Average or vote | Weighted sum |
| Overfitting risk | Low; more learners rarely hurt | Higher; needs shrinkage, early stopping, depth limits |
| Noise sensitivity | Robust | Can chase noisy labels and outliers |
| Examples | Random forest | AdaBoost, gradient boosting, XGBoost |
Random forests add feature subsampling to decorrelate trees, which further reduces the variance of the average. Gradient boosting fits each new learner to the negative gradient (residuals) of the loss, with a learning rate controlling the step size.
Closing point
Each technique maps to the bias-variance trade-off: capacity, boosting and longer training reduce bias, while data, augmentation, regularization, dropout and bagging reduce variance. Always confirm with learning curves before choosing the fix.