Data Analytics with Machine Learning
Scales of measurement, feature engineering, EDA, performance metrics, KNN, decision trees, SVM, ensemble methods (XGBoost, LightGBM), PCA, and ICA.
Topics in this chapter
- Scales of Measurement: Nominal, Ordinal, Interval, Ratio
- Feature Engineering and Exploratory Data Analysis (EDA)
- Performance Metrics: MSE, RMSE, MAE, R², Confusion Matrix, Accuracy, Recall, Precision, F1-Score, Specificity
- Regression and Classification using KNN
- Decision Tree, Attribute Selection Criteria, ID3 vs C4.5 vs CART
- Random Forest (Bagging and Boosting)
- Linear and Non-linear SVM, SVC, SVR
- Gradient Boosting: XGBoost and LightGBM
- Dimensionality Reduction: PCA and ICA
Foundations of Machine Learning: Data Preparation and Evaluation Metrics
Scales of Measurement
Before any machine learning model can be constructed, the data must be understood in terms of its scales of measurement. These scales determine which mathematical operations are meaningful and guide feature encoding, distance metrics, and ultimately the choice of algorithms. There are four fundamental scales.
Nominal attributes are categorical labels without any intrinsic ordering. Examples include country of origin, product colour, or a unique identifier. The only permissible operation is equality testing (). For machine learning, nominal variables are typically transformed using one-hot encoding, which creates binary dummy variables for distinct categories, ensuring that no artificial ordinal relationship is imposed. Note that one-hot encoding increases dimensionality and, if categories are numerous, may require dimensionality reduction or target encoding.
Ordinal attributes possess a meaningful order but the intervals between successive values are not necessarily uniform. A credit rating from AAA to C, or a Likert scale from "strongly disagree" to "strongly agree" are ordinal. While we can state that AAA AA A, we cannot claim that the difference between AAA and AA equals the difference between B and CCC. Ordinal encoding, where integers preserve the order (e.g., 1, 2, 3, …), is common, but caution is required when using distance-based models, which implicitly treat the encoded numbers as interval-scaled.
Interval-scaled attributes have equal and meaningful differences, but no true zero point. Temperature in Celsius or Fahrenheit is interval: the difference between C and C is the same as between C and C, but C does not imply the absence of heat. All arithmetic operations (addition, subtraction) are valid, but ratios are not. Standardization (z-score ) is applied to interval variables to remove scale effects.
Ratio-scaled attributes have all the properties of interval data plus a true zero, allowing meaningful ratios. Examples include income, height, elapsed time, and quantity sold. A household earning \100,000$50,000$. Ratio variables are also amenable to standardization, but logarithmic or Box-Cox transformations are often applied to handle positive skewness typical in economic indicators.
The hierarchy of measurement scales — nominal ordinal interval ratio — dictates permissible transformations. Nominal data allows only one-to-one mappings; ordinal data permits monotonic increasing transformations; interval data supports linear transformations where ; and ratio data allows similarity transformations where .
Feature Engineering
Feature engineering is the process of transforming raw data into a representation that better captures the underlying structure of the problem, thereby improving model accuracy, interpretability, and generalizability. Formally, given a dataset with original feature vectors , feature engineering constructs a mapping such that a learning algorithm achieves lower empirical risk.
Essential Steps in Feature Engineering
-
Exploratory Data Analysis (EDA) precedes any transformation. EDA employs summary statistics, correlation matrices, and visualizations (histograms, scatter plots, box plots) to reveal distributions, outliers, and relationships.
Univariate analysis examines individual variables through measures of central tendency (, median, mode) and dispersion (, standard deviation, IQR). Histograms, box plots, and kernel density estimates reveal distributional properties such as skewness and kurtosis .
Bivariate analysis explores relationships between variables. The Pearson correlation coefficient quantifies linear associations. However, correlation does not imply causation, and nonlinear relationships may exhibit despite strong dependencies.
Missing data analysis is critical: the pattern of missingness — whether missing completely at random (MCAR), missing at random (MAR), or missing not at random (MNAR) — determines appropriate imputation strategies. Simple mean imputation preserves the sample mean but artificially reduces variance. More sophisticated approaches include k-nearest neighbors imputation, multiple imputation by chained equations (MICE), or model-based methods.
Outlier detection employs both statistical and visual techniques. The IQR method flags observations outside as potential outliers. Z-score methods identify points where .
-
Handling Categorical Variables is perhaps the most common transformation. Nominal variables are encoded via one-hot encoding, which for a categorical feature with levels yields a binary indicator matrix . For high-cardinality features, label encoding (assigning integers ) may be used with tree-based models. An intermediate approach is target encoding, where each category is replaced by the mean of the target variable for that category, often with smoothing to avoid overfitting.
-
Numerical Transformations and Scaling are essential for distance-based algorithms like -NN, SVM with RBF kernel, and neural networks:
- Standardization (z-score): , yielding zero mean and unit variance.
- Min-max scaling: , bounding values to .
- Robust scaling: , providing resilience against extreme values.
- Logarithmic or Box-Cox transformations to reduce skewness and stabilize variance: \begin{cases}\frac{x^\lambda - 1}{\lambda} & \text{if } \lambda \neq 0 \ \log(x) & \text{if } \lambda = 0\end{cases} .
-
Feature Creation and Selection go beyond encoding. Polynomial features capture interactions and non-linearities. After creation, feature selection techniques such as recursive feature elimination, regularization ( penalty), and mutual information prune irrelevant or redundant variables.
Performance Evaluation Metrics
Regression Metrics
Given true values and predicted values , the most fundamental error measure is the mean squared error (MSE):
Because MSE squares errors, it heavily penalizes large deviations. Taking the square root yields the root mean squared error (RMSE):
RMSE is expressed in the same units as the target variable, facilitating interpretation. The quadratic nature makes RMSE differentiable and convex, which is why it is the default optimization objective for many algorithms. However, the sensitivity to outliers can be problematic when predicting variables like income, where a few extreme values may dominate the error. In such cases, the mean absolute error (MAE),
provides a more robust alternative because it weights all errors linearly. The coefficient of determination (),
measures the proportion of variance explained, with indicating perfect fit. It is scale-free, allowing comparisons across problems.
Classification Metrics
For binary classification, the confusion matrix is the foundation. Each prediction falls into one of four categories: true positive (TP), false positive (FP), false negative (FN), and true negative (TN). From these we define:
- Accuracy: . Misleading when classes are imbalanced.
- Precision (positive predictive value): . Measures how many of the predicted positives are actually positive. High precision is crucial when the cost of a false positive is high.
- Recall (sensitivity, true positive rate): . Captures how many of the actual positives are correctly identified. In medical diagnosis, high recall minimizes the risk of missing a disease.
- Specificity (true negative rate): . The analogue of recall for the negative class.
- F1-Score: . The harmonic mean of precision and recall.
In economic terms, the choice between precision and recall maps to the relative costs of Type I errors (false positives) and Type II errors (false negatives). A spam filter with high precision avoids blocking legitimate emails (low false positives); a cancer screening with high recall avoids missing cases (low false negatives).
Advanced Classification Metrics
The Receiver Operating Characteristic (ROC) curve plots the true positive rate (recall) against the false positive rate () at various threshold settings. The Area Under the ROC Curve (AUC-ROC) is a threshold-invariant metric; an AUC of 1.0 indicates perfect discrimination, while 0.5 indicates random guessing. The Precision-Recall (PR) curve is preferred when classes are highly imbalanced.
Log Loss (Cross-Entropy) for probabilistic classifiers:
where is the predicted probability. Log loss heavily penalizes confident but wrong predictions, making it appropriate when probabilistic calibration matters.
Holdout and Cross-Validation
Holdout validation splits data into training (typically 70-80%) and test sets. The k-fold cross-validation partitions data into equal-sized folds, trains on folds and validates on the remaining fold, repeating times. The average performance provides a more robust estimate of generalization error. Stratified k-fold preserves class proportions in each fold, essential for imbalanced classification. Leave-one-out cross-validation (LOOCV) is the extreme case where , providing near-unbiased but high-variance estimates.
Performance Evaluation Metrics
K-Nearest Neighbors (KNN)
The K-Nearest Neighbors (KNN) algorithm is a non-parametric, instance-based learner that requires no explicit training phase. For a new query point , it identifies the training observations closest under a chosen distance metric, typically the Euclidean norm .
In classification, the predicted class is the majority vote among the neighbors. In regression, the prediction is the (possibly inverse-distance-weighted) average of the neighbors' target values:
Common distance metrics include the Minkowski distance , which specializes to Manhattan () and Euclidean () distances. The hyper-parameter governs the bias–variance trade-off: small yields highly flexible, low-bias but high-variance boundaries; large smoothes the decision surface.
Although KNN is conceptually appealing, its performance degrades in high-dimensional spaces (the curse of dimensionality) because all points become roughly equidistant. Formally, as , , rendering the notion of "nearest" statistically meaningless. The algorithm's economic intuition is that of a pure market-follower: it predicts the outcome of a new observation by looking at the most similar historical cases, much like a real-estate appraisal that averages recent sale prices of comparable properties.
Decision Trees
A Decision Tree recursively partitions the input space into axis-aligned hyper-rectangles, assigning a constant prediction (the majority class or the mean response) to each terminal leaf. The tree is grown by sequentially choosing the attribute and splitting threshold that maximize a measure of node purity.
Attribute Selection Criteria
For classification, given a set of samples and classes with proportions , the entropy captures the uncertainty:
The information gain (ID3 algorithm) of splitting on attribute is the reduction in entropy:
Because information gain favours attributes with many distinct values, C4.5 introduces the gain ratio:
The CART algorithm, in contrast, uses the Gini impurity:
which measures the probability of misclassification if a sample were labelled randomly according to the class distribution. For regression trees, splitting decisions are based on the reduction in mean squared error:
Tree-Building Algorithms and Pruning
- ID3 — restricted to categorical features, no missing-value handling, no pruning; it greedily maximizes information gain.
- C4.5 — extends ID3 to numeric attributes (candidate splits are midpoints between sorted values), handles missing values via fractional counts, and uses gain ratio. Post-pruning via error-based pruning simplifies the tree.
- CART — builds binary trees using Gini impurity (classification) or least-squares error (regression). It applies cost-complexity pruning: a sequence of subtrees is generated by minimizing , where is the misclassification/error rate and the number of leaves; is selected by cross-validation.
From an economic perspective, decision trees mirror sequential investment decisions under uncertainty: each internal node represents a "test" that partitions the state space, and the leaf provides the expected payoff of the path. Their interpretability makes them attractive in regulated industries where model transparency is mandatory.
Random Forest and Ensemble Methods
Random Forest is an ensemble of decision trees trained via bagging (Bootstrap Aggregating). Each tree is trained on a bootstrap sample of the data, and at each split, only a random subset of features (typically for classification, for regression) is considered. The final prediction is the majority vote (classification) or average (regression) across all trees. The random feature selection decorrelates the trees, reducing variance:
where is the average pairwise correlation between trees, is the variance of a single tree, and is the number of trees. Reducing through random feature subsets directly reduces ensemble variance.
Boosting trains models sequentially, with each subsequent model focusing on the errors of previous ones. The ensemble prediction is a weighted combination:
AdaBoost adjusts sample weights: , increasing the weight of misclassified points. Gradient Boosting frames boosting as functional gradient descent in function space. At each iteration , a new tree is fit to the negative gradient of the loss function:
XGBoost (Extreme Gradient Boosting) uses a second-order Taylor approximation of the loss:
where and are the first and second order gradients. is a regularization term penalizing tree complexity. XGBoost includes built-in handling of missing values, column subsampling, and shrinkage (learning rate ).
LightGBM uses histogram-based algorithms and leaf-wise tree growth (expanding the leaf with the highest loss reduction) rather than level-wise growth. It introduces Gradient-based One-Side Sampling (GOSS) to retain instances with large gradients while randomly sampling those with small gradients, and Exclusive Feature Bundling (EFB) to bundle mutually exclusive features, dramatically reducing feature dimensionality.
Support Vector Machines (SVM)
Support Vector Machines (SVM) construct a maximum-margin separating hyperplane for binary classification. Given linearly separable data with , the hard-margin SVM solves the convex quadratic program:
The Lagrangian dual reveals that the solution depends only on the subset of training points (the support vectors) with nonzero Lagrange multipliers , and the decision function becomes
When data are not perfectly separable, the soft-margin formulation introduces slack variables :
The parameter controls the trade-off between margin width and classification error. The dual formulation is:
Non-linear SVM and the Kernel Trick
Real-world data are rarely linearly separable. The kernel trick circumvents explicit feature mapping by replacing inner products with a symmetric, positive semi-definite kernel function . By Mercer's theorem, any continuous, symmetric, positive semi-definite kernel corresponds to an inner product in some reproducing kernel Hilbert space (RKHS). Common choices:
- Polynomial kernel:
- Radial Basis Function (RBF) kernel:
- Sigmoid kernel:
The RBF kernel effectively lifts the data into an infinite-dimensional space, enabling highly flexible decision boundaries. The hyper-parameter controls the influence of a single training example: large leads to peaked Gaussians and complex, locally adapted boundaries prone to over-fitting.
Support Vector Regression (SVR)
Support Vector Regression (SVR) adapts the margin principle to regression. SVR fits a tube of radius around the predicted function such that errors smaller than are ignored, while larger deviations incur a linear penalty:
subject to
$ \begin{aligned} y_i - \mathbf{w}^\top \mathbf{x}_i - b &\le \epsilon + \xi_i, \\ \mathbf{w}^\top \mathbf{x}_i + b - y_i &\le \epsilon + \xi_i^*, \\ \xi_i, \xi_i^* &\ge 0. \end{aligned} $The -insensitive loss function creates a sparse solution where only points outside the -tube contribute to the model.
Predictive Modeling with Trees, Support Vectors, and Ensembles
Principal Component Analysis: Variance-Maximizing Projection
Principal Component Analysis (PCA) seeks an orthogonal basis along which the projected data exhibits maximal variance. Let be a mean-centered data matrix. The sample covariance matrix is
We wish to find a unit vector that maximizes the variance of the projection :
Forming the Lagrangian and setting yields the eigenvalue equation
The variance-maximizing direction is the eigenvector associated with the largest eigenvalue . Subsequent components are obtained by repeating the optimization under the additional orthogonality constraint for , producing the ordered spectrum .
Equivalently, PCA can be computed via the singular value decomposition (SVD) , where the right singular vectors are the principal directions and the singular values satisfy . The -dimensional representation is , and the fraction of total variance retained is — a quantity routinely inspected via a scree plot to select .
Practical implementation steps:
- Center the data: subtract the mean of each feature.
- (Optional) Scale to unit variance if features have different units.
- Compute SVD of the centered (and scaled) matrix.
- Project data onto the first right singular vectors.
- Transform new data using the same centering/scaling and projection matrix .
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
pca = PCA(n_components=0.95) # retain 95% variance
X_pca = pca.fit_transform(X_scaled)
print(f"Explained variance ratio: {pca.explained_variance_ratio_}")
print(f"Number of components: {pca.n_components_}")
Intuitively, PCA identifies the axes of greatest spread in the data ellipsoid. In finance, the first principal component of a cross-section of asset returns often proxies the market factor; in macroeconomics, a handful of components summarize hundreds of indicators into "coincident" and "leading" indices. However, PCA has two structural limitations: it is sensitive to feature scaling (necessitating standardization when units differ), and it captures only second-order (linear correlation) structure. Two variables may be uncorrelated yet strongly dependent, a gap that ICA is designed to close.
Independent Component Analysis: Recovering Latent Sources
Independent Component Analysis (ICA) addresses a fundamentally different problem. Suppose we observe signals that are unknown linear mixtures of latent source signals :
where is an unknown mixing matrix. The goal of ICA is to estimate an unmixing matrix such that the recovered components are as statistically independent as possible. Two random variables and are statistically independent if and only if . This condition is strictly stronger than uncorrelatedness ().
Why Non-Gaussianity Is the Key
A central result is that independence can only be identified when the sources are non-Gaussian. The argument rests on two pillars:
- Rotational invariance of the Gaussian. If is a vector of i.i.d. standard Gaussians, then any orthogonal rotation has the same distribution. The mixing matrix is therefore unidentifiable from second-order statistics alone.
- The Central Limit Theorem. A sum (or linear mixture) of independent non-Gaussian variables is more Gaussian than its constituents. Hence, searching for projections of that are least Gaussian recovers the original sources.
This insight converts ICA into an optimization: find such that is maximally non-Gaussian. Two standard measures are used:
- Kurtosis (the fourth standardized cumulant): . Gaussian variables have ; super-Gaussian (sparse, heavy-tailed) sources have ; sub-Gaussian (uniform-like) sources have .
- Negentropy, defined via the differential entropy : where is a Gaussian with the same covariance as . Since the Gaussian maximizes entropy for a given variance, with equality iff is Gaussian.
The FastICA Algorithm
The most widely used ICA solver, FastICA, maximizes an approximation to negentropy through a fixed-point iteration. After whitening to (so that , which PCA provides for free), one iterates for each component:
where or serves as a contrast function approximating negentropy. Convergence is cubic under mild conditions. Two intrinsic ambiguities remain: the order of the components and their sign are indeterminate; ICA recovers sources up to scaling and permutation.
from sklearn.decomposition import FastICA
ica = FastICA(n_components=3, random_state=42)
S_ica = ica.fit_transform(X_scaled)
A_ica = ica.mixing_ # estimated mixing matrix
Contrast with PCA: PCA yields uncorrelated components that maximize variance; ICA yields independent components that capture the data's non-Gaussian structure. In many signals, the interesting structure lives in the tails, not the bulk variance. PCA tends to capture high-variance Gaussian-like noise, while ICA can extract hidden factors, e.g., separating EEG artifacts from brain activity, or identifying latent factors in financial time series. For high-dimensional data, apply PCA to reduce to a manageable number of dimensions (e.g., retaining 99% variance) before ICA to improve stability and computational efficiency.
Dimensionality Reduction: PCA and ICA
Principal Component Analysis (PCA) finds orthogonal directions of maximum variance. The covariance matrix eigendecomposition S w = λ w yields principal components as eigenvectors; the explained variance ratio Σλᵢ/Σλ guides dimensionality choice. PCA can be computed via SVD: X = UΣV^T. PCA is sensitive to scaling and captures only second-order (correlation) structure. Independent Component Analysis (ICA) addresses blind source separation: given mixed signals x = As, find unmixing matrix W ≈ A⁻¹ such that recovered components are maximally independent. ICA relies on non-Gaussianity — since Gaussian variables are rotationally invariant and the Central Limit Theorem implies mixtures are more Gaussian than sources. Optimization uses kurtosis or negentropy-based contrast functions. The FastICA algorithm whitens data, then iteratively maximizes non-Gaussianity using fixed-point iteration. PCA captures variance; ICA captures independence and non-Gaussian structure.