Shahid Beheshti University · MSc · 14 chapters

Advanced
Mathematical Software

The whole course, compressed: from cleaning a CSV to solving differential equations with neural networks. Arrow keys to move, T for contents, R to hide formulas and quiz yourself, M for the deep dive on each slide.

Notes by · lectures by Prof. Kurosh Parand · Shahid Beheshti University · Spring 2026
Reconstructed from the 29 recorded lectures (Persian) — transcribed and distilled with AI.
Course project: Pima Indians Diabetes classification · Final project: PINN / KAN equation solving.

Part I · Chapters 1–2

Foundations

I

CH 01 · Analytics landscape · AI hierarchy & attention

One word, three meanings — that's what attention buys you

Self-attention lets every token vote on what its neighbors mean. Generative ≠ Transformer — GANs and LSTMs generate without it; attention is what made the current LLM wave possible.

AI ML DL GENERATIVE AI LLM diffusion / image model — not LLM
self-attention — the شیر (shir) example $$ \text{Attention}(Q,K,V) = \text{softmax}\!\left(\frac{QK^{T}}{\sqrt{d_k}}\right)V $$

شیر means lion, milk, or tap — "farm/cow" vs "cage/roar" vs "sink/drip" nearby pulls it toward the right one. Context decides, not the word alone.

positional encoding $$ PE_{(pos,2i)} = \sin\!\left(\frac{pos}{10000^{2i/d}}\right) $$

Attention alone sees a set, not a sequence — sine/cosine encodings (cos on the odd dims) restore word order.

generative ≠ transformer

GANs and LSTMs generate content with zero self-attention. What's new isn't "generative" — it's the Transformer itself.

CH 01 · Analytics landscape · Data-driven orgs & analytics types

What happened isn't the interesting question — what should we do about it is

Analytics forms a staircase: descriptive and diagnostic look backward, predictive/prescriptive/advanced look forward. The course's first project sits on the predictive step.

what happened? why did it happen? what's likely next? what should we do? can it act alone? DESCRIPTIVE DIAGNOSTIC PREDICTIVE course starts here PRESCRIPTIVE ADVANCED cognitive / autonomous

Descriptive → Diagnostic → Predictive → Prescriptive → Advanced — each step asks a harder question of the same data.

the value pipeline $$ \text{Data} \rightarrow \text{Information} \rightarrow \text{Knowledge} \rightarrow \text{Model} \rightarrow \text{Money} $$

Skip the middle stops and a data-rich org still never sees the money — that takes a data-driven culture, not just data.

analyst vs. data scientist

The Analyst turns a CEO's business question into a data question; the Data Scientist builds the model. Framing in, communicating out.

health analytics, end to end

Alzheimer's staging from MRI/fMRI (predictive); drug discovery modeled with differential equations. One domain, five kinds of analytics.

CH 01 · Analytics landscape · Pima dataset & preprocessing

Nine columns, one target — but cleaning comes before modeling

768 Pima Indians Diabetes records, 8 predictor features plus one binary Outcome. Predictive analytics starts with prep, not algorithms.

RAW PIMA CSV 768 rows × 9 cols PRE-PROCESS clean — missing values, errors select — relevant features reduce — dimensionality transform — scale / encode (integrate — skipped, single file) CLASSIFIER SVM · DT · LR · RF · NB · LDA · KNN · MLP OUTCOME 0 = non-diabetic · 1 = diabetic
Pima Indians Diabetes — 768 × 9

8 features (Pregnancies … Age) → Outcome (0 = non-diabetic, 1 = diabetic). Women aged 21+, sourced from Kaggle.

feature = field = dimension = variable = attribute

Five words, one idea: a single column in the dataset. Literature uses them interchangeably — don't let vocabulary fool you.

classification roundup (theory deferred)

SVM · Decision Trees · Logistic Regression · Random Forest · Naive Bayes · LDA · Ensembles · KNN · MLP.

CH 02 · Optimization & parallel · Taxonomy & complexity

Every ML tool is optimization — in disguise

SVM training, PCA, and LDA all reduce to optimizing an objective under constraints — the axes you classify a problem on decide which complexity class, and which solvers, apply.

three independent axes classify a problem feasible region constrained unconstrained objective linear nonlinear most real ML objectives domain continuous integer / combinatorial → NP-Hard
optimization problem — the general form $$\text{optimize } f(x) \quad \text{s.t.} \quad g_i(x)\ \{\le,=,\ge\}\ 0$$

Phenomenon → data → model: SVM, PCA, and LDA are this same shape underneath. Name the objective and constraints, and the solver menu follows.

classmeans
Psolvable in polynomial time
NPa solution is verifiable in polynomial time
NP-Completehardest core of NP — every NP problem reduces to it
NP-Hard≥ as hard as NP; need not even be checkable fast

CH 02 · Optimization & parallel · Exact vs. approximate

Optimal costs time — Branch & Bound proves it

NP-Hard problems force a trade: exact algorithms guarantee the best answer; heuristics trade that guarantee for speed.

LP relaxation branch: x₁=0 branch: x₁=1 x₂=0 x₂=1 optimal ILP solution bound ≤ best found → pruned branch: partition the space · bound: discard subtrees that can't win

exact, not exhaustive — the right subtree is never fully explored

GreedyDynamic ProgrammingBacktrackingBranch & Bound — for ILP
Branch & Bound — exact, yet fast enough to matter $$\text{ILP: } \max\; c^Tx \quad \text{s.t.} \quad Ax\le b,\; x\in\mathbb{Z}^n$$

Branch: partition on a fractional variable. Bound: drop any subproblem that can't beat the best solution found — no exhaustive search, still optimal.

exactness has a price — even B&B can stall

A real instance from the lecture took up to 13 days to solve exactly. Past some size, even mature commercial ILP solvers stop returning useful answers — teams fall back to heuristics.

