Python AI Algorithms / Technical reference
Understand the choices behind the code

An atlas of
AI algorithms.

Explore how an algorithm chooses a path, learns a boundary, or compresses a dataset. Inspect the mathematics, computational costs, assumptions, and implementations in this repository.

Start with a search trace ↓
A branching graph connected to a layered learning model
20algorithms & methods
5search strategies
0external dependencies
FOUNDATIONS · BEGINNER · 20 MINUTES

Big O: count the work, account for the memory.

Prerequisite: loops, arrays, and functions. Start here before comparing algorithms. Big O is an asymptotic upper bound; Θ is a tight bound and Ω is a lower bound. State the input size and case before making a claim.

Counted toy operations, not milliseconds or benchmark predictions
ExampleGrowthn2nAuxiliary memory

Derive the bound
  1. Define the dimensions: n elements; V vertices and E edges; n rows and d features.
  2. Count a representative operation, such as one comparison or one pair visit.
  3. Add sequential phases: O(n) + O(n²) becomes O(n²). Multiply independent nested loops: n × m becomes O(nm).
  4. A loop that halves its search interval takes O(log n) iterations. Two pointers each moving forward at most n times still take O(n), even with a nested while loop.
  5. Drop fixed constants and lower-order terms asymptotically: 3n + 5 is Θ(n). Constants and cache behavior still matter in practice.
Time cases, amortization, and memory

Linear search has Θ(1) best-case and Θ(n) worst-case comparisons. Average-case needs an input distribution. Hash lookup is commonly expected O(1), not an unconditional worst-case promise. Dynamic-array append is amortized O(1) across a sequence, although a resizing append can take O(n).

Auxiliary space is extra working memory, excluding the input and, when explicitly stated, the returned output. Total memory includes input, working memory, and output. Recursive depth consumes stack space: balanced tree DFS uses O(log n) stack; a chain can use O(n). Enumerating every subset requires Θ(n·2ⁿ) output elements even if the recursion path needs only O(n).

These guides save snapshots. Copying an n-cell board for O(n) frames can consume O(n²) time and memory even when the underlying algorithm uses O(1) auxiliary space. Input validation and trace construction are separate from the algorithm's displayed bound. Teaching integer arithmetic assumes bounded values; very large integers have nonconstant arithmetic costs.

Worked comparisons
  • Pair sum: brute-force pairs take Θ(n²); sorting then two pointers takes O(n log n) overall; already-sorted two pointers take O(n). State whether sorting is included.
  • Graph traversal: O(V + E) with adjacency lists; repeatedly scanning an adjacency matrix takes O(V²). Representation changes cost.
  • Model training: one dense gradient pass takes O(nd). I iterations take O(Ind); K-fold evaluation multiplies fitting work by K.
  • Heap selection: O(n log(k + 1)) time and O(k) working memory. A small k and a large n are different dimensions.
Check your reasoning: two consecutive loops of length n

02 / DECISIONS IN A FRONTIER

The shortest route depends
on what you minimize.

Two edges can cost more than three. Step through the same weighted, directed graph with five strategies.

Intermediate · 15 minutes · Prerequisites: Big O, graphs, queues, and heaps. Try the contrasting graph presets before reading the completed results.

Step-by-step weighted graph searchS connects to A at cost 1 and B at cost 4. A connects to C at cost 1. C and B connect to G at cost 1. Use the labeled controls to advance expansions.
CurrentExpandedQueuedUnseen

Edge labels are costs. Heuristics: h(S)=3, h(A)=2, h(B)=0, h(C)=1, h(G)=0. The default values are admissible for this graph. DFS follows A before B. Frontier entries are queued candidates; stale entries can await removal.

Completed results on the selected illustrative graph
MethodPriorityRouteCostGuarantee here
03 / WATCH AN UPDATE

Learning is an iterative process.

Vary a step size, inspect a projection, and connect the geometry to the formula.

Gradient descent

One standardized feature, five noiseless points, and mean squared error. Move the step slider to inspect an update.

PCA: preserve a direction

Project a cloud onto its principal axis. Gray segments show discarded perpendicular variation. This geometric illustration is not a fitted dataset benchmark. The principal axis runs diagonally through the centered cloud; projecting onto it discards each point’s perpendicular displacement. Reconstruction returns a point on that axis, losing the discarded variation.

Principal component projection and reconstructionFeature 1Feature 2First principal directionOriginalReconstructed
scores = X_centered V_k
reconstruction = scores V_kᵀ + mean

Fit scaling and PCA on training rows. Variance retained is not classification accuracy. For an executed example, open Visual foundations.

04 / THE TECHNICAL REFERENCE

Choose a method.
Understand its trade-offs.

