Traditional Machine Learning, Exploratory Data Analysis & Statistical Testing
Primary references:
- ML From Scratch GitHub Repository
- Stanford CS Courses - Statistical Learning and Regression Notes
- Analytics Vidhya - Understanding Random Forest Architectures
- Medium - Comprehensive Guide to A/B Testing Frameworks
Overview
Traditional machine learning provides the foundations on which modern deep learning systems are built: optimization, convexity, supervised models, unsupervised representation learning, ensembles, data hygiene, and statistical evaluation.
This document covers:
- Convexity, Hessians, and optimization.
- Linear, logistic, and multinomial logistic regression.
- Support Vector Machines, k-Nearest Neighbors, decision trees, and Naive Bayes.
- Principal Component Analysis, K-Means, and Isolation Forest.
- Exploratory data analysis and data hygiene.
- Hypothesis testing and A/B testing.
- Bagging, boosting, LIME, and SHAP.
A source note: the linked Stanford chapter is titled Embeddings and primarily covers vector semantics, word embeddings, cosine similarity, and word2vec rather than regression or statistical learning. Its material is used here for vector representation, similarity, and representation-learning foundations. web.stanford
Module 1: Optimization and Convexity Foundations
Convexity
A function $f$ is convex if, for any $x$ and $y$ in its domain and any $k \in $, the following relation holds:[0][1]
\[f(kx + (1-k)y) \le k f(x) + (1-k) f(y)\]Intuitively, a convex function has no local dips: every line segment between two points on its graph lies on or above the graph.
For differentiable functions, a first-order condition for convexity is:
\[f(x) + f'(x)(y-x) \le f(y)\]where:
- $f’(x)$ is the first derivative at $x$.
- The tangent line at any point lies below the function.
Positive semi-definite Hessians
A symmetric matrix $A$ is Positive Semi-Definite, or PSD, if for any real vector $x$:
\[x^T A x \ge 0\]This is equivalent to saying that all eigenvalues of $A$ are non-negative.
For a twice-differentiable function $f$, the Hessian matrix contains second derivatives:
\[H_{ij} = \frac{\partial^2 f}{\partial x_i \partial x_j}\]The Hessian of a convex function is positive semi-definite everywhere in its domain.
Critical points
Critical points occur where the gradient vanishes:
\[\nabla f(x) = 0\]The Hessian classifies these points.
| Hessian property | Critical-point classification |
|---|---|
| Positive-definite, all $\lambda_i > 0$ | Isolated local minimum |
| Negative-definite, all $\lambda_i < 0$ | Isolated local maximum |
| Mixed eigenvalue signs, some $\lambda_i > 0$ and some $\lambda_j < 0$ | Saddle point |
| Positive semi-definite, all $\lambda_i \ge 0$ | Possible local minimum; may be flat |
where $\lambda_i$ denotes an eigenvalue of the Hessian.
For a convex function, every local minimum is also a global minimum. This is why convex optimization is much easier than non-convex optimization.
Module 2: Supervised Learning Models and Algorithms
Linear regression
Linear regression predicts a continuous target using a linear combination of features:
\[\hat{y} = w^T x + b\]where:
- $x$ is the feature vector.
- $w$ is the weight vector.
- $b$ is the bias term.
- $\hat{y}$ is the predicted value.
It minimizes Mean Squared Error, or MSE:
\[\mathcal{L}_{MSE} = \frac{1}{N} \sum_{i=1}^{N} (y_i - \hat{y}_i)^2\]where:
- $y_i$ is the true target.
- $\hat{y}_i$ is the predicted target.
- $N$ is the number of samples.
Because MSE is convex with respect to the parameters in ordinary linear regression, gradient descent converges to the global minimum under appropriate conditions.
Logistic regression
Logistic regression applies a sigmoid activation to a linear combination of features to predict binary outcomes:
\[S(a) = \frac{1}{1 + e^{-a}}\]where:
\[a = w^T x + b\]The sigmoid maps any real number into the interval $(0, 1)$:
a = -inf -> S(a) = 0
a = 0 -> S(a) = 0.5
a = +inf -> S(a) = 1
Although the sigmoid composition itself is non-linear, applying negative log-likelihood derived from the Bernoulli distribution produces a convex cross-entropy loss:
\[\mathcal{L}_{CE} = -\frac{1}{N} \sum_{i=1}^{N} \left[ y_i \log \hat{y}_i + (1-y_i)\log(1-\hat{y}_i) \right]\]where:
- $y_i \in {0, 1}$ is the binary label.
- $\hat{y}_i$ is the predicted probability of class 1.
Multinomial logistic regression
Multinomial logistic regression extends binary logistic regression to $K$ discrete classes. It uses the softmax normalization function:
\[P(y = k \mid x) = \frac{\exp(w_k^T x + b_k)} {\sum_{j=1}^{K} \exp(w_j^T x + b_j)}\]where:
- $K$ is the number of classes.
- $w_k$ is the weight vector for class $k$.
- $b_k$ is the bias for class $k$.
The multi-class cross-entropy loss is:
\[\mathcal{L} = -\frac{1}{N} \sum_{i=1}^{N} \log P(y_i \mid x_i)\]Support Vector Machines
Support Vector Machines, or SVMs, find an optimal separating hyperplane:
\[w^T x + b = 0\]that maximizes the geometric margin between classes.
For a linearly separable dataset, the primal optimization problem minimizes:
\[\frac{1}{2} \|w\|^2\]subject to:
\[y_i(w^T x_i + b) \ge 1\]where:
- $x_i$ is a training sample.
- $y_i \in {-1, +1}$ is its class label.
- $w$ is the normal vector to the hyperplane.
- $b$ is the bias.
Using Lagrange multipliers and satisfying the Karush-Kuhn-Tucker, or KKT, conditions yields the dual quadratic-programming formulation. The dual formulation depends only on support vectors: the training points closest to the decision boundary.
Class +1
o o
o
---------------- decision boundary
x
x x
Class -1
k-Nearest Neighbors
k-Nearest Neighbors, or kNN, is a non-parametric, instance-based method. It classifies an unlabeled point based on a plurality vote among its $k$ nearest neighbors, commonly using Euclidean distance.
\[d(x, x_i) = \sqrt{ \sum_{j=1}^{d} (x_j - x_{i,j})^2 }\]where:
- $x$ is the query point.
- $x_i$ is a training point.
- $d$ is the feature dimension.
kNN has no explicit training phase, but prediction can be expensive because it must compute distances to stored training examples.
Decision trees
Decision trees recursively partition the feature space into non-overlapping rectangular regions. At each node, the algorithm selects a split that maximizes information gain or Gini gain.
Entropy and information gain
Entropy measures impurity:
\[H(S) = -\sum_{c=1}^{C} p_c \log_2 p_c\]where:
- $S$ is a set of samples.
- $C$ is the number of classes.
- $p_c$ is the proportion of samples in class $c$.
Information gain from a split is:
\[IG(S, A) = H(S) - \sum_{v \in \text{values}(A)} \frac{|S_v|}{|S|} H(S_v)\]where:
- $A$ is the selected feature.
- $S_v$ is the subset of samples with feature value $v$.
Gini impurity
Gini impurity is:
\[G(S) = 1 - \sum_{c=1}^{C} p_c^2\]A split that reduces Gini impurity or entropy creates purer child nodes.
Naive Bayes
Naive Bayes applies Bayes’ theorem under a strong conditional-independence assumption between features:
\[P(y \mid x) \propto P(y) \prod_{j=1}^{d} P(x_j \mid y)\]where:
- $y$ is the class label.
- $x_j$ is feature $j$.
- $P(y)$ is the class prior.
- $P(x_j \mid y)$ is the likelihood of feature $j$ given class $y$.
For continuous attributes, Naive Bayes commonly evaluates Gaussian probability densities:
\[P(x_j \mid y) = \frac{1} {\sqrt{2\pi\sigma_{y,j}^2}} \exp \left( -\frac{(x_j - \mu_{y,j})^2} {2\sigma_{y,j}^2} \right)\]where:
- $\mu_{y,j}$ is the mean of feature $j$ for class $y$.
- $\sigma_{y,j}^2$ is the variance of feature $j$ for class $y$.
Module 3: Unsupervised Learning and Dimensionality Reduction
Principal Component Analysis
Principal Component Analysis, or PCA, reduces data dimensionality while preserving maximum variance.
The three core steps are:
- Mean-center and standardize the data matrix $X$.
- Compute the empirical covariance matrix.
- Perform eigendecomposition and project onto the leading principal components.
Original high-dimensional data
|
v
Mean-center and standardize
|
v
Compute covariance matrix
|
v
Eigendecomposition
|
v
Select top-k eigenvectors
|
v
Project data onto principal components
The covariance matrix is:
\[C = \frac{1}{n-1} A^T A\]where:
- $A$ is the centered data matrix.
- $n$ is the number of samples.
PCA finds eigenvectors of $C$. The eigenvector with the largest eigenvalue is the first principal component and captures the greatest variance.
The explained variance ratio for component $i$ is:
\[\text{explained variance ratio}_i = \frac{\lambda_i} {\sum_{j=1}^{d} \lambda_j}\]where:
- $\lambda_i$ is the $i$-th eigenvalue.
- $d$ is the number of original features.
K-Means clustering
K-Means partitions data into $K$ clusters by alternating between:
- Assigning each point to the nearest cluster centroid.
- Recomputing each centroid as the mean of its assigned points.
Initialize K centroids
|
v
Assign points to nearest centroid
|
v
Recompute centroids
|
v
Repeat until convergence
The objective is to minimize within-cluster sum of squares:
\[\mathcal{L} = \sum_{k=1}^{K} \sum_{x_i \in C_k} \|x_i - \mu_k\|^2\]where:
- $C_k$ is cluster $k$.
- $\mu_k$ is the centroid of cluster $k$.
K-Means is sensitive to initialization, cluster shape, scale, and outliers. It assumes roughly spherical, similarly sized clusters.
Isolation Forest
Isolation Forest is an unsupervised anomaly-detection algorithm that isolates anomalies rather than profiling normal data.
Because anomalies are sparse and distinct, they require fewer random partitions, producing shorter path lengths in random isolation trees than dense normal points. web.stanford
Random feature and split
|
v
Partition data
|
v
Repeat recursively
|
v
Anomaly score based on path length
A shorter average path length indicates that a point is easier to isolate and is therefore more likely to be anomalous.
Module 4: Exploratory Data Analysis and Data Hygiene
Data-quality workflow
Raw data
|
v
Inspect schema and types
|
v
Remove duplicates
|
v
Handle missing values
|
v
Detect outliers
|
v
Visualize distributions
|
v
Check correlations and leakage
|
v
Model-ready dataset
Handling missing values
Common strategies include:
| Strategy | When to use | Risk |
|---|---|---|
| Drop rows | Missingness is rare and random | Loss of data |
| Drop columns | Feature is mostly missing | Loss of potentially useful signal |
| Mean or median imputation | Numeric feature with simple distribution | Can distort variance |
| Mode imputation | Categorical feature | Can overrepresent a category |
| Model-based imputation | Complex missingness pattern | More complexity and leakage risk |
| Missingness indicator | Missingness itself is informative | Adds features |
Robust imputation can use trimmed means, which discard extreme upper and lower percentiles before computing the average.
Outlier detection
Interquartile range
The Interquartile Range, or IQR, is:
\[\text{IQR} = Q_3 - Q_1\]where:
- $Q_1$ is the 25th percentile.
- $Q_3$ is the 75th percentile.
A common outlier rule flags values outside:
\[[Q_1 - 1.5 \times \text{IQR}, Q_3 + 1.5 \times \text{IQR}]\]Z-score
The Z-score measures standardized deviation from the mean:
\[z = \frac{x - \mu}{\sigma}\]where:
- $x$ is a value.
- $\mu$ is the mean.
- $\sigma$ is the standard deviation.
A common rule filters points where:
\[|z| > 3\]Z-score-based detection assumes approximately normal data and can be misleading for skewed or heavy-tailed distributions.
Statistical distributions and visualization
Univariate and bivariate structure should be inspected using:
- Count plots.
- Distribution plots.
- Box plots.
- Pair plots.
- Correlation heatmaps.
- Scatter plots.
- Time-series plots.
Numeric feature
|
+--> Histogram / KDE
|
+--> Box plot
|
+--> Q-Q plot
Categorical feature
|
+--> Count plot
|
+--> Group-wise aggregate plot
Two numeric features
|
+--> Scatter plot
|
+--> Correlation heatmap
Correlation does not imply causation. A high correlation may reflect confounding, leakage, selection bias, or a shared upstream cause.
Module 5: Statistical Hypothesis Testing and A/B Testing
Hypothesis testing
Hypothesis testing evaluates a null hypothesis $H_0$ against an alternative hypothesis $H_1$ using test statistics and $p$-values.
| Term | Meaning |
|---|---|
| Null hypothesis $H_0$ | Default assumption, often “no effect” |
| Alternative hypothesis $H_1$ | Claim being tested, often “there is an effect” |
| Test statistic | Standardized measure of evidence against $H_0$ |
| $p$-value | Probability of observing data at least as extreme as observed, assuming $H_0$ is true |
| Significance level $\alpha$ | Maximum tolerated Type I error probability |
| Statistical power $1-\beta$ | Probability of correctly rejecting a false null hypothesis |
Z-test and t-test
A Z-test is commonly applied when sample sizes are large, often $n \ge 30$, or when the population variance is known.
A t-test is commonly applied when sample sizes are small, often $n < 30$, or when the population variance is unknown. It uses Student’s t-distribution.
For comparing two sample means, a simplified two-sample test statistic is:
\[t = \frac{ \bar{x}_A - \bar{x}_B }{ \sqrt{ \frac{s_A^2}{n_A} + \frac{s_B^2}{n_B} } }\]where:
- $\bar{x}_A$ and $\bar{x}_B$ are sample means.
- $s_A^2$ and $s_B^2$ are sample variances.
- $n_A$ and $n_B$ are sample sizes.
Error types
| Error | Definition | Example |
|---|---|---|
| Type I error, $\alpha$ | Rejecting a true null hypothesis | Launching a change that has no real effect |
| Type II error, $\beta$ | Failing to reject a false null hypothesis | Missing a real improvement |
| Statistical power, $1-\beta$ | Probability of detecting a true effect | Higher power reduces missed improvements |
Truth: no effect Truth: effect exists
Decision: reject H0 Type I error Correct rejection
Decision: keep H0 Correct decision Type II error
A/B testing methodology
A/B testing optimizes digital products by exposing different user groups to different experiences simultaneously.
Traffic
|
+--> Control: variant A
|
+--> Treatment: variant B
|
v
Measure business and guardrail metrics
|
v
Statistical test
|
v
Launch, iterate, or reject
Key steps:
- Define a clear hypothesis.
- Select a primary business metric, such as conversion rate or revenue per user.
- Select guardrail metrics, such as bounce rate, latency, error rate, or complaint rate.
- Compute required sample size from the minimum detectable effect, significance level, and power.
- Randomize users consistently.
- Run the experiment for full business cycles where possible.
- Analyze with appropriate statistical tests.
- Check for novelty effects, sample-ratio mismatch, and guardrail regressions.
- Make a launch decision based on practical as well as statistical significance.
Sample size
A simplified sample-size calculation for comparing two proportions is:
\[n \approx \frac{ 2 \left( z_{1-\alpha/2} + z_{1-\beta} \right)^2 \bar{p}(1-\bar{p}) }{ \Delta^2 }\]where:
- $z_{1-\alpha/2}$ is the critical value for the chosen significance level.
- $z_{1-\beta}$ is the critical value for the chosen power.
- $\bar{p}$ is the average baseline conversion rate.
- $\Delta$ is the minimum detectable effect.
Smaller effects, higher power, and lower significance levels all require larger sample sizes.
Module 6: Ensemble Learning and Model Explainability
Bagging
Bagging, or bootstrap aggregating, trains multiple models independently on bootstrap samples drawn with replacement. Their predictions are aggregated by majority vote for classification or averaging for regression. web.stanford
Training data
|
+--> Bootstrap sample 1 --> Tree 1
|
+--> Bootstrap sample 2 --> Tree 2
|
+--> Bootstrap sample 3 --> Tree 3
|
v
Aggregate predictions
Random Forests extend bagging by training many decision trees independently in parallel on bootstrap samples. Each tree also selects a random subset of features at each split, decorrelating individual estimators and reducing variance. web.stanford
| Property | Effect |
|---|---|
| Bootstrap sampling | Reduces variance |
| Random feature selection | Decorrelates trees |
| Majority vote or averaging | Improves robustness |
| Deep unpruned trees | Allows complex decision boundaries |
Boosting
Boosting trains weak predictors sequentially. Each new model explicitly targets the residual errors or reweighted hard instances of its predecessor. Boosting primarily reduces bias. web.stanford
Initial model
|
v
Compute residuals or errors
|
v
Train next model on errors
|
v
Add weighted prediction
|
v
Repeat
AdaBoost
AdaBoost reweights misclassified examples so subsequent weak learners focus more on them.
Gradient Boosting
Gradient boosting fits each new learner to the negative gradient of the loss, which for squared-error loss is the residual:
\[r_i = y_i - F_{m-1}(x_i)\]where:
- $F_{m-1}(x_i)$ is the prediction after $m-1$ boosting rounds.
- $r_i$ is the residual for sample $i$.
LIME
Local Interpretable Model-agnostic Explanations, or LIME, explains individual predictions by perturbing input instances locally and fitting an interpretable surrogate model, such as linear regression, over the synthetic neighborhood. web.stanford
Original instance
|
v
Generate perturbed neighbors
|
v
Get black-box predictions
|
v
Weight neighbors by proximity
|
v
Fit interpretable surrogate model
|
v
Local explanation
LIME is model-agnostic but local: an explanation for one prediction may not generalize to another.
SHAP
SHAP, or SHapley Additive exPlanations, applies cooperative game theory to compute Shapley values. It assigns each feature a consistent contribution score toward the final model prediction. web.stanford
Prediction
|
v
Consider all feature coalitions
|
v
Measure marginal contribution of each feature
|
v
Average over coalitions
|
v
Shapley value per feature
SHAP values satisfy useful consistency and additivity properties, but exact computation can be expensive for models with many features.
Module 7: Vector Representations and Similarity
Why representations matter
The linked Stanford chapter introduces vector semantics: representing word meaning as a point in a multidimensional space derived from word distributions. It is grounded in the distributional hypothesis: words that occur in similar contexts tend to have similar meanings. web.stanford
Word contexts
|
v
Co-occurrence statistics
|
v
Vector representation
|
v
Semantic similarity
This principle extends beyond NLP. Traditional ML also relies heavily on learned or engineered vector representations of users, items, documents, and events.
Cosine similarity
Cosine similarity measures the angle between two vectors and is widely used to compare embeddings.
\[\text{cosine}(v,w) = \frac{v \cdot w} {\|v\|\|w\|} = \frac{ \sum_{i=1}^{N} v_i w_i }{ \sqrt{\sum_{i=1}^{N} v_i^2} \sqrt{\sum_{i=1}^{N} w_i^2} }\]where:
- $v$ and $w$ are vectors.
- $v \cdot w$ is the dot product.
- $|v|$ and $|w|$ are vector lengths.
Cosine similarity ranges from $-1$ to $1$ for real-valued vectors. For non-negative frequency vectors, it ranges from $0$ to $1$. web.stanford
Cosine similarity is preferred over raw dot product when vector magnitude should not influence similarity.
Sparse versus dense representations
| Representation | Example | Dimension | Strength | Limitation |
|---|---|---|---|---|
| Sparse count vector | Bag-of-words | Vocabulary size | Interpretable, simple | High-dimensional and sparse |
| TF-IDF vector | Weighted bag-of-words | Vocabulary size | Emphasizes distinctive terms | Still sparse |
| Dense embedding | word2vec, learned encoder | 50 to 1,000 | Captures semantic similarity | Less directly interpretable |
Dense embeddings use far fewer dimensions than vocabulary-sized sparse vectors and can capture similarity between related but distinct terms. web.stanford
Part 8: Comparisons and Trade-Offs
Supervised model comparison
| Model | Strength | Limitation | Best use |
|---|---|---|---|
| Linear regression | Simple, interpretable, convex | Assumes linear relationship | Continuous prediction |
| Logistic regression | Calibrated probabilities, convex loss | Linear decision boundary | Binary classification |
| Multinomial logistic regression | Multi-class probabilities | Linear boundaries | Text or tabular classification |
| SVM | Strong margins, kernel flexibility | Scaling and tuning complexity | Small to medium datasets |
| kNN | Simple, non-parametric | Slow inference, sensitive to scale | Low-dimensional local structure |
| Decision tree | Interpretable, handles mixed features | High variance | Rule discovery and baselines |
| Naive Bayes | Fast, works with limited data | Strong independence assumption | Text classification and spam filtering |
Bagging versus boosting
| Property | Bagging / Random Forest | Boosting |
|---|---|---|
| Training order | Parallel | Sequential |
| Main goal | Reduce variance | Reduce bias |
| Base learners | Usually deep trees | Usually shallow trees |
| Sensitivity to noisy labels | Lower | Higher |
| Typical inference | Parallel ensemble | Sequential additive model |
| Examples | Random Forest | AdaBoost, Gradient Boosting |
PCA versus K-Means
| Property | PCA | K-Means |
|---|---|---|
| Task | Dimensionality reduction | Clustering |
| Output | Principal components | Cluster assignments and centroids |
| Objective | Maximize retained variance | Minimize within-cluster distance |
| Supervision | Unsupervised | Unsupervised |
| Main risk | Linear assumptions | Poor fit for non-spherical clusters |
Part 9: Limitations and Open Questions
Modeling limitations
- Linear models cannot capture non-linear relationships without feature engineering or kernels.
- kNN scales poorly with dataset size and high dimensionality.
- Decision trees can overfit without pruning or ensembling.
- Naive Bayes’ independence assumption is often violated.
- SVMs require careful kernel and hyperparameter selection.
Data limitations
- Missing values can introduce bias if missingness is not random.
- Outlier removal can discard legitimate rare events.
- Correlation analysis can mislead when confounders exist.
- Train-test leakage can inflate offline metrics.
- Class imbalance can make accuracy misleading.
Experimentation limitations
- A/B tests require sufficient sample size and duration.
- Multiple comparisons increase false-positive risk.
- Novelty effects can temporarily inflate treatment performance.
- Network effects and shared infrastructure can violate independence assumptions.
- Statistical significance does not guarantee business significance.
Representation limitations
- Sparse count-based representations do not naturally capture synonymy.
- Static embeddings assign one vector per word, even though meaning depends on context.
- Cosine similarity measures directional similarity, not causality or factual correctness.
The Stanford chapter notes that word2vec produces static embeddings, while contextualized models such as BERT produce different vectors for a word in different contexts. web.stanford
Resources
- ML From Scratch — implementation references for foundational machine-learning algorithms.
- Stanford CS: Embeddings chapter — vector semantics, cosine similarity, sparse and dense representations, and word2vec.
- Understanding Random Forest Architectures — overview of bagging and ensemble methods.
- A/B Testing Frameworks — practical experimentation methodology.
Final Technical Takeaways
- Central mechanism: Traditional ML learns decision boundaries, clusters, or representations by optimizing objectives over data, then evaluates whether those objectives generalize.
- Main optimization insight: Convex objectives have no bad local minima; linear regression and logistic regression are convex under their standard loss formulations.
- Main modeling insight: No single model dominates. Linear models offer interpretability, trees capture non-linear rules, SVMs maximize margins, and ensembles trade bias against variance.
- Main data insight: Data hygiene, leakage prevention, missing-value handling, and distribution analysis often affect production performance more than model choice.
- Main evaluation insight: Use power analysis, guardrail metrics, and appropriate statistical tests; statistical significance alone does not establish business value.
- Main representation insight: Cosine similarity compares direction rather than magnitude, making it a standard similarity measure for sparse vectors and dense embeddings. web.stanford
- Broader engineering implication: Build ML systems as measurement-driven pipelines: clean data, choose a model matched to the constraint, validate rigorously, explain decisions, and experiment before launch.