Machine Learning Fundamentals: Concepts, part 2
What are parametric vs non-parametric models?
Parametric models have a fixed number of parameters regardless of dataset size: linear/logistic regression, naive Bayes, a neural network of a given architecture. They make stronger assumptions, are fast at inference, and need less data, but can underfit.
Non-parametric models grow in complexity with the data: k-nearest neighbors (stores the dataset), decision trees without depth limits, kernel methods, Gaussian processes. They're flexible but can be slow at inference and need more data. (Note: "non-parametric" doesn't mean "no parameters".)
Explain logistic regression. Why use log-loss instead of MSE?
Logistic regression models P(y=1|x) = σ(wᵀx + b) with sigmoid σ(z) = 1/(1+e^(−z)). It is a linear model of the log-odds: log(p/(1−p)) = wᵀx + b.
It's trained by maximizing likelihood, which is equivalent to minimizing binary cross-entropy: −[y·log p + (1−y)·log(1−p)].
Why not MSE: (1) with a sigmoid, MSE is non-convex in w, while log-loss is convex, so there is one global optimum. (2) MSE gradients vanish when the sigmoid saturates even if the prediction is confidently wrong, whereas log-loss's gradient is simply (p − y)·x, staying large for confident mistakes. (3) Log-loss is the proper scoring rule from maximum likelihood under a Bernoulli model.
How do decision trees choose splits? What are Gini impurity and entropy?
At each node, a tree greedily picks the feature and threshold that maximize the reduction in impurity (information gain) between parent and the weighted children.
- Gini impurity: G = 1 − Σₖ pₖ². The probability of misclassifying a random sample labeled according to the node's class distribution.
- Entropy: H = −Σₖ pₖ log₂ pₖ. Information gain = H(parent) − weighted H(children).
Both behave similarly; Gini is slightly cheaper (no logs). For regression trees, the criterion is variance (MSE) reduction.
Trees overfit easily, so control with max depth, min samples per leaf, or pruning. Their strengths: no feature scaling needed, they handle non-linearities and interactions, and they are interpretable.
What is cross-validation and when would plain k-fold be wrong?
k-fold CV splits data into k folds, trains on k−1 and validates on the remaining one, rotates, and averages the scores. This gives a lower-variance estimate of generalization than one split and uses all data for both training and validation.
When plain k-fold is wrong:
- Time series: random folds leak the future into training. Use forward-chaining (train on past, validate on the next period).
- Grouped data (multiple rows per user/patient): the same group in train and val inflates scores. Use GroupKFold.
- Imbalanced classes: use stratified k-fold to preserve class ratios.
- Hyperparameter tuning + evaluation on the same CV overestimates performance. Use nested CV or a final held-out test set.
What is data leakage? Give examples.
Leakage is when information that won't be available at prediction time influences training, producing optimistic offline metrics that collapse in production.
Examples:
- Target leakage: a feature derived from the label (e.g., "refund_issued" when predicting fraud; "discharge_date" for predicting hospitalization length).
- Train–test contamination: fitting a scaler, imputer or TF-IDF vocabulary on the full dataset before splitting.
- Temporal leakage: random splits on time-ordered data; using features computed with future data (e.g., a 30-day rolling average that includes future days).
- Duplicate leakage: near-duplicate rows across train and test (common with web text, which is also a big issue in LLM benchmark contamination).
Prevention: split first, put all preprocessing in a pipeline fit only on training folds, split by time/group when relevant, and be suspicious of "too good" results.
Explain the curse of dimensionality.
As the number of dimensions grows:
- Data becomes sparse: the volume grows exponentially, so you need exponentially more data to cover the space at the same density.
- Distances concentrate: the ratio between the nearest and farthest neighbor distances approaches 1, so distance-based methods (kNN, clustering) lose discriminative power.
- Most of a hypercube's volume lies near its corners/surface, which is counterintuitive for geometric reasoning.
Mitigations: feature selection, dimensionality reduction (PCA, autoencoders), regularization, and models that exploit structure. Real data often lies on a lower-dimensional manifold, which is why high-dimensional embeddings still work well in practice.
How does k-nearest neighbors work and when would you use it?
To predict for a point, find the k closest training points (by a distance metric) and take a majority vote (classification) or average (regression), optionally distance-weighted.
- Pros: no training, naturally multi-class, adapts to complex boundaries, easy to explain ("these 5 similar customers…").
- Cons: slow inference (O(n·d) without an index), sensitive to feature scaling and irrelevant features, suffers in high dimensions.
- Choosing k: small k → high variance; large k → high bias. Pick by cross-validation.
Modern relevance: approximate nearest-neighbor search over embeddings is k-NN at scale, the backbone of semantic search and RAG.
Explain the difference between a hyperparameter and a parameter. How do you tune hyperparameters?
Parameters are learned from data by the training algorithm (weights, biases, tree split thresholds). Hyperparameters are set before training and control the learning process or model capacity (learning rate, regularization strength, tree depth, number of layers, k in k-NN).
Tuning methods:
- Grid search: exhaustive but wasteful in high dimensions.
- Random search: often better than grid for the same budget, because few hyperparameters matter most (Bergstra & Bengio).
- Bayesian optimization (Optuna, Hyperopt): models the objective to pick promising configurations.
- Early-stopping-based schedulers (Hyperband/ASHA): kill bad trials early.
Always tune on validation data (or CV), and report the final score on the untouched test set.