Read the objective before the implementation. Each entry links to project code and states where its guarantees end.

20 of 20 methods
Supervised

Linear regression

View implementation ↗

Predict a numeric target from an intercept and weighted features.

ŷ = b + xᵀw; L = (1/n) Σᵢ(ŷᵢ − yᵢ)²
Walk through the algorithm
  1. Reserve held-out observations.
  2. Fit coefficients by least squares or gradient descent.
  3. Compare held-out errors with a baseline.

Computational cost

A full dense gradient step costs O(nd). Dense least squares is solver-dependent; a common tall-matrix QR approach is O(nd²).

Assumptions & failure modes

Linear responses can underfit nonlinear relationships. Correlated features can destabilize coefficients. The NumPy model learns scaling on training rows only.

Example. Points (0,1), (1,3), (2,5) fit y = 1 + 2x. See the salary notebook for a dataset application.

Supervised

Logistic regression

View implementation ↗

Convert learned class scores into probabilities with sigmoid or multiclass softmax.

p(y=1|x) = 1 / (1 + exp(−(b + xᵀw)))
Walk through the algorithm
  1. Fit preprocessing within the training pipeline.
  2. Minimize regularized cross-entropy.
  3. Choose C or thresholds on validation data and report final test metrics.

Computational cost

Solver-dependent. A dense gradient pass costs O(nd) for binary classification or O(ndc) for c classes. Iteration count depends on convergence.

Assumptions & failure modes

This is a classifier despite its name. Linear scores can underfit nonlinear structure. In scikit-learn, larger C means weaker regularization. Probability calibration is not guaranteed.

Example. At score z=0, p=0.5. With y=1, cross-entropy is −log(0.5), approximately 0.693.

Supervised

K-nearest neighbors

View implementation ↗

Classify a query using nearby training examples and a vote.

d²(x,z) = Σⱼ(xⱼ − zⱼ)²; prediction = majority among k nearest
Walk through the algorithm
  1. Learn feature scaling on training observations.
  2. Compute distances from a query to training rows.
  3. Select k neighbors and apply the documented tie rule.

Computational cost

The NumPy query uses O(nd) distance work plus O(n log n) sorting. Indexed implementations have data- and dimension-dependent costs.

Assumptions & failure modes

Feature units matter. Small k can follow noise; large k smooths boundaries. The NumPy version breaks distance ties by training order and vote ties by sorted class order.

Example. For [0,1,3] with labels [A,A,B], query 2.2 predicts B at k=1 but A at k=3.

Supervised

Decision tree

View implementation ↗

Partition feature space with threshold questions, then predict from the reached leaf.

Gini(t) = 1 − Σₖpₖ²; maximize weighted impurity reduction
Walk through the algorithm
  1. Evaluate candidate feature thresholds.
  2. Choose the greatest allowed impurity reduction.
  3. Repeat until a depth, leaf-size, or purity stopping rule.

Computational cost

Training depends on split search and shape; O(d n log n) is a common balanced-tree description. Prediction is O(depth), potentially O(n) for a degenerate tree.

Assumptions & failure modes

Deep trees can memorize noise. Training impurity improvements do not guarantee generalization. Select depth using training-only CV.

Example. Two positives and two negatives have Gini 0.5. Two pure children have weighted impurity 0.

Supervised

Random forest

View implementation ↗

Combine randomized trees to reduce the variance of individual trees.

p̂(y=k|x) = (1/T) Σₜp̂ₜ(y=k|x)
Walk through the algorithm
  1. Fit trees on bootstrap samples with randomized feature candidates.
  2. Let each tree build its own partitions.
  3. Average class probabilities and choose the highest.

Computational cost

Approximately T times the chosen tree-training cost, with parallelization opportunities. Prediction visits one path in each tree.

Assumptions & failure modes

Randomization does not eliminate bias or fix leakage. Larger forests require more memory and can be harder to explain directly.

Example. The Iris demo fits 100 trees on the same held-out split as the other classifiers.

Supervised

Support vector machine

View implementation ↗

Balance a separating margin against penalties for classification violations. Kernels enable nonlinear boundaries.

hinge = max(0, 1 − y f(x)); RBF K(x,z) = exp(−γ‖x−z‖²)
Walk through the algorithm
  1. Fit feature scaling within training data.
  2. Fit the margin-based classifier with chosen C and kernel parameters.
  3. Validate C and gamma without using final test rows.

Computational cost

Kernel training commonly needs at least quadratic resources and can approach cubic time in n, depending on data/solver. Kernel storage can be O(n²). Prediction depends on support-vector count.

Assumptions & failure modes

Distances depend on scaling. Large C or gamma can overfit. Decision scores are not automatically calibrated probabilities.

Example. The project uses StandardScaler followed by an RBF SVC for Iris.

Supervised

Gaussian Naive Bayes

View implementation ↗

Combine class priors and Gaussian feature likelihoods under conditional independence.

score(y) = log P(y) + Σⱼlog N(xⱼ; μᵧⱼ, σ²ᵧⱼ)
Walk through the algorithm
  1. Estimate class priors.
  2. Estimate feature means and variances per class.
  3. Sum log-likelihoods and priors; choose the largest posterior score.

Computational cost

Training is O(nd), with O(cd) stored parameters. A query typically costs O(cd).

Assumptions & failure modes

Correlated features can double-count evidence. Gaussian assumptions can fit poorly. Variance smoothing improves numerical behavior, not assumption validity.

Example. GaussianNB uses the same Iris partition as the tree, forest, and SVM.

Unsupervised

K-means clustering

View implementation ↗

Alternate nearest-center assignments and mean updates to find compact groups.

J = Σᵢ ‖xᵢ − μ_label(i)‖²
Walk through the algorithm
  1. Initialize k centers for several seeded starts.
  2. Assign each point to its nearest center.
  3. Update nonempty centers to member means; retain the run with lowest inertia.

Computational cost

Basic Lloyd updates cost O(I n k d) per start. The NumPy implementation materializes pairwise differences and can require O(nkd) temporary memory.

Assumptions & failure modes

IDs are arbitrary. Starts can find different local minima. Compact similar-scale groups fit better than elongated or unequal-density groups. Empty centers are retained here.

Example. Assign [0,2,8,10] to [0,10]; the next centers become [1,9].

Unsupervised

Principal component analysis

View implementation ↗

Project centered features onto orthogonal directions retaining maximum training variance.

X_centered = UΣVᵀ; scores = X_centered V_k
Walk through the algorithm
  1. Fit scaling and centering on training rows.
  2. Find principal directions using SVD or an eigensolver.
  3. Transform unseen observations without refitting; optionally reconstruct.

Computational cost

Dense full SVD is typically O(min(nd², n²d)); truncated/randomized solvers can be cheaper. Projection into k components costs O(ndk).

Assumptions & failure modes

Largest variance does not imply predictive relevance. Units and outliers can dominate. Component signs are arbitrary; inspect reconstruction or subspaces.

Example. A cloud near y=x has a diagonal first direction. One-component reconstruction removes perpendicular variation.

Supervised

Feed-forward neural network

View implementation ↗

Combine linear layers and nonlinear activations to learn feature interactions.

h = ReLU(W₁x+b₁); scores = W₂h+b₂; cross-entropy + regularization
Walk through the algorithm
  1. Initialize weights and define the objective.
  2. Use backpropagation to obtain derivatives and optimize weights.
  3. Evaluate with the same fitted input representation on held-out rows.

Computational cost

Forward/backward work is proportional to batch size times layer connections. Total cost depends on iterations/optimizer; L-BFGS also stores optimization history.

Assumptions & failure modes

More units do not guarantee better performance. Weak regularization, small datasets, or repeated test-based tuning can overfit. Seeds affect results.

Example. The NLP helper uses a 32-unit ReLU hidden layer, L2 regularization, and L-BFGS on TF-IDF.

Optimization

Gradient descent

View implementation ↗

Move parameters against the gradient of the training objective.

θₜ₊₁ = θₜ − η∇L(θₜ); ∇MSE = (2/n) Dᵀ(Dθ−y)
Walk through the algorithm
  1. Choose a learning rate and initialize parameters.
  2. Compute residuals and the gradient.
  3. Update and inspect loss until the chosen budget or stopping rule.

Computational cost

For dense regression, a full batch step is O(nd). Saving I parameter vectors adds O(Id) history storage.

Assumptions & failure modes

Large steps can overshoot or diverge. Falling training loss measures optimization, not generalization. Scaling can improve conditioning.

Example. The live panel uses one standardized feature. Rates above 1 are unstable for this particular quadratic.

NLP

TF-IDF representation

View implementation ↗

Weight words by within-document importance and rarity across training documents.

tf(t,d) × idf(t); smoothed idf = log((1+n)/(1+df(t))) + 1
Walk through the algorithm
  1. Fit the vocabulary and document frequencies using training texts only.
  2. Create sparse weighted document vectors.
  3. Transform held-out text using fixed vocabulary and IDF.

Computational cost

Roughly proportional to token occurrences plus vocabulary processing. Sparse storage follows nonzero entries, not all document×vocabulary combinations.

Assumptions & failure modes

TF transformation and normalization are configurable. The NLP helper uses sublinear TF, smoothed IDF, and default L2 normalization. New words never create new columns at prediction time.

Example. A term appearing only in test articles is not added to the training vocabulary.

NLP

Rule-based Nepali stemming

View implementation ↗

Normalize words using a matching long suffix after Devanagari cleaning.

word → longest permitted suffix removal; keep at least two characters
Walk through the algorithm
  1. Keep Devanagari text and remove digits/punctuation and basic stopwords.
  2. Read UTF-8 suffixes and sort longest first.
  3. Remove the first matching suffix only when a usable stem remains.

Computational cost

For W tokens and S suffixes, a direct scan is up to O(W S ℓ), where ℓ bounds suffix comparison length.

Assumptions & failure modes

This is a teaching heuristic, not a linguistic parser. It can over-stem words or merge meanings. Apply identical cleaning to training and prediction.

Example. Inspect cleaned/original news before assuming that more normalization improves classification.

Evaluation

Stratified cross-validation

View implementation ↗

Assess validation behavior across folds while approximately preserving class proportions.

CV = (1/K) Σₖ score(model trained without fold k, fold k)
Walk through the algorithm
  1. Reserve a final test partition first.
  2. Fit a fresh complete pipeline in each training CV fold.
  3. Summarize scores and variability without treating fold std as a confidence interval.

Computational cost

K folds require K fits per configuration. Learning curves add fits at each training size.

Assumptions & failure modes

Stratification does not create independence. Repeated people, duplicate texts, or temporal data require grouped or chronological splits.

Example. The evaluation lesson uses four shuffled stratified folds entirely within training data.

Evaluation

Grid search with CV

View implementation ↗

Compare a finite parameter grid using training-only CV, then refit the selected pipeline.

λ* = argmax_λ mean CV score(λ)
Walk through the algorithm
  1. Predefine the grid and scoring metric.
  2. Cross-validate the complete pipeline for each configuration.
  3. Refit on all training rows; evaluate final test data after selection.

Computational cost

H configurations and K folds need approximately H×K fits, plus final refitting.

Assumptions & failure modes

The best CV score is selection-biased, not a final unbiased test estimate. Extensive comparisons may require nested CV or fresh outer evaluation.

Example. The project compares C ∈ {0.01,0.1,1,10} by average precision, then reports held-out metrics.

Choose a threshold. Inspect the tradeoff.

Illustrative validation scores for eight cases, not a trained model benchmark. Positive prediction means score ≥ threshold.

Choose an operating threshold using validation data and error costs. Freeze it before reporting held-out test performance. Precision or recall is undefined when its denominator is zero.

05 / TRUST THE PROCESS

A good score starts
with a valid experiment.

Model selection belongs inside training data. The final test set is a report after selection, not another tuning tool.

Separate training cross-validation from final held-out evaluationDatasetdeduplicate firstTraining splitfit & select hereCross-validate pipelinescaler → model in each foldRefit selected modelall training rowsHeld-out test splitnever used to tuneFinal reportmetrics + errors

Text equivalent of the pipeline: deduplicate the dataset and split it into training and held-out test partitions. Cross-validate the entire preprocessing-and-model pipeline using only training rows. Select settings, refit on all training rows, then evaluate once on the held-out test partition. The test branch bypasses model selection.

Imbalanced classification

With 90 negatives and 10 positives, predicting negative for every row gives 90% accuracy, zero positive recall, and 50% balanced accuracy. Compare against a baseline before celebrating accuracy.

Precision = TP / (TP + FP)
Recall = TP / (TP + FN)
F1 = 2PR / (P + R)

What to inspect

Use per-class metrics, confusion counts, average precision, PR/ROC curves, and validation learning curves. Average precision differs from trapezoidal PR area. Fold standard deviation is not a confidence interval.

Choose thresholds on validation data using error costs. If test-set error inspection guides changes, obtain a fresh test set. Stratification cannot fix duplicate, grouped, or time-dependent observations.

A pipeline prevents preprocessing leakage inside cross-validation. It cannot repair biased labels, an inappropriate split, or a dataset that does not represent future inputs.
Run the evaluation notebook ↗
06 / KEEP THE SYMBOLS STRAIGHT

Notation & further reading

n / d
Number of observations / features.
c / k
Classes; or neighbors, clusters, or components as stated.
V / E
Graph vertices / directed edges.
g(n) / h(n)
Cost paid / estimated remaining path cost.
η / I
Learning rate / optimization iterations.
Training / validation / test
Fit parameters / choose settings / final evaluation.

Complexities describe typical or explicitly stated implementations, not universal runtime guarantees. NumPy teaching models retain history for inspection and omit production optimizations. Browser experiments use illustrative data; they do not run Python models.

Learning path · Derivations and exercises · Classifier assumptions · Evaluation guide · Roadmap