Guided Learning

Learn

Proceed through the chapters in order. Each section develops concepts by definition, role in the workflow, technical basis, practical application, limitations, and relations to adjacent topics. Use the table of contents to navigate within this page.

For reference lookup of individual algorithms and metrics, use the Concept Library.

Chapter 1

Foundations of AI and Machine Learning

This chapter establishes the vocabulary and principles required for every subsequent chapter: how a learning problem is formulated, how data are represented, and how training, validation, testing, and inference are distinguished. Read it before proceeding, because the remaining chapters assume this language.

Scope of AI, Machine Learning, and Deep Learning

Artificial Intelligence, Machine Learning, and Deep Learning

Open in Concept Library →
Definition

Artificial intelligence (AI) denotes systems that perform tasks associated with perception, reasoning, or decision-making. Machine learning (ML) is a subset of AI in which behavior is learned from data rather than encoded explicitly. Deep learning (DL) is a subset of ML that employs neural networks with multiple layers to learn hierarchical representations directly from raw inputs.

Role in the Workflow

These terms describe the scope of methods available before problem definition and model selection. They establish expectations for data requirements, interpretability, and deployment complexity.

Purpose

To distinguish general intelligent systems from data-driven learning, and to distinguish manually engineered representations from representation-learning architectures that dominate modern perception and language tasks.

Technical Basis

ML relies on optimization of parameters against a loss function over a dataset. DL additionally relies on composable nonlinear transformations (layers) trained by gradient-based methods, which allows features to be learned rather than hand-specified.

Practical Application

Tabular business problems often begin with classical ML; unstructured sensory, visual, or textual data often require DL or pretrained transformer models.

Limitations

A broader label does not imply that the most complex method is appropriate. Deep learning in particular requires substantial data, compute, and validation discipline, and frequently underperforms classical models on small structured datasets.

Trade-offs

Increasing the generality of the paradigm typically increases data demand, opacity of internal representations, and operational cost.

Recommended subsequent study: Data and features; Training and inference

Related concepts: Supervised learning; Loss function; Generalization; Deployment constraints

A formal study of machine learning assumes three components: a dataset of observations, a model family parameterized by learnable quantities, and an objective (loss) function minimized through optimization. Generalization—performance on unseen data—depends on problem formulation, data quality, model capacity, and validation discipline, not on the sophistication of the algorithm alone.

Distinction: AI vs ML vs Deep Learning

These are nested categories, not competing ones. Artificial intelligence is the broadest field; machine learning is the subset that learns behavior from data; deep learning is the subset of machine learning that uses multi-layer neural networks to learn representations. A system can be 'AI' without learning from data at all (for example, a hand-written rule engine).

Core Vocabulary: Data, Features, Labels, Models, Parameters

Core entities

  • —Dataset: a collection of samples used for estimation and evaluation.
  • —Feature: a measurable input variable describing each sample.
  • —Label or target: the quantity to be predicted in supervised learning.
  • —Model: a parameterized mapping from inputs to outputs.
  • —Parameters: values learned during training, such as weights and biases.
  • —Hyperparameters: configuration set before training, such as learning rate, tree depth, or the number of neighbors k.

Distinction: Parameters vs Hyperparameters

Parameters are learned by the optimization procedure from the training data (for example, the coefficients of a linear model). Hyperparameters are chosen by the practitioner before training and govern how learning proceeds (for example, regularization strength or tree depth). Hyperparameters are selected using the validation set, never the test set.

Training, Validation, Testing, and Inference

These four activities occur at different points in the lifecycle and must not be conflated. Training adjusts parameters to reduce empirical loss on the training partition. Validation estimates performance during development and guides hyperparameter selection. Testing provides a single, final, unbiased estimate of generalization. Inference is the application of the finished model to new observations in production.

ActivityData usedPurposeHow often
TrainingTraining setEstimate model parametersRepeatedly during development
ValidationValidation set / CV foldsSelect hyperparameters and modelsRepeatedly during development
TestingHeld-out test setFinal unbiased performance estimateOnce, at the conclusion
InferenceNew production inputsGenerate predictions in deploymentContinuously in production

Distinction: Validation vs Testing

The validation set is consulted many times to make modeling decisions, so performance on it becomes optimistically biased. The test set must be touched only once, after all decisions are finalized, to obtain an honest estimate of generalization. Repeatedly evaluating on the test set silently converts it into a validation set.

Loss Minimization and Generalization

Learning is typically cast as minimization of a loss function that measures the discrepancy between predictions and targets—for example, mean squared error for regression or cross-entropy for classification. Optimization (often gradient-based) adjusts parameters to reduce this loss. However, minimizing training loss alone does not guarantee acceptable deployment performance: a model can memorize training data while failing on new inputs.

The central tension: overfitting vs underfitting

A model with too little capacity underfits and cannot capture the underlying pattern; a model with too much capacity overfits and memorizes noise. Regularization, appropriate model capacity, and honest validation are the tools used to find the balance that generalizes.

Chapter 2

AI Generations

Machine learning practice is often grouped into three generations distinguished by how representations are obtained, the data modalities involved, and the scale of deployment. The generations differ in architecture and scale; they share a dependence on data representation, mathematical modeling, optimization, loss minimization, and evaluation.

Three Generations at a Glance

GenerationRepresentationTypical dataPrimary constraint
Gen 1: Classical MLHand-crafted or tabular featuresStructured tablesQuality of feature engineering
Gen 2: Deep neural networksLearned hierarchical featuresImages, audio, sequencesData volume and compute
Gen 3: Transformers and modern AIAttention-based contextText and multimodal corporaCost, safety, and evaluation

What remains constant across all generations

Although the generations differ in architecture and scale, all of them still rely on data representation, mathematical modeling, optimization, loss/error minimization, and evaluation. A transformer and a linear regression are trained by the same underlying principle: define an objective and minimize it on data.

Generation 1: Classical Machine Learning

Definition. Generation 1 comprises algorithms that learn from structured, tabular data using features that a practitioner has engineered explicitly. The model itself is comparatively simple; predictive quality depends heavily on the quality of the features supplied to it.

Profile

  • —Typical data types: structured tables of numeric and categorical variables.
  • —Representative models: Linear Regression, Logistic Regression, SVM, k-NN, Decision Trees, Random Forests, Gradient Boosting.
  • —Strengths: interpretability, fast training, low data and compute requirements, strong performance on tabular problems.
  • —Limitations: requires manual feature engineering; limited ability to model raw perceptual data such as images or audio.

Generation 2: Deep Neural Networks

Definition. Generation 2 replaces hand-crafted features with representations learned automatically through layered neural networks. Convolutional networks learn spatial features from images; recurrent and LSTM networks learn temporal features from sequences.

Profile

  • —Typical data types: images, audio, video, and sequential signals.
  • —Representative models: MLPs, CNNs, RNNs, LSTMs, Autoencoders.
  • —Strengths: learns features directly from raw data; strong performance on perception tasks.
  • —Limitations: requires large labeled datasets and significant compute; reduced interpretability.
  • —What changed from Gen 1: features are learned rather than engineered, shifting effort from feature design to data collection and architecture design.

Generation 3: Transformers and Modern AI

Definition. Generation 3 is defined by the Transformer architecture and attention-based context modeling, combined with large-scale pretraining on broad corpora. Models are frequently pretrained once and then adapted to many downstream tasks.

Profile

  • —Typical data types: text, code, and multimodal corpora at very large scale.
  • —Representative models and systems: Transformers, BERT, GPT, Vision Transformers, large language models (LLMs), retrieval-augmented generation (RAG), agents, and embeddings.
  • —Strengths: transfer learning, broad generalization, and generation across modalities.
  • —Limitations: high training and inference cost; difficult evaluation; safety, reliability, and factuality concerns.
  • —What changed from Gen 2: attention enables long-range context and parallel training; pretraining enables reuse across tasks.

Chapter 3

The Machine Learning Pipeline

The pipeline is a sequential workflow in which each stage produces artifacts consumed by the next. Errors introduced early—particularly in problem definition, data leakage, or preprocessing—propagate to deployment. This chapter explains where each technique belongs in the process, which is the foundation for the chapters that follow.

The Connected Workflow

The pipeline proceeds as follows: Problem Definition → Data Collection → Data Cleaning → Preprocessing → Feature Engineering → Feature Selection / Extraction → Model Selection → Training → Hyperparameter Tuning → Validation → Evaluation → Optimization → Deployment → Monitoring. Each arrow represents an artifact handed to the next stage; understanding these hand-offs is more important than memorizing the names.

Visual Intuition

StageDefinition / roleCommon techniquesOutputCommon errors
Problem DefinitionSpecify the task, target, and success criteriaStakeholder analysis, metric selectionTask type, target, constraints, success metricOptimizing a metric misaligned with the objective
Data CollectionAcquire representative samplesSampling, logging, labelingRaw datasetSampling bias; unrepresentative data
Data CleaningResolve missing, duplicate, or erroneous valuesImputation, deduplication, outlier handlingCleaned datasetDiscarding informative records; silent imputation
PreprocessingTransform inputs into model-ready formScaling, encoding, normalizationFitted transformers (training statistics only)Fitting transforms on the full dataset (leakage)
Feature EngineeringConstruct domain-informed variablesAggregations, interactions, domain transformsEnriched feature setLeaking the target into engineered features
Feature Selection / ExtractionReduce dimensionality or choose informative featuresFilter/wrapper selection, PCA, embeddingsReduced or transformed feature setSelecting features using test labels
Model SelectionChoose a model family appropriate to the dataBaselines, candidate comparisonCandidate model(s)Choosing by popularity rather than fit
TrainingEstimate parameters by minimizing lossGradient descent, tree inductionTrained model artifactTraining on data that overlaps the test set
Hyperparameter TuningSearch configurations that govern learningGrid/random search, Bayesian optimizationSelected hyperparametersTuning against the test set
ValidationEstimate generalization during developmentHold-out, cross-validation, nested CVUnbiased development metricsIgnoring temporal or grouped structure
EvaluationMeasure final performance against the objectiveTask-appropriate metrics on the test setFinal metricsReporting accuracy under class imbalance
OptimizationCompress for efficient inferenceQuantization, pruning, distillationDeployable, efficient modelSkipping accuracy re-validation after compression
DeploymentServe the model in productionAPIs, ONNX, TFLite, embedded CRuntime artifact with documented preprocessingTraining–serving skew
MonitoringTrack performance and drift over timeDrift detection, logging, alertingOperational metrics and alertsAssuming static performance after launch

Critical Distinctions Within the Pipeline

Distinction: Preprocessing vs Feature Engineering

Preprocessing standardizes or encodes raw inputs so they are valid for a model (scaling, imputation, one-hot encoding). Feature engineering creates new, domain-informed variables that expose structure the model could not easily discover on its own (for example, deriving 'transactions per day' from raw timestamps).

Distinction: Feature Selection vs Feature Extraction