CH 02 · Optimization & parallel · Flynn & memory models

Parallelism has two independent labels — Flynn, then memory

Flynn's taxonomy classifies instruction/data streams; shared vs. distributed memory is a second, orthogonal axis — a system can be any combination of both.

single data multiple data single instr. multiple instr. SISD classical sequential SIMD one op → whole matrix e.g. GPU MISD no real system built MIMD multi-core, now standard
shared memory — one address space, many cores

Independent cores — own compute, control, registers — but one shared memory all of them access. This is what "multi-core system" means.

distributed memory — no shared address space

Each node owns private memory; nodes exchange data over an interconnect via message passing (MPI-style).

heterogeneous — neither model fits cleanly

GPUs: thousands of light cores built for SIMD-style matrix work. FPGAs too. At scale: Spark, Hadoop.

CH 02 · Optimization & parallel · Dependencies & load balance

RAW is the real bottleneck — balance decides the rest

True data dependency can't be removed by any trick; how evenly you split the remaining work decides how much speedup you actually get.

RAW — read-after-write, the true dependency

1: A = E + C
2: D = A + C
Instr 2 needs A from instr 1 — genuinely can't parallelize; no renaming trick removes this.

hazardcausefixable?
RAWread needs a prior writeno — structural
WARwrite must wait for a readyes — renaming
WAWtwo writes, order mattersyes — renaming
sequential 17 units naive split · 4 workers 14 workers 2–4 idle before 14 balanced split · tighter, not perfect less idle, still not zero
mutexsemaphorecondition variablemonitorbarrier

Part II · Chapters 3–5

Working with Data

II

CH 03 · Preprocessing · Zeros that lie

A clean CSV is not clean data — zero can mean "never measured"

Pima's isnull() reports zero nulls everywhere. That's the trap. Garbage in, garbage out.

BloodPressure count impossible real values start here 0
disguised missing — not a real 0

A living patient cannot have BloodPressure = 0. Same story for Glucose, SkinThickness, Insulin, BMI — isnull() never sees it.

the fix, in order

replace(0, np.nan) first, then fillna(median) — never fill a raw zero, or you bias every statistic computed before the fix.

CH 03 · Preprocessing · Impute, don't drop

Dropping a row throws away seven good features to punish one bad one

The right statistic follows from data type and outliers — never from convenience.

methoduse when
meannumeric, no outliers
mediannumeric, outliers present
modecategorical (nominal/ordinal)
ffill / bfilltime-ordered data
why mean breaks — one outlier, big lie

19 students earn 10–30M Toman/mo, one earns 1B. Mean ≈ 100M — meaningless. Median ignores the extreme entirely.

conditional imputation — condition on a related feature

Missing BloodPressure for a 50-year-old? Use the mean BloodPressure of other ~50-year-olds, not the whole dataset's mean.

preserves size → 768 rows stay 768 preserves shape → median keeps distribution drop risk → shrinks an already-small set

CH 03 · Preprocessing · Skew fools the Z-score

Skew fools the Z-score — median-based methods don't bend

Same masking problem, same fix, downstream: this is why RobustScaler exists.

IQR: outlier z-score: missed Q1 Q3 median Insulin (right-skewed)

Skew inflates mean/σ, so ordinary z-score masks the same point IQR flags.

IQR rule — the robust default $$x < Q_1 - 1.5\,IQR \ \text{ or }\ x > Q_3 + 1.5\,IQR$$

Flags dozens in SkinThickness, almost none in Glucose.

modified Z-score — median + MAD $$M_i = \frac{x_i - \tilde{x}}{MAD}$$

Median and MAD resist extremes, so skew can't mask the outlier the way $\mu,\sigma$ do.

CH 04 · Visualization · Choosing the right chart

Match the chart to the question — not the data to a default

Audience, purpose, and data type decide the chart — and data type even limits which statistics are valid. A "mean gender" is meaningless.

variable categorical (nominal / ordinal) numerical (interval / ratio) mode + median if ordinal mean · median · mode · var · std · skew bar · column · pie hist · KDE · box/scatter

Data type gates both the valid statistics and the valid chart family.

Data type — what statistics are even valid
typevalid stats
nominal / binarymode only
ordinalmode, median
interval / ratiomean, median, mode, var, skew

Categorical → mode (± median); numerical unlocks mean, variance, skew.

Goal → chart family
comparison → bar/column composition → pie distribution → hist/KDE trend → line relationship → scatter/heatmap

CH 04 · Visualization · Scaling, engineering & imbalance

What you plot depends on what you did first — scaling, engineering, imbalance

Visualization runs on data that's already been transformed — and is often the tool that reveals a transformation is needed. One oversized feature can drown out all the rest.

500 non-diab. 268 diabetic

768 Pima records: 500 vs 268 — "always negative" still looks accurate.

Euclidean distance — why scale at all $$ d(x,y) = \sqrt{\sum_i (x_i - y_i)^2} $$

One oversized feature dominates the sum regardless of relevance — scale first.

Two fixes $$ z=\frac{x-\mu}{\sigma} \qquad x'=\frac{x-x_{\min}}{x_{\max}-x_{\min}} $$

Standardize to mean 0, sd 1 (≈99.7% within [-3,3]); min–max maps into [0,1].

Feature engineering — a double edge

BMI → underweight/normal/overweight/obese speeds learning — unless the threshold assumption is wrong.

CH 04 · Visualization · Pima: skew & hidden zeros

Zero isn't a measurement — it's missing data in disguise

Histograms of Glucose, BMI, and Insulin all spike at exactly zero — a biologically impossible value hiding as a real one. ≈374 of 768 Insulin rows are zero.

≈374/768 zero skew ≈ 2.27 median≈30 mean≈80 0 insulin (µU/mL) →

Insulin: skewness ≈ 2.27 — mean ~80, median ~30, and about half the column parked at zero.

Skewness by feature
featureskewread
Glucose0.17near symmetric
BMI0.43mild right skew
Age1.30young-heavy, long tail
Insulin2.27most skewed

Higher skew ⇒ longer tail; Insulin's 2.27 pairs with ~374 zero-valued rows.

Split by outcome

Glucose and BMI both shift higher in diabetics — with real overlap. Age barely moves.

CH 04 · Visualization · Outliers, correlation & causation

A heatmap is not a causal claim — IQR finds outliers, RCTs find causes

Box plots flag the same implausible zeros as isolated points; a Glucose–BMI scatter shows diabetics clustering upper-right. Neither chart proves causation.

IQR outlier rule $$ IQR = Q_3 - Q_1 $$ $$ [\,Q_1-1.5\,IQR,\ Q_3+1.5\,IQR\,] $$

Points outside this band are flagged — the same rule fraud detection applies to a $100–300/day spender.

Heatmap read

Glucose↔Outcome is the strongest single link; Glucose↔BMI and BMI↔skin-fold are moderate.

BMI ↑ glucose → non-diabetic diabetic overlap — not a clean split

Diabetic patients cluster high-glucose/high-BMI — association, not proof of cause.

CH 05 · Dimensionality reduction · PCA mechanics

Variance is the signal — rotate, then drop

PCA looks for the axes along which the data spreads out most, then keeps only the top few. Those axes are eigenvectors of the covariance matrix.

PC1 PC2 Outcome 0 Outcome 1
eigen-problem — variance-maximizing directions $$ C = \frac{1}{n-1}X^TX, \qquad Cx = \lambda x $$

$C$ is symmetric, so its eigenvectors come out mutually orthogonal — a free rotated axis system. Sort $\lambda$ descending, keep top $k$.

z-score first, always $$ z = \frac{x-\mu}{\sigma} $$

Puts every feature on comparable footing before any covariance is computed — and already mean-centers the data for free.

CH 05 · Dimensionality reduction · Explained variance ratio

Two axes, most of the story — the elbow flattens fast

Explained variance ratio tells you exactly how much you lose by dropping components. On Pima, PC1 + PC2 alone keep about 80% of the total spread.

PC1 PC2 PC3 PC4 PC5 PC6 PC7 PC8 ~60% ~20% cumulative → 80% by PC2

Bars: per-component variance (blue/green = the two kept). Dashed line: running total.

EVR — explained variance ratio $$ \text{EVR}_j = \frac{\lambda_j}{\sum_i \lambda_i} $$

Fraction of total variance held by component $j$. PC1+PC2 ≈ 80% on Pima's 8 features.

9 steps — raw features to $Z$

standardize → covariance $C$ → eigen $Cx=\lambda x$ → sort → project $Z=X_cW$ → (cumulative) EVR.

by hand vs sklearn

Both run on Pima; `sklearn.decomposition.PCA` uses SVD — more stable, exposes `explained_variance_ratio_` directly.

CH 05 · Dimensionality reduction · t-SNE mechanics

Neighbors, not axes — t-SNE fights the crowding problem

t-SNE turns distances into neighbor probabilities, then matches them in 2D with a heavy-tailed distribution. KL divergence is what the optimizer actually minimizes.

distance in embedding Gaussian (high-D) Student-t (low-D) ≈0 — crowded still apart
cost — match neighbor probabilities $$ C = KL(P\|Q) = \sum_{i \neq j} p_{ij}\log\frac{p_{ij}}{q_{ij}} $$

Gradient pulls points together where $P_{ij}>Q_{ij}$, apart where $Q_{ij}>P_{ij}$.

perplexity — target neighbor count $$ \text{Perp}(P_i) = 2^{H(P_i)} $$

Binary search picks $\sigma_i$ per point (e.g. 20 → 30) since local density varies across the dataset.

heavy tail fixes crowding

Cauchy-shaped $q_{ij}$ decays slower than Gaussian, letting moderately-far points spread apart instead of collapsing.

CH 05 · Dimensionality reduction · PCA vs t-SNE

Pick by the question — not by which method is "better"

Neither method dominates universally — on Pima, t-SNE actually showed more class overlap than PCA. Match the tool to variance vs. neighborhood questions.

aspectPCAt-SNE
naturelinear (eigendecomposition)nonlinear, iterative (KL descent)
deterministic?yesno, unless seeded
downstream modelingyes — reusable featuresno — visualization only
typical usefeature reduction + quick vizexplore nonlinear cluster structure
PCA — one axis t-SNE — clusters
opposite direction — kernel PCA

Kernel methods map data to a higher-dim space to expose nonlinear structure — the reverse of reduction, sharing the same eigen machinery.

Part III · Chapters 6–10

Classical Machine Learning

III

CH 06 · Validation · Why we split the data

Test accuracy is a statistic — not a certainty

Train and evaluate on the same rows and a model just memorizes the answer key. The test set stands in for the real world.

full dataset · N rows train — 80% fit the model here test 20% eval once

80/20 shown here — the ratio used throughout the course's diabetes project.

parameter vs statistic $$ \hat a_{\text{test}} \;\approx\; a_{\text{population}} $$

A parameter is the true, usually unknown fact about a population; a statistic is what you measure on a sample. Test accuracy is a statistic — an estimate, not a guarantee.

split ratio by dataset size
sizeratiowhy
100k–1M+90/10even 10% is huge
moderate80/20this course's diabetes set
small70/3020% test starves training

CH 06 · Validation · Sampling theory

Random doesn't mean representative — structure the draw instead

A sample can be drawn correctly and still mislead — how you sample matters as much as how much you sample.

simple random sampling population: mostly bachelor's (blue), few master's/PhD picked 5/5 = master's (green) — unlucky stratified sampling department: 60% BS · 30% MS · 10% PhD n=100 → 60 BS · 30 MS · 10 PhD, same 60:30:10

Same population, two draws: SRS can miss a whole subgroup by chance; stratified sampling can't.

simple random — equal chance

Every unit equally likely. Simple, but a small sample can get unlucky — all 5 picks turning out master's students.

stratified — proportional

Split into strata first, then sample each stratum in its true proportion — no subgroup gets left out.

cluster — whole groups at once

Divide into homogeneous clusters (districts), then take entire clusters wholesale — cheaper, less representative.

convenience — whoever's on hand

Fast, low-effort, no probability guarantee — asking the nearest classmates and hoping.

CH 06 · Validation · Imbalance vs. stratified split

Fixing the ratio and preserving it are different jobs

SMOTE, undersampling and oversampling change the class ratio; stratified splitting only preserves whatever ratio already exists across train and test.

undersampling

Drops majority-class rows until ratios balance. Throws away real data — like pruning a tree's roots; rarely the first choice.

oversampling

Duplicates minority rows. Risk: a duplicate leaks across train/test, and the repeated pattern gets over-weighted.

SMOTE — synthetic, not copied $$ x_{\text{syn}} = x_i + \lambda\,(x_j - x_i),\quad \lambda\in[0,1] $$

Interpolates new minority points between nearby real ones — raises the minority share without duplication or leakage.

100 patients 30 diab. 70 non-diab. train · 80 24 56 test · 20 6 14 30:70 held constant at every scale

Stratified splitting doesn't touch the ratio — it just carries 30:70 into both partitions.

CH 06 · Validation · Cross-validation & hyperparameters

One split can get lucky — cross-validation averages that away

An unusually easy or hard test split can make a model look better or worse than it is. Repeat the split, then aggregate.

round 1 F1 F2 F3 F4 F5 round 3 F1 F2 F3 F4 F5 … rotate the held-out fold through all K=5 rounds … each round: train K−1 folds (80%) · test 1 fold (20%)

Magenta = the one held-out fold that round; blue = the folds trained on.

parameters vs hyperparameters $$ \sigma\!\left(\sum_{i=1}^{n} w_i x_i + b\right) $$

$w_i, b$ are parameters — learned by training. Layers, $K$ in KNN, $C$ in SVM are hyperparameters — fixed beforehand, tuned externally.

validation split

Carve the 80% train allocation further: 60% actual-train / 20% validation. Compare hyperparameters there; the test set stays untouched until the final check.

holdout vs. K-fold / LOOCV

Holdout: one split, cheap, fine for big data. LOOCV ($K=N$) trains $N$ separate models — too costly past small datasets.

CH 07 · Classification · KNN & distance

No model, just a neighborhood — K decides how big

KNN never trains — every prediction re-scans the whole dataset. K alone tunes the bias–variance trade-off.

K = 1 K = 15 low bias · high variance high bias · low variance

Same 12 points, two boundaries: K=1 carves a tiny pocket around each lone point; K=15 smooths straight through them.

Minkowski distance family $$d(x,y)=\Big(\sum_{i=1}^m |x_i-y_i|^p\Big)^{1/p}$$

$p{=}1$ Manhattan · $p{=}2$ Euclidean · $p\to\infty$ Chebyshev. Scale features first — glucose in the hundreds would swamp a 0/1 flag.

choosing K

Small $K$: jagged boundary, low bias, high variance — one outlier flips a vote. Large $K$: smoother, high bias, low variance. No closed form — search $K$ on held-out data.

even-$K$ tie → use odd K or vote weighted by 1/distance $O(N{\cdot}M)$/query → KD-tree

CH 07 · Classification · Naive Bayes

45% vs 55% — Naive Bayes never hedges

A generative model: it learns $P(X\mid C)$ per class, then inverts it with Bayes' theorem. Whichever posterior wins, even barely, takes the whole prediction.

50% 45.5% 54.5% 2/9·3/9·9/14 → 1/21 No Yes 2/5·2/5·5/14 → 2/35 P(class | Hot, Rainy)

Query = Hot & Rainy: No edges out 54.5% to 45.5% — yet the model still commits fully, no "too close to call."

Bayes' theorem → decision rule $$P(C\mid X)\propto P(C)\prod_{i=1}^n P(x_i\mid C)$$

Naive independence turns an intractable joint likelihood into a product of 1-D terms. Drop the marginal $P(X)$ — it's the same for every class, so it can't change the ranking.

Laplace smoothing $$P(w\mid C)=\frac{\text{count}(w,C)+1}{N_C+|V|}$$

One unseen word gives a raw likelihood of zero — and a zero factor collapses the entire product. Add-one smoothing keeps every word's likelihood strictly positive.

Bernoulli → binary Multinomial → counts (text) Gaussian → continuous (Pima)

CH 07 · Classification · Logistic Regression

Squash the line, then threshold it — a perceptron before perceptrons

Linear regression's raw score is unbounded and outlier-sensitive. The sigmoid squashes it into a probability before any decision is made.

predict 0 (P<0.5) predict 1 (P≥0.5) 1 0 .5 z = 0 z →

σ(z) = 1/(1+e⁻ᶻ): as the linear score z crosses 0, the probability crosses 0.5 and the predicted label flips.

sigmoid squash $$P=\frac{1}{1+e^{-(W^TX+B)}}$$

$\sigma(0){=}0.5$, $\sigma(z)\to1$ as $z\to+\infty$, $\sigma(z)\to0$ as $z\to-\infty$. Each feature's $W_i$ measures how strongly it drives the outcome.

fit by max likelihood $$\ell(W,B)=\sum_i\big[y_i\log p_i+(1{-}y_i)\log(1{-}p_i)\big]$$

No closed form like least-squares — an iterative optimizer maximizes $\ell$ so the observed labels are as probable as possible.

softmax: scores 2,3,5 → thin 20% normal 30% obese 50% ← argmax

CH 07 · Classification · Support Vector Machines

The middle doesn't matter — only the closest points do

Among every hyperplane that separates the classes, SVM keeps the one with the widest breathing room. Only the points touching that margin ever determine it.

2/‖W‖ WᵀX+B=0 +1 −1 support vector support vector

Every non-support point could vanish and the boundary wouldn't move — only the ringed points on the margin fix it.

primal problem $$\min_{W,B}\tfrac12 W^TW \ \text{ s.t. } y_i(W^TX_i{+}B)\geq1$$

Maximizing the margin $2/\|W\|$ is the same as minimizing $\|W\|$. Points on $W^TX+B=\pm1$ are the support vectors.

dual via KKT $$W=\sum_i\alpha_iy_iX_i,\quad \sum_i\alpha_iy_i=0$$

Complementary slackness: $\alpha_i{=}0$ unless point $i$ sits exactly on the margin. Only those points ($\alpha_i{>}0$) shape $W,B$.

hard margin → cleanly separable soft margin → tolerates overlap kernel trick → non-linear (outline only)

CH 08 · Evaluation · Confusion matrix & accuracy paradox

99% accurate, 0% useful — the accuracy paradox

Four raw counts — TP, FP, FN, TN — are the only ground truth; every metric in this chapter is a ratio built from them. Accuracy alone can hide a model that never finds what it was built to find.

ACTUAL + ACTUAL − PRED. + PRED. TP correct hit FP Type I · false alarm FN Type II · missed case TN correct clear

FN — a sick patient called healthy — is the costliest cell in medicine.

Accuracy — fraction correct $$Accuracy = \frac{TP + TN}{TP + TN + FP + FN}$$

1000 patients, 10 sick: an "always healthy" dummy model scores ~99% accuracy yet catches zero real cases.

Beyond two classes

n×n matrix (normal / ad / spam) → one-vs-rest: pick a target class, collapse the rest into "negative," recompute TP/FP/FN/TN.

Where imbalance hides

Rare-disease screening, fraud detection, defect inspection: the majority class quietly dominates accuracy in all three.

CH 08 · Evaluation · Precision, recall & F-beta

Precision and recall disagree — F-beta breaks the tie

Precision asks "were the alarms real?"; recall asks "did we catch everyone?" F-beta lets you weight whichever error costs more.

1.0 0.0 decision threshold → trade-off point recall precision

Raising the threshold trades recall for precision, and vice versa.

Precision vs Recall $$Precision = \frac{TP}{TP+FP} \qquad Recall = \frac{TP}{TP+FN}$$

Precision: of everything flagged +, how much was real? Recall: of everyone truly +, how many did we catch?

F1 — harmonic mean $$F_1 = \frac{2\cdot Precision \cdot Recall}{Precision + Recall}$$

P=0.9, R=0.1 → arithmetic mean 0.5 (flattering); F1 ≈ 0.18 — missing 90% isn't "medium."

F-beta — tune the weight $$F_\beta = \frac{(1+\beta^2)\cdot Precision \cdot Recall}{\beta^2\cdot Precision + Recall}$$

Beta under 1 favors precision (spam filters); beta over 1 favors recall (diabetes screening, β=2 typical).

CH 08 · Evaluation · ROC, AUC & metric choice

One curve, every threshold — then let the stakes pick the metric

Every metric so far freezes one threshold. ROC and AUC score the classifier across all of them at once.

random guess (AUC = 0.5) chosen threshold AUC FPR = 1 − specificity → TPR (recall) ↑ 0 1 1

The curve bows toward the top-left as separation improves; the dashed diagonal is a coin flip.

AUC — area under the curve $$AUC = \textstyle\int_0^1 TPR\,d(FPR)$$

1.0 = perfect, 0.5 = random (diagonal), 0 = inverted.

Ranking candidates

No threshold fixed yet? Use AUC to compare RF, LogReg, GB, KNN, SVM, MLP, NB, DT on equal footing.

Choosing for deployment

Diabetes screening: a missed case (FN) costs more than an extra test (FP) — favor recall or F-beta above 1.

CH 09 · Clustering · Distance & scaling

Distance lies when scales don't match — standardize before you cluster

Clustering is often run before supervised modeling, to catch outliers before they contaminate a classifier — but every step reduces to distance, and distance reduces to scale.

UNSCALED glucose 0–200 BMI 0–60 BMI swamped by glucose's scale STANDARDIZED z(glucose) z(BMI) both features pull equal weight

Same points, two scalings: unscaled, glucose's 0–200 range swamps BMI's 0–60; standardized, both axes carry equal weight in the distance calculation.

z-score — standardization $$ z = \frac{x-\mu}{\sigma} $$

Rescales every feature to mean 0, std 1 — so no single feature's raw range decides "closeness."

Euclidean — the default norm $$ d(x,y)=\sqrt{\textstyle\sum_i (x_i-y_i)^2} $$

One instance of a norm (non-negativity, homogeneity, triangle inequality) — the family that makes "distance" precise.

CH 09 · Clustering · K-Means mechanics

Converged doesn't mean correct — K-Means's local-optimum trap

K-Means minimizes WCSS by definition — the mean is exactly the point minimizing summed squared distance. But the objective isn't convex, so convergence only promises a local minimum.

elbow ≈ K=3 1 2 3 4 5 6 7 K WCSS

WCSS always falls as K grows, but the gains flatten fast — the elbow near K=3 is where extra clusters stop paying for themselves.

WCSS — what K-Means minimizes $$ WCSS=\sum_i \|x_i-\mu_{k(i)}\|^2 $$

The mean is exactly the point minimizing summed squared distance — that's why centroid = mean, not median or mode.

local optima — not global

WCSS isn't convex in the centroids, so a bad init can get stuck. Fix: n_init reruns from several random starts, keeps the lowest WCSS.

shape assumption — the blind spot

Needs convex, round, separated, similarly sized clusters. A single outlier can drag a centroid off-center — the mean resists nothing.

CH 09 · Clustering · DBSCAN vs K-Means

Density needs no K — and it calls outliers by name

DBSCAN swaps "distance to a mean" for "density of a neighborhood" — no K to guess, arbitrary shapes allowed, and noise is a first-class citizen.

cluster A cluster B K-Means split (wrong) — cuts both ε-neighborhood → core point noise (label = -1)

Two interleaved, non-convex clusters: a straight split (dashed, red) cuts through both; DBSCAN instead grows outward from dense ε-neighborhoods and leaves the lone point labeled noise.

core point

min_samples points within its ε-neighborhood.

border point

Not core itself, but sits in a core point's ε-neighborhood — joins that cluster.

noise point

Neither core nor reachable from one — flagged an outlier, typically labeled -1.

CH 10 · Ensembles · Bagging vs boosting

Two failure modes, two remedies — bagging averages away variance, boosting chases down bias

Both turn many weak learners into one strong one — the difference is parallel averaging vs sequential correction.

bagging — parallel data independent bootstrap trees avg / vote variance ↓ boosting — sequential h1 h2 h3 residual, stage by stage Fm = Fm-1 + ν·hm bias ↓

Same input, opposite architecture: bagging fans out and averages; boosting chains stages and corrects.

bagging — parallel, independent $$\hat{f}(x)=\frac{1}{B}\sum_{b=1}^{B} f_b(x)$$

Random Forest bags trees + samples features per split — bootstrap noise averages out, bias barely moves.

boosting — sequential, corrective

AdaBoost / Gradient Boosting add one stage at a time, each weighted by how well it closes the error still left.

bagging → independent teachers, no coordination boosting → 2nd teacher reteaches only the quiz misses canonical → Random Forest · AdaBoost · Gradient Boosting

CH 10 · Ensembles · Voting vs stacking

A fixed rule only goes so far — stacking learns how much to trust each model

Voting combines models with a fixed rule; stacking trains a model to learn the combination instead.

voting — fixed rule linear tree NN avg / majority stacking — learned weights meta-model (learned) arrow width ∝ learned weight

Same base models — voting combines them by a fixed rule, stacking lets a meta-model learn the weights.

soft voting — average the confidence $$\hat{y}=\arg\max_c \frac{1}{M}\sum_{m=1}^{M} p_m(c\mid x)$$

Uses each model's probability, not just its label — typically beats hard voting's all-or-nothing count.

hard voting — majority rule $$\hat{y} = \text{mode}\{\hat{y}_1,\dots,\hat{y}_M\}$$

Each model casts one vote for a class label; most votes wins.

stacking — a learned combiner

A meta-model trains on the base models' outputs, learning how much to trust each one — not a fixed rule.

CH 10 · Ensembles · Gradient boosting steps

Fit the error, not the target — gradient boosting closes the gap one stage at a time

Each stage doesn't relearn $y$ — it learns what the ensemble so far still gets wrong.

true y F0 F1 F2 F3 large residual residual → 0

Each stage nudges the ensemble closer to the true value; by stage 3 the residual gap is nearly gone.

the update — add a small correction $$F_m(x) = F_{m-1}(x) + \nu\, h_m(x)$$

Learning rate $\nu$ (0.01–0.3) keeps one stage from overcorrecting — slower, but generalizes better.

init + residual — what each stage sees $$F_0(x)=\bar{y} \qquad r_i = y_i - F_{m-1}(x_i)$$

Start at the mean; every later $h_m$ trains on the residuals, never the raw targets.

base learner → shallow regression tree general loss → residual becomes the negative gradient stopping → fixed $M$ stages or validation error

Part IV · Chapters 11–14

Deep Learning & the Frontier

IV

CH 11 · Neural networks · Neuron to perceptron

Same shape, different substrate — biology gives the pattern, not the proof

Dendrites, soma, and axon are just relabeled inputs, sum, and output — the math doesn't need the biology to be true.

dendrites soma axon biological x1 x2 x3 w1 w2 w3 Σ φ ŷ weighted sum + activation artificial neuron
perceptron — one neuron's full computation $$ z = \sum_i w_i x_i + b, \qquad \hat{y} = \phi(z) $$

$\phi$ is the only thing standing between this and plain linear regression.

parameters vs hyperparameters

$W,b$ are learned by gradient descent. Depth, width, and even the choice of $\phi$ are set by you — nothing in the math picks them in advance.

One hidden layer of these units is an ANN; stack more than one and it's deep learning.

CH 11 · Neural networks · Why nonlinearity matters

Depth without $\phi$ is a mirage — stacked lines are still a line

A composition of linear layers is still linear — nonlinearity is the entire reason depth helps.

class A class B φ = identity — one straight cut φ = σ — boundary bends
sigmoid — squashes to a probability-like range $$ \sigma(x) = \frac{1}{1+e^{-x}} $$

Maps $\mathbb{R} \to (0,1)$ — a natural fit for binary classification outputs.

identity $\phi(z)=z$ — the collapse case $$ \hat{y} = \sum_i w_i x_i + b $$

Exactly multiple linear regression — stacking more such layers changes nothing.

not every nonlinear function qualifies

A usable $\phi$ must be differentiable almost everywhere — e.g. $\tanh$, used in the Sec. 11.6 worked example.

Same two classes, same weights — only $\phi$ decides whether the boundary can bend.

CH 11 · Neural networks · Backprop via chain rule

One chain rule turns $O(n^2)$ into $O(n)$ — that's what makes depth affordable

Backpropagation isn't a separate algorithm — it's how gradient descent affords many layers at once.

layer 1 (tanh) layer 2 (tanh) layer 3 loss x W1 W2 W3 ŷ L ∂L/∂W3 — direct ∂L/∂W2 — reuses ∂L/∂W3 ∂L/∂W1 — reuses both forward → ← backward

Forward once, then walk the chain rule backward — each layer's derivative is computed once and reused, not recomputed per weight.

gradient descent — the update rule $$ W_{\text{new}} = W_{\text{old}} - \alpha\, \nabla_W L $$

$\alpha$ is the learning rate — a hyperparameter, not something descent tunes itself.

loss — matched to the target type

Regression → MAE / MSE (RMSE too). Classification → cross-entropy. Same machinery either way.

backprop — why it's cheap

Finite differences cost $O(n^2)$; reusing each layer's derivative drops it to $O(n)$.

CH 11 · Neural networks · When depth pays off

Depth is earned, not assumed — four criteria decide when

More parameters need more data and compute — deep learning is a bet, not a default.

2015 Lane–Emden NN loses to classical PINN PIML Karniadakis: physics ⊕ data blend 2019 orthogonal-φ nets usable, not superior RL DQN → DDQN new closed-form soln
PINN — physics as a loss term $$ y''(x)+y(x)=0, \quad y(0)=0,\ y'(0)=1 $$

Governing equation + initial conditions get folded straight into the training loss, blended with whatever data exists.

four criteria — decide before you pick an architecture
small data → classical ML tight compute → classical ML raw pixels → CNN order ≥ 10 → ML / DL

A decade of responses: each stage answers the previous stage's limit.

CH 12 · Transformers & LLMs · Attention mechanics

Every token asks, every token answers — attention is just weighted lookup

Attention replaced recurrence entirely — parallel to compute, no vanishing gradient over long chains. The 2017 paper's title says exactly this.

cat sat because it strong weak weak raw sim(it, cat) ≈ 0 — attention resolves it anyway

Q·K learns "it" refers to "cat" — a relation static embeddings never see.

Q, K, V — scaled dot-product attention $$\text{Attention}(Q,K,V)=\text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right)V$$

Query = what I'm looking for; Key = what I offer; Value = what I contribute if picked. Softmax turns raw scores into weights summing to 1.

cost — quadratic in context length

$QK^\top$ is $N\times N$ for context length $N$. An "8K-context" model computes an 8000×8000 matrix every pass.

multi-head — parallel specialists

GPT-2 runs 12 heads per layer, each free to specialize: one tracks pronoun reference, another subject–verb structure.

CH 12 · Transformers & LLMs · Decoder architecture

GPT can't peek ahead — enforced with a wall of −∞

Masking future positions before softmax is the entire difference between GPT and bidirectional BERT. No new math — just −∞ in the right cells.

key position j → query position i ↓ 1 6 1 6 kept, j ≤ i masked → 0

Row i (query) may only look at columns j ≤ i (key) — everything to the right is masked to −∞ before softmax.

masked — causal self-attention $$\text{Attention}(Q,K,V)=\text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}+M\right)V$$

$M_{ij}=0$ for $j\le i$, $-\infty$ for $j>i$ — future scores vanish to exactly 0 after exponentiating.

GPT vs BERT — decoder vs encoder

GPT: decoder-only, autoregressive, $P(x_t\mid x_{

pipeline — one forward pass
tokenizeembed+ pos-encmask+attendsample

Repeat: append the sampled token, feed the longer sequence back in.

CH 12 · Transformers & LLMs · Tokenization

Equations pay a tokenizer tax English never sees — and embeddings can't fix it

Byte-level BPE handles any script uniformly — but LaTeX still shreds into noise. Backslashes and braces fragment into near-meaningless tokens.

merge the most frequent adjacent pair, repeat tired tired tired bytes first, then merge → one token ID for lookup

Byte-level BPE runs this same merge process on raw bytes, so any script fits the one scheme.

tokenize — text to integer IDs $$\text{text} \rightarrow (t_1, t_2, \ldots, t_n), \quad t_i \in \{1,\ldots,|V|\}$$

Word-level (fragile to typos) → BPE merges frequent byte-pairs (GPT-1–3.5) → byte-level BPE today, any script uniformly.

real counts — live tiktokenizer demo, GPT-2 → GPT-4o
Persian greeting: 26 → 8 tokPython snippet: 17 → 15 tok

GPT-2's mostly-English vocabulary pays dearly for Persian; Chinese, by contrast, compresses heavily.

bare symbols — no inherent meaning

$x, y, u, v$ aren't like "king" — their meaning is entirely local, fixed only by the equation they sit in.

CH 12 · Transformers & LLMs · Prompting, RAG & calibration

Sharper reasoning, same blind spot — confidence outruns correctness

Fine-tuning bakes in a reasoning style; RAG retrieves a fact instead of memorizing one. Neither teaches a model to say "no solution."

the benchmark problem — Fredholm, second kind $$y(x) = f(x) + \lambda \int_a^b K(x,t)\, y(t)\, dt$$

~500K symbolic base equations, plus ~60 hand-designed edge cases across 14 augmentation strategies.

chain-of-thought — same model, more tokens

A "thinking budget" caps reasoning tokens; GPT-5 at medium effort clearly beat GPT-4o on the instructor's own DE benchmark.

RAG — retrieval, not memorization

Finds a similar solved problem by vector similarity and supplies it in-context — no weight update, unlike CoT fine-tuning.

correctly flagged "no solution" cases 25% 50% 75% 0% ~33% GPT-5.2 GPT-4o

GPT-5.2 aces "exact"/"family" types (100%) but never flags a true "no solution" case; GPT-4o-mini sits near 0% overall.

CH 13 · Agentic AI · Capability lineage

Suggestion becomes action — the agentic layer closes the loop

Every layer below still just ranks the next token; only the top layer decides and acts on that decision.

next-token prediction — the generative core $$ \hat{w}_{t+1} = \arg\max_{w} P(w \mid w_1, w_2, \dots, w_t) $$

This is where a plain generative model stops — ranking words, never dialing an API.

Agentic AI — definition

Autonomously search, decide, and act on that decision — not just propose an answer for a human to execute.

AI Machine Learning Deep Learning Generative AI Agentic AI predicts next token decide + act

CH 13 · Agentic AI · MCP permissioning

From free-form scripts to permissioned calls — MCP fences in what an agent may do

LangChain taught models to call tools; MCP decides which calls they're allowed to make.

LangChain — chaining tool calls

Developer wires each step to a real action: search API → compare → booking server → payment.

MCP request — tool, arguments, action
tool: "shell"arguments: {cmd}action: "run"

The server executes and enforces what's allowed — the model only asks.

Local Agent Kit — a cautionary run

A local dev run triggered a DB migration against production and took it down.

ad hoc scripts model writes a script runs, unrestricted shell / prod DB no gate MCP model tool · args · action scoped? read-only? shell / DB gated

Same call-and-return shape as ping or telnet — MCP just adds a gate.

CH 13 · Agentic AI · Multi-agent systems

Specialists beat one generalist — split the project, then recombine

Sub-agents converge the way a human team does: each masters one slice, then they compare notes.

Decomposition — one project, many specialists

Split the work across sub-agents; each executes its slice independently, then the outputs combine into one coherent result.

Concrete specialties
DB schemaAbstract Factory patternoptimized algorithm

Each output mirrors what a human specialist on the team would propose.

project 1 · describe 2 · split DB agent algo agent backend agent 3 · execute independently 4 · exchange outputs integrated result 5 · combine

CH 13 · Agentic AI · Skills paradigm

Prompts you can actually reuse — one skill, one job, loaded on demand

Only headlines sit in context up front; the agent reads a skill's full text only when it needs it.

Skill — one markdown file, one job

Authored, shared, and version-controlled like any other file in the repo.

Unix philosophy, applied

Small, single-purpose, composable — complex behavior emerges from combining many skills, not one giant prompt.

skill headlines agent scans for a match loads full skill.md executes the step scan match → load follow it next step

Only headlines sit in context up front; full instructions load on demand.

CH 14 · Scientific ML · Inductive bias

Physics is inductive bias — trade data for structure

Every learner sits somewhere between raw data and a governing equation — PINNs lean deliberately toward the equation.

THE INDUCTIVE-BIAS SPECTRUM LLMs data only curve fitting data, no equation PINN equation + data classical numerics equation only ← more data, less structure more structure (physics), less data →

PINNs sit near the physics end but keep one foot in data — that's the hybrid position.

inductive bias — the axis $$\text{data volume} \;\;\longleftrightarrow\;\; \text{structural prior (physics)}$$

Every learner sits on this line. PINNs sit deliberately toward the physics end.

physics-informed = hybrid

Equation and data both available — trained to satisfy the equation while optionally fitting whatever data exists.

why the shift, now

Same three drivers as the wider DL boom: more data, cheaper GPU/TPU compute, maturing algorithms.

CH 14 · Scientific ML · PINN formulation

Autodiff turns the network into the solution

No labeled solution data anywhere — only a physics residual and an initial-condition penalty.

x_i (collocation points) u_θ(x) — NN 1→32→32→1 · tanh autodiff: du/dx r(x)=du/dx−cos(x) L_res=mean(r²) boundary: x=0 u(0) L_IC=(u(0)−0)² L(θ)=λ₁L_res+λ₂L_IC backprop → update θ
residual + composite loss $$r(x)=\mathcal{N}[u_\theta](x)-f(x)$$ $$L(\theta)=\lambda_1 L_{\text{res}}+\lambda_2 L_{\text{IC}}$$

No exact-solution data anywhere — only the equation and the conditions that pick one solution.

worked example — u'(x)=cos(x)

MLP $1\to32\to32\to1$, tanh, Adam; 40 points, requires_grad=True; autograd.grad(u,x,create_graph=True).

result

3000 epochs, loss ↓ to ~$10^{-5}$; tested on 200 new points → MAE ≈ 3.38×10⁻⁴ vs. exact $\sin(x)$.

CH 14 · Scientific ML · Validation

Low residual loss isn't proof — trust, but verify

Van der Pol's limit cycle stress-tests a PINN; QLM supplies an independent second opinion.

y y' limit cycle trajectories spiral onto the cycle uniform chebyshev
Van der Pol — nonlinear stress test $$y''-\mu(1-y^2)y'+y=0$$

Self-sustained limit-cycle oscillations — a network can't just memorize a sinusoid.

chebyshev vs. uniform

2nd-kind Chebyshev collocation nodes beat uniform spacing — but the gain was described as "very marginal."

QLM cross-check

Linearize $(1-y^2)y'$ around the current iterate (Newton-type) → sequence of linear ODEs → iterate to convergence.

CH 14 · Scientific ML · KAN → PIKAN → project

Edges learn now, not nodes

Swap MLP for KAN inside an unchanged PINN loop — the edge-function choice alone can decide the winner.

MLP — params on nodes KAN — params on edges σ σ σ w learnable: weights & bias φ(x) learnable learnable: one function per edge
Kolmogorov–Arnold vs. universal approx. $$f(x)\approx\sum_i w_i\,\sigma(w_i x+b_i)\;\;\text{(MLP)}$$

KAN keeps the sum but makes each edge's univariate function learnable instead.

PIKAN = PINN with KAN swapped in

Training loop, residual, and loss stay unchanged — only the network block swaps MLP → KAN.

allen–cahn case study

Jacobi-basis PIKAN beat both a spline-KAN and a plain PINN (64×64, tanh) on $L^2$ residual error.

RECALL move · T contents · R recall · M more 1/1