Feature selection retains a subset of the original features and discards the rest, preserving interpretability. Feature extraction constructs new features as combinations of the originals (for example, PCA components or learned embeddings), which can be more compact but less interpretable. Conflating the two leads to incorrect pipeline design.

Distinction: Model Parameters vs Hyperparameters (in the pipeline)

Parameters are produced by the Training stage; hyperparameters are chosen by the Hyperparameter Tuning stage using validation data. Keeping these stages separate is what allows the Evaluation stage to remain unbiased.

Principal Component Analysis (PCA)

Open in Concept Library →
Definition

Principal Component Analysis is a feature extraction method that transforms a set of possibly correlated variables into a smaller set of orthogonal components ordered by retained variance.

Role in the Workflow

PCA belongs to feature selection/extraction, after preprocessing (typically scaling) and before model training.

Purpose

To reduce dimensionality, mitigate multicollinearity, and compress information for visualization or downstream modeling.

Technical Basis

PCA identifies directions of maximum variance via eigen-decomposition of the covariance matrix or singular value decomposition (SVD) of the centered data matrix. Each component is a linear projection of the original features.

Practical Application

Applied to continuous, scaled tabular data when linear correlation structure dominates and interpretability of raw features is secondary.

Limitations

Components are linear combinations of original features, which reduces direct interpretability. Nonlinear structure is not captured without extensions (e.g., kernel PCA). Fitting on the full dataset including the test partition induces leakage.

Trade-offs

Variance retention versus loss of nonlinear structure and interpretability; computational efficiency versus fidelity of representation.

Common Errors
  • • Applying PCA without scaling continuous features
  • • Fitting PCA on training and test data jointly

Recommended prior study: Standardization; Covariance and linear algebra

Recommended subsequent study: Linear models on reduced features; Comparison with feature selection

Related concepts: Standardization; Feature selection; Embeddings; Autoencoders

Chapter 4

Model Families

Model families differ in inductive bias, suitable data modality, interpretability, and deployment profile. Model selection should be justified by problem structure and constraints, not by popularity. This chapter surveys the major families and provides formal entries for the most representative members.

Comparison of Model Families

FamilyRepresentative examplesSuitable dataKey strength
Linear modelsLinear Regression, Logistic RegressionTabular, linearly separableInterpretable, efficient
Instance-basedk-NNSmall tabularNo training phase, flexible
Tree-basedDecision TreeMixed tabularInterpretable rules
EnsembleRandom Forest, Gradient BoostingTabularHigh accuracy, robust
Neural networksMLP, CNN, RNN, LSTMImages, audio, sequencesLearned representations
TransformersBERT, GPT, ViTText, multimodalLong-range context
Generative modelsLLMs, diffusion modelsText, imagesSample synthesis

Linear and Instance-Based Models

Linear Models

Open in Concept Library →
Definition

Linear models predict an output as a weighted sum of input features, optionally passed through a link function. Linear regression predicts a continuous value; logistic regression maps the weighted sum through a sigmoid to estimate class probability.

Role in the Workflow

Model selection and training. Linear models are frequently used as interpretable baselines against which more complex families are justified.

Purpose

To model relationships that are approximately linear in the chosen feature space, providing fast training, low memory footprint, and coefficient-level interpretability.

Technical Basis

Parameters are estimated by minimizing a loss function—mean squared error for regression, cross-entropy for logistic regression—often with L1 (lasso) or L2 (ridge) regularization to control overfitting.

Practical Application

Tabular problems with informative engineered features, risk scoring, and any setting in which coefficient interpretation or compact deployment is required.

Limitations

Cannot represent nonlinear interactions without explicit feature construction; sensitive to multicollinearity and to unscaled features when regularized.

Trade-offs

Interpretability and efficiency versus restricted expressive capacity.

Recommended prior study: Loss minimization; Feature scaling

Recommended subsequent study: SVM; Tree-based models

Related concepts: Regularization; Logistic regression; Feature engineering; SVM

k-Nearest Neighbors (k-NN)

Open in Concept Library →
Definition

k-Nearest Neighbors is an instance-based method that assigns a label or value according to the majority vote or average of the k training points closest to the query in feature space.

Role in the Workflow

Model selection; inference requires access to stored training data.

Purpose

Nonparametric classification or regression without an explicit training-phase optimization.

Technical Basis

Distance metrics (e.g., Euclidean) in feature space; lazy learning that defers computation to inference time.

Practical Application

Small datasets, baselines, and teaching illustrations of bias-variance and distance geometry.

Limitations

Inference cost and memory scale with training-set size; performance degrades in high dimensions without careful feature design; requires consistent scaling.

Trade-offs

Simplicity and flexibility versus memory, latency, and the curse of dimensionality.

Common Errors
  • • Omitting feature scaling
  • • Selecting k without cross-validation

Recommended prior study: Distance metrics; Train/validation split

Recommended subsequent study: SVM; Decision trees

Related concepts: Distance metrics; Standardization; Prototype selection; Curse of dimensionality

Tree-Based and Ensemble Models

Decision Tree

Open in Concept Library →
Definition

A Decision Tree partitions the feature space through recursive binary splits that minimize impurity (classification) or error (regression) in the resulting child nodes.

Role in the Workflow

Model selection and training; outputs an interpretable rule structure.

Purpose

Interpretable modeling with mixed feature types and nonlinear decision boundaries.

Technical Basis

Greedy split search using the Gini index, entropy, or mean-squared-error reduction.

Practical Application

When rule-based explanations are required; embedded systems with controlled depth.

Limitations

High variance for a single tree; sensitivity to small data perturbations; overfitting without pruning or ensembling.

Trade-offs

Interpretability versus stability and peak predictive performance.

Recommended prior study: Impurity measures; Overfitting

Recommended subsequent study: Random Forest; Gradient boosting

Related concepts: Random Forest; Information gain; Overfitting; Ensemble methods

Random Forest and Gradient Boosting

Open in Concept Library →
Definition

Ensemble methods combine many trees. Random Forest trains trees on bootstrap samples with random feature subsets and aggregates by voting or averaging. Gradient boosting fits trees sequentially, each correcting the residual errors of the previous ensemble.

Role in the Workflow

Model selection for tabular classification or regression.

Purpose

Reduce the variance of single trees (bagging) or reduce bias by sequential correction (boosting), while maintaining strong performance on structured data.

Technical Basis

Random Forest uses bagging and the random subspace method to decorrelate trees. Gradient boosting performs additive stage-wise optimization of a differentiable loss.

Practical Application

Default strong baselines for tabular problems; gradient boosting frequently achieves state-of-the-art accuracy on structured data.

Limitations

Model size can be large for embedded deployment; less interpretable than a single tree; boosting is sensitive to hyperparameters and can overfit without early stopping.

Trade-offs

Predictive robustness versus model size, training time, and explainability.

Recommended prior study: Decision Tree; Cross-validation

Recommended subsequent study: Model compression; Hardware-aware selection

Related concepts: Decision Tree; Bagging; Boosting; Feature importance

Margin-Based Models

Support Vector Machine (SVM)

Open in Concept Library →
Definition

A Support Vector Machine constructs a decision boundary that maximizes the margin between classes, optionally using kernel functions to represent nonlinear separation in a higher-dimensional space.

Role in the Workflow

Model selection and training for classification (and regression variants).

Purpose

To obtain robust boundaries in medium-dimensional feature spaces with clear margin structure.

Technical Basis

Convex optimization over support vectors; the kernel trick computes inner products in an implicit feature space without explicit transformation.

Practical Application

Medium-scale classification with scaled features; linear SVMs are well suited to compact embedded deployment.

Limitations

Training cost can grow with sample size; kernel selection requires validation; probability calibration may require additional methods.

Trade-offs

Margin quality and flexibility versus training time and tuning complexity.

Recommended prior study: Feature scaling; Binary classification metrics

Recommended subsequent study: Random Forest; Neural networks

Related concepts: Margin; Kernel methods; Logistic regression; Standardization

Neural Networks and Transformers

Neural Networks (MLP, CNN, RNN, LSTM)

Open in Concept Library →
Definition

Neural networks compose layers of nonlinear transformations of learned representations. Multilayer perceptrons (MLPs) operate on vectors; convolutional networks (CNNs) exploit spatial locality; recurrent networks (RNNs) and Long Short-Term Memory (LSTM) units model sequential state.

Role in the Workflow

Model selection and training for perception and sequence tasks; the basis of deep learning.

Purpose

To learn hierarchical features directly from raw inputs such as images, audio, and sequences.

Technical Basis

Parameters are trained by backpropagation of gradients of a loss function. Convolutions share weights across spatial positions; recurrent and LSTM units maintain and gate state across time steps.

Practical Application

Image classification (CNN), time series and speech (RNN/LSTM), and general nonlinear function approximation (MLP).

Limitations

Require substantial labeled data and compute; reduced interpretability; sensitive to architecture and optimization choices; prone to overfitting without regularization.

Trade-offs

Representational power versus data demand, compute, and transparency.

Recommended prior study: Linear models; Loss minimization

Recommended subsequent study: Transformer architecture; Model compression

Related concepts: Backpropagation; Autoencoders; Transformers; Regularization

Transformer Architecture

Open in Concept Library →
Definition

The Transformer is a neural architecture that models sequences using self-attention and position-aware representations rather than recurrent state alone.

Role in the Workflow

Model selection for language, code, and many multimodal tasks; pretraining followed by fine-tuning.

Purpose

Capture long-range dependencies and contextual relationships at scale, with parallelizable training.

Technical Basis

Multi-head self-attention computes weighted combinations of token representations; feed-forward layers, residual connections, and normalization stabilize training.

Practical Application

Natural language processing, code models, Vision Transformers (ViT), and large-scale generative systems.

Limitations

Quadratic memory in sequence length; high training and inference cost; evaluation and safety challenges at scale.

Trade-offs

Representational power versus compute, memory, and operational risk.

Recommended prior study: Neural networks; Embeddings

Recommended subsequent study: LLMs; RAG

Related concepts: Attention; Embeddings; BERT; GPT; Fine-tuning

Attention and Self-Attention

Open in Concept Library →
Definition

Attention computes a weighted aggregation of values based on the compatibility between queries and keys, allowing the model to emphasize relevant inputs. Self-attention applies this mechanism within a single sequence so that each element attends to every other element.

Role in the Workflow

Core computation within Transformers and many encoder-decoder models.

Purpose

Dynamic, input-dependent focus across sequence elements or modalities.

Technical Basis

Scaled dot-product attention: softmax(QKᵀ/√d)V; multi-head attention projects into parallel subspaces and concatenates the results.

Practical Application

Machine translation, language modeling, and Vision Transformers.

Limitations

Computational and memory cost grows quadratically with sequence length.

Trade-offs

Contextual modeling capacity versus resource requirements.

Recommended prior study: Linear algebra; Sequence models

Recommended subsequent study: Transformers; LLMs

Related concepts: Self-attention; Transformer; Embeddings; Positional encoding

Generative Models

Generative Models

Open in Concept Library →
Definition

Generative models learn the structure of a data distribution well enough to produce new samples that resemble the training data. Examples include large language models for text, diffusion models for images, and autoencoder-based methods for compact latent representations.

Role in the Workflow

Model selection for synthesis, augmentation, and representation tasks; frequently used through pretrained checkpoints.

Purpose

To synthesize plausible data, learn reusable representations, or condition generation on prompts or retrieved context.

Technical Basis

Language models are trained by next-token prediction; diffusion models learn to reverse a gradual noising process; autoencoders reconstruct inputs through a bottleneck. All optimize a likelihood or reconstruction objective.

Practical Application

Text generation and summarization, image synthesis, data augmentation, and anomaly detection through reconstruction error.

Limitations

May produce confident but incorrect output (hallucination); evaluation is difficult because there is no single ground-truth target; training cost is high.

Trade-offs

Flexibility and creativity versus controllability, factual reliability, and evaluation difficulty.

Recommended prior study: Neural networks; Transformer architecture

Recommended subsequent study: RAG; Evaluation of generative systems

Related concepts: LLMs; Diffusion models; Autoencoders; Hallucination

Chapter 5

Evaluation and Validation

Evaluation is not the act of reporting a single number; it is a controlled process for determining whether a model generalizes reliably. This chapter explains why metric selection must match the task objective, why accuracy alone is insufficient, and how validation methodology protects against optimistic bias.

Matching Metrics to the Objective

Metric selection should reflect the task objective, the class distribution, the risk level, and the relative cost of false positives and false negatives. A medical screening test that must not miss positive cases prioritizes recall; a spam filter that must not discard legitimate mail prioritizes precision. Reporting a single metric without reference to these factors obscures the actual operational behavior of the model.

Why accuracy alone is insufficient

On an imbalanced dataset where 99% of cases are negative, a model that always predicts 'negative' achieves 99% accuracy while detecting nothing of interest. Accuracy is meaningful only when classes are balanced and the costs of the two error types are symmetric.

The Confusion Matrix and Classification Metrics

Most classification metrics are derived from the confusion matrix, which tabulates predictions against actual labels into true positives, false positives, true negatives, and false negatives. Precision, recall, specificity, and F1 are different summaries of this same table; ROC-AUC summarizes ranking quality across all decision thresholds rather than at a single one.

Visual Intuition

Visual Intuition

Classification Metrics: Accuracy, Precision, Recall, Specificity, F1

Open in Concept Library →
Definition

Accuracy is the proportion of correct predictions. Precision is the proportion of predicted positives that are true positives. Recall (sensitivity) is the proportion of actual positives correctly identified. Specificity is the proportion of actual negatives correctly identified. F1-score is the harmonic mean of precision and recall.

Role in the Workflow

Evaluation stage, after model training and threshold selection.

Purpose

Metric selection should reflect the task objective, class distribution, risk level, and the relative cost of false positives and false negatives.

Technical Basis

All quantities are derived from the confusion matrix of true/false positives and negatives. F1 balances precision and recall when both error types matter; ROC-AUC summarizes ranking quality across all thresholds.

Practical Application

Use accuracy only when classes are balanced and misclassification costs are symmetric; use precision, recall, F1, and ROC-AUC under class imbalance or asymmetric costs.

Limitations

A single metric summarizes away the operational threshold choice; accuracy can mask failure on rare but important classes.

Trade-offs

Simplicity of reporting versus alignment with domain-specific costs.

Recommended prior study: Confusion matrix

Recommended subsequent study: ROC-AUC; Cost-sensitive learning

Related concepts: Confusion matrix; ROC-AUC; Class imbalance; Threshold tuning

Regression Metrics

Regression Metrics: MAE, RMSE, R²

Open in Concept Library →
Definition

Mean Absolute Error (MAE) is the average absolute difference between predictions and targets. Root Mean Squared Error (RMSE) is the square root of the average squared difference. The coefficient of determination (R²) is the proportion of variance in the target explained by the model.

Role in the Workflow

Evaluation stage for continuous-valued prediction tasks.

Purpose

To quantify the magnitude of prediction error and the explanatory power of a regression model.

Technical Basis

MAE treats all errors linearly; RMSE squares errors and therefore penalizes large deviations more heavily; R² compares model error against the variance of a naive mean predictor.

Practical Application

Report MAE when the cost of error scales linearly and outliers should not dominate; report RMSE when large errors are disproportionately costly; report R² to communicate relative explanatory power.

Limitations

R² can be misleading on nonlinear relationships and can be inflated by adding predictors; RMSE is sensitive to outliers.

Trade-offs

Robustness to outliers (MAE) versus sensitivity to large errors (RMSE).

Recommended prior study: Loss minimization

Recommended subsequent study: Cross-validation; Residual analysis

Related concepts: Loss function; Overfitting; Cross-validation

Validation Methodology and Test-Set Discipline

A train/test split sets aside data for a final estimate; a validation set (or cross-validation) supports model and hyperparameter selection without consuming the test set. Nested cross-validation separates tuning from performance estimation when hyperparameters are optimized. Stratified folds preserve class proportions; temporal data require splits that respect time ordering.

Visual Intuition

Cross-Validation and Nested Cross-Validation

Open in Concept Library →
Definition

Cross-validation partitions data into multiple folds, repeatedly training on subsets and evaluating on held-out folds to estimate generalization performance. Nested cross-validation adds an inner loop for hyperparameter selection so that tuning does not contaminate the performance estimate.

Role in the Workflow

Validation stage; supports model and hyperparameter selection.

Purpose

Obtain more stable performance estimates than a single split, especially with limited data, and separate tuning from final estimation.

Technical Basis

Resampling from the training distribution; stratification preserves class proportions in classification; the outer loop of nested CV estimates generalization while the inner loop selects hyperparameters.

Practical Application

Hyperparameter tuning and model comparison before final test evaluation.

Limitations

Computationally expensive; produces invalid estimates if folds ignore temporal or grouped structure; must remain separate from the final test set.

Trade-offs

Estimate reliability versus computational cost.

Common Errors
  • • Tuning on the test set
  • • Leakage within folds from global preprocessing

Recommended prior study: Train/test split

Recommended subsequent study: Data leakage; Final test evaluation

Related concepts: Train/test split; Nested cross-validation; Data leakage; Stratification

Data Leakage

Open in Concept Library →
Definition

Data leakage occurs when information from outside the training set—including test data or future observations—influences training, preprocessing, or model selection, producing optimistically biased performance estimates.

Role in the Workflow

Affects the validation, preprocessing, and feature engineering stages.

Purpose

Recognition of leakage is necessary to ensure that reported metrics reflect deployable generalization.

Technical Basis

Statistical dependence introduced by improper partitioning or by fitting transformations on pooled data.

Practical Application

Audit pipelines before publication or deployment; fit scalers and feature selectors on training data only.

Limitations

Leakage can be subtle in temporal, grouped, or pipeline-transformed data.

Trade-offs

Convenience of global transforms versus validity of evaluation.

Common Errors
  • • Scaling before splitting
  • • Feature selection using test labels

Recommended prior study: Train/validation/test splits

Recommended subsequent study: Nested cross-validation; Pipeline versioning

Related concepts: Cross-validation; Test-set discipline; Preprocessing

Handling class imbalance

Under class imbalance, prefer precision, recall, F1, and ROC-AUC over accuracy, and consider resampling, class weights, or threshold adjustment. Crucially, any resampling must be applied within cross-validation folds—never before the split—to avoid leakage.

Chapter 6

Optimization and Deployment

After a model is trained and validated, it must be made efficient enough to run under practical constraints and then served reliably. Deployment is not only the question of whether a model runs; it is whether the model runs reliably under constraints such as latency, memory, firmware size, numerical precision, and available hardware support.

Model Compression Methods

Compression reduces the size and inference cost of a trained model so that it fits the deployment target. The three principal techniques—quantization, pruning, and knowledge distillation—are frequently combined, and each must be followed by re-validation of accuracy on representative data.

Visual Intuition

Quantization

Open in Concept Library →
Definition

Quantization maps model weights and activations from floating-point to lower-precision representations (e.g., int8) to reduce storage and accelerate inference.

Role in the Workflow

Optimization/compression, after training and before deployment.

Purpose

Meet memory, latency, and energy constraints on edge and microcontroller hardware.

Technical Basis

Linear quantization with a scale and zero-point, applied either post-training or through quantization-aware training.

Practical Application

Mobile, embedded, and microcontroller deployment, after accuracy validation on representative data.

Limitations

May reduce accuracy; numerical behavior must be verified on the target hardware.

Trade-offs

Efficiency versus fidelity of predictions.

Common Errors
  • • Deploying quantized models without sample-level parity checks

Recommended prior study: Trained float model baseline

Recommended subsequent study: TFLite Micro; Embedded verification

Related concepts: Pruning; Knowledge distillation; TensorFlow Lite; Deployment verification

Pruning

Open in Concept Library →
Definition

Pruning removes weights, neurons, or structures with low estimated contribution to the model output.

Role in the Workflow

Optimization/compression between training and deployment.

Purpose

Reduce model size and inference cost while preserving acceptable accuracy.

Technical Basis

Magnitude-based or structured pruning, with optional fine-tuning to recover lost accuracy.

Practical Application

Neural network compression for edge inference.

Limitations

May require retraining; unstructured sparsity may not accelerate inference without hardware support.

Trade-offs

Sparsity and size versus the effort required to recover accuracy.

Recommended prior study: Trained neural network

Recommended subsequent study: Quantization; Hardware benchmarking

Related concepts: Quantization; Knowledge distillation; Model compression

Knowledge Distillation

Open in Concept Library →
Definition

Knowledge distillation trains a small 'student' model to reproduce the behavior of a larger, more accurate 'teacher' model, using the teacher's output distribution as a richer training signal than hard labels alone.

Role in the Workflow

Optimization/compression, producing a deployable model from a larger trained reference.

Purpose

Transfer the predictive quality of a large model into a compact model suitable for constrained deployment.

Technical Basis

The student minimizes a loss that combines the true labels with the teacher's softened probability outputs (soft targets), which convey inter-class similarity information.

Practical Application

Producing compact language or vision models for mobile and edge inference.

Limitations

Requires a trained teacher and additional training; the student rarely matches the teacher exactly.

Trade-offs

Compactness versus a typically small accuracy gap relative to the teacher.

Recommended prior study: Trained teacher model

Recommended subsequent study: Quantization; Deployment verification

Related concepts: Quantization; Pruning; Model compression

Export Runtimes and Embedded Integration

Common deployment targets

  • —API or cloud serving for scalable, latency-tolerant inference.
  • —ONNX: an open exchange format that decouples training frameworks from runtimes for portability.
  • —TensorFlow Lite: optimized inference for mobile and edge devices.
  • —TensorFlow Lite Micro: inference on microcontrollers with static memory allocation.
  • —Embedded C deployment: hand-integrated inference for the most constrained or specialized firmware.

Hardware-Aware Model Selection

Open in Concept Library →
Definition

Hardware-aware model selection chooses algorithms and model configurations according to the latency, SRAM, flash, firmware size, and energy budgets of the target device—not accuracy alone.

Role in the Workflow

Model selection and optimization prior to final deployment sign-off.

Purpose

Ensure the chosen model is deployable and verifiable on production hardware.

Technical Basis

Profiling inference time and memory; comparing numeric pipelines across runtimes and precisions.

Practical Application

Embedded ML, mobile, and fixed-function accelerators.

Limitations

Early estimates may diverge from final integrated firmware without on-device measurement.

Trade-offs

Predictive performance versus deployability constraints.

Recommended prior study: Problem constraints definition

Recommended subsequent study: Deployment verification; Monitoring

Related concepts: TinyML; Quantization; k-NN memory footprint; Random Forest size

Deployment verification

Verification should include sample-level comparison of predictions across the training framework, the exported intermediate runtime, and final device execution. Preprocessing must be versioned and shipped with the model to prevent training–serving skew, in which the data seen in production differs subtly from the data seen during training.

Chapter 7

Modern AI and Large Language Models

Modern AI systems combine large pretrained Transformers with retrieval, fine-tuning, and agentic orchestration. Despite their scale, these systems rest on the same core ideas developed in earlier chapters: representation, optimization, data, evaluation, and deployment constraints. Evaluation must address faithfulness, safety, and cost in addition to fluency.

From Text to Representation

A language model first segments text into tokens, then maps those tokens to embeddings, then mixes information across the sequence using attention. These three steps—tokenization, embedding, attention—are the bridge between raw text and the Transformer layers studied in the Model Families chapter.

Visual Intuition

Tokenization

Open in Concept Library →
Definition

Tokenization segments raw text into discrete units (tokens) such as subwords, which are then mapped to integer identifiers consumable by a language model.

Role in the Workflow

Input representation for language models, preceding embedding lookup.

Purpose

Convert unbounded text into a fixed vocabulary of units that balance vocabulary size against sequence length.

Technical Basis

Subword algorithms (e.g., byte-pair encoding) learn frequent character sequences so that rare words decompose into known pieces.

Practical Application

All Transformer-based language and code models; token counts determine context-window usage and cost.

Limitations

Tokenization choices affect sequence length, multilingual coverage, and the handling of numbers and code.

Trade-offs

Vocabulary size versus sequence length and coverage of rare terms.

Recommended prior study: Text preprocessing

Recommended subsequent study: Embeddings; Attention

Related concepts: Embeddings; Transformer; Context window

Embeddings

Open in Concept Library →
Definition

Embeddings are dense vector representations of discrete objects (tokens, documents, users, items) positioned so that semantic similarity corresponds to geometric proximity.

Role in the Workflow

Feature extraction and representation for retrieval, classification, and generation.

Purpose

Encode meaning in a continuous space suitable for neural computation and similarity search.

Technical Basis

Learned lookup tables or contextual encoders trained with language-modeling or contrastive objectives.

Practical Application

Information retrieval, RAG, recommendation, and transfer learning.

Limitations

Quality depends on the training corpus and domain match; large collections require storage and index maintenance.

Trade-offs

Expressiveness versus the infrastructure required for vector search.

Recommended prior study: Tokenization; Linear algebra

Recommended subsequent study: RAG; Fine-tuning

Related concepts: Tokenization; RAG; Vector database; BERT

Systems Built on Language Models

Large language models are Transformer-based models trained on broad corpora by next-token prediction. Practical systems extend them in three principal ways: retrieval grounds generation in external knowledge (RAG); fine-tuning adapts the model to a domain; and agents allow the model to invoke tools and act over multiple steps.

Retrieval-Augmented Generation (RAG)

Open in Concept Library →
Definition

RAG retrieves relevant documents or passages at inference time and conditions a generative model on that evidence to produce grounded outputs.

Role in the Workflow

Deployment architecture combining retrieval systems with language models.

Purpose

Ground generation in external, updatable knowledge and reduce reliance on parametric memory alone.

Technical Basis

Embedding-based retrieval from a vector database, followed by attention-conditioned generation; chunking and ranking strongly affect recall.

Practical Application

Enterprise question answering, documentation assistants, and knowledge bases.

Limitations

Retrieval quality bounds answer quality; index search adds latency; corpora require maintenance.

Trade-offs

Grounding and freshness versus system complexity.

Recommended prior study: Embeddings; LLM basics

Recommended subsequent study: Agents; Monitoring

Related concepts: Vector database; Embeddings; LLM; Faithfulness evaluation

Fine-Tuning and LoRA

Open in Concept Library →
Definition

Fine-tuning adapts a pretrained model to a specific task or domain by continued training on task data. Parameter-efficient methods such as Low-Rank Adaptation (LoRA) update a small number of additional parameters while keeping the original weights frozen.

Role in the Workflow

Adaptation stage between pretraining and deployment.

Purpose

Specialize a general model to a domain without the cost of training from scratch.

Technical Basis

LoRA injects low-rank weight updates into selected layers, dramatically reducing the number of trainable parameters and memory required for adaptation.

Practical Application

Domain-specific assistants, classification on top of pretrained encoders, and instruction tuning.

Limitations

Requires representative task data; full fine-tuning is costly and can degrade general capabilities (catastrophic forgetting).

Trade-offs

Adaptation quality versus compute, data requirements, and the risk of overfitting.

Recommended prior study: Transformer architecture; Embeddings

Recommended subsequent study: Evaluation; Deployment

Related concepts: Transfer learning; Embeddings; RAG; Catastrophic forgetting

Agents and Tool Use

Open in Concept Library →
Definition

An agent is a system that uses a language model to plan and execute multi-step tasks, invoking external tools—search, code execution, APIs, or databases—and incorporating their results into subsequent reasoning.

Role in the Workflow

Deployment-level orchestration built on top of language models and retrieval.

Purpose

Extend a model beyond text generation to act on external systems and complete goal-directed tasks.

Technical Basis

Structured prompting and output parsing route model decisions to tool calls; results are fed back into the context for the next step.

Practical Application

Automated research assistants, code agents, and workflow automation.

Limitations

Error compounding across steps, difficulty of evaluation, latency and cost of multiple model calls, and safety considerations for tool access.

Trade-offs

Autonomy and capability versus reliability, cost, and control.

Recommended prior study: LLM basics; RAG

Recommended subsequent study: Monitoring; Evaluation of generative systems

Related concepts: Tool use; RAG; Hallucination; Evaluation challenges

Hallucination and Evaluation Challenges

Hallucination denotes confident but incorrect generation. Because generative outputs have no single ground-truth target, evaluation is intrinsically harder than for classification or regression. Mitigation includes retrieval grounding, constrained tool use, human review for high-stakes decisions, and task-specific evaluation protocols that go beyond a single scalar metric.

The same principles, at a larger scale

RAG depends on embedding quality and retrieval recall; fine-tuning is optimization against a loss on domain data; deployment is bounded by latency and cost. Modern AI does not abandon the foundations—it applies them under more demanding constraints.

Chapter 8

TinyML and Embedded AI

Embedded AI operates under strict resource ceilings. Model selection and compression must be co-designed with the firmware architecture and confirmed by measurement on the target hardware. This chapter connects the earlier material directly to embedded machine learning research and practice.

Microcontroller Constraints

Implementation considerations

  • —Latency: the maximum allowable inference time per decision cycle.
  • —Flash: upper bound on stored program and model weights.
  • —SRAM: upper bound on activations and working memory during inference.
  • —Firmware size: total binary impact, including the runtime and the model.
  • —Numeric precision: the effect of quantization on output fidelity.
  • —Power and energy: duty cycle and battery lifetime.

TinyML and Embedded Machine Learning

Open in Concept Library →
Definition

TinyML denotes machine learning inference on microcontrollers and severely resource-constrained devices, where memory, energy, and latency budgets dominate design.

Role in the Workflow

Deployment under hardware constraints; typically follows compression and verification.

Purpose

Enable on-device inference without cloud dependency for privacy, latency, or connectivity reasons.

Technical Basis

Quantized operators, static memory allocation, and toolchain export (e.g., TensorFlow Lite Micro) integrated with C firmware.

Practical Application

Sensors, wearables, and industrial controllers.

Limitations

Limited model capacity; restricted operator sets; mandatory verification against training-framework predictions.

Trade-offs

Autonomy and efficiency versus model capability.

Common Errors
  • • Optimizing only for accuracy
  • • Skipping parity checks between Python, exported C, and device output

Recommended prior study: Quantization; Compact classical models

Recommended subsequent study: On-device monitoring

Related concepts: Quantization; Hardware-aware selection; Python-to-C verification

Model Trade-offs Under Constraints

On constrained devices, model choice is governed as much by memory and latency as by accuracy. The following trade-offs frequently determine which model is deployable.

Visual Intuition

ModelEmbedded strengthEmbedded limitation
Linear SVMCompact and efficient; few parametersLimited flexibility for nonlinear problems
Decision TreeFast and interpretableSize can grow with depth
Random ForestImproves robustness over a single treeIncreases memory and firmware cost
k-NNSimple to implementMemory-heavy: stores training examples
Neural networkPowerful representation learningOften requires quantization or specialized deployment tools

Hardware-Aware Model Selection

Open in Concept Library →
Definition

Hardware-aware model selection chooses algorithms and model configurations according to the latency, SRAM, flash, firmware size, and energy budgets of the target device—not accuracy alone.

Role in the Workflow

Model selection and optimization prior to final deployment sign-off.

Purpose

Ensure the chosen model is deployable and verifiable on production hardware.

Technical Basis

Profiling inference time and memory; comparing numeric pipelines across runtimes and precisions.

Practical Application

Embedded ML, mobile, and fixed-function accelerators.

Limitations

Early estimates may diverge from final integrated firmware without on-device measurement.

Trade-offs

Predictive performance versus deployability constraints.

Recommended prior study: Problem constraints definition

Recommended subsequent study: Deployment verification; Monitoring

Related concepts: TinyML; Quantization; k-NN memory footprint; Random Forest size

Python-to-C-to-Device Verification

Numerical behavior can diverge between a training framework and an embedded target. A disciplined verification flow detects such divergence before it reaches production.

Verification flow

  • —Record Python predictions on a fixed test set in the training framework.
  • —Compare exported C (or TensorFlow Lite Micro) predictions on identical inputs.
  • —Compare on-device predictions on the same inputs.
  • —Perform a sample-by-sample comparison and document any divergence and the acceptable tolerance.

Verification flow, in one line

Python predictions → exported C predictions → device predictions → sample-by-sample comparison. Parity across all three stages is the evidence that the deployed model behaves as validated.