Slides · Trees, ensembles and classical models

k-NN, k-means, PCA, SVM and naive Bayes: the classical toolkit

The classical toolkit

k-NN, k-means, PCA, SVM and naive Bayes: five cheap bets about distance and variance, and the data on which each one loses.

Concept

Why this is worth 85 minutes

  • These are the quickest baselines you can build, and they train habits that carry over: check units, check dimension, name the assumption.
  • Distance and variance break first on messy data, before any tuning matters.
  • A common interview topic (common industry pattern).

Five things you will be able to do:

  1. Explain k-NN, the choice of k and the curse of dimensionality.
  2. Run k-means by hand and say when it fails.
  3. Compute PCA step by step and choose components.
  4. Choose between k-NN, SVM, naive Bayes, trees and linear models.
  5. Say what mixtures, Isolation Forest and t-SNE add.

Diagram

The map

Diagram: Without labels you group rows (k-means, hierarchical clustering, DBSCAN) or compress columns (PCA).

no

no

yes

Do you have labels?

Group rows: k-means, hierarchical, DBSCAN

Compress columns: PCA

Predict: k-NN, SVM, naive Bayes, trees, linear

Diagram summary: Without labels you group rows (k-means, hierarchical clustering, DBSCAN) or compress columns (PCA). With labels you predict with k-NN, an SVM, naive Bayes, trees or a linear model.

Concept

k-NN: store, then vote

  • No model is fitted; the training set is stored (instance-based learning). Training is cheap, prediction is not.
  • A query is compared with every stored row: work grows like ndnd per prediction (derived).
  • Larger kk suppresses noise but blurs boundaries.
  • Each training row is its own nearest neighbour, so 1-NN scores 100% on its training data (barring duplicate rows with different labels) and says nothing about new data.

Source1 Nearest Neighbors (scikit-learn user guide)

Worked example

Choosing k, measured

A disc with 15% flipped labels (best possible 0.85), 200 training rows, median of 40 datasets:

kkValidation accuracy
10.723
50.792
150.791
510.747
  • Small kk: variance. Large kk: bias. Choose on validation data.

Source1 Nearest Neighbors (scikit-learn user guide)

Worked example

Scale decides the neighbours

Clean disc, 5-NN validation accuracy (median of 40 datasets):

ColumnsAccuracy
2 real columns0.950
plus 1 noise column, scale 10.883
plus 1 noise column, scale 1000.530
  • Always answering “outside the disc” scores 0.607 (derived), so 0.530 is worse than guessing.
  • Fit the scaler on training data only.

Check yourself

Check: who is the nearest neighbour?

A person is described by (age in decades, income in dollars). Query P = (4, 50,000). Candidate A = (6, 50,001) and candidate B = (4, 50,030). Which is nearer in Euclidean distance, and what does that say about the age column?

Answer

A is at distance 22+12=5≈2.2\sqrt{2^2+1^2}=\sqrt5\approx2.2 and B at 02+302=30\sqrt{0^2+30^2}=30, so A is nearer even though it is two decades older. Income, in large units, decides the distance and age is almost invisible. Standardise both columns first.

Worked example

The curse of dimensionality

200 uniform points in [0,1]d[0,1]^d, one random query, median of 10 queries:

ddnearest / farthest
20.04
100.37
1000.74
1,0000.91
  • Beyer et al. (1999): under broad conditions the nearest distance approaches the farthest; seen from about 10 to 15 dimensions in their experiments, and not in every workload.

Source2 When Is Nearest Neighbor Meaningful?

Compare

Irrelevant columns do the same damage

Noise columns added5-NN accuracy
00.950
20.833
80.645
320.560
  • Remedies keep fewer or better columns: feature selection, PCA, scaling, more data.
  • A model that learns which columns matter (regularised linear, tree ensemble) is often better (judgment).

Diagram

Lloyd’s k-means loop

Diagram: Pick starting centres, assign each row to the nearest, move each centre to the mean of its rows, and repeat until no assignment changes.

yes

no

Choose k starting centres

Assign each row to its nearest centre

Move each centre to the mean of its rows

Did any assignment change?

Stop: a local optimum

Diagram summary: Pick starting centres, assign each row to the nearest, move each centre to the mean of its rows, and repeat until no assignment changes. Each step can only lower the inertia, so the loop ends, at a local optimum that depends on the start.

Sources3 Clustering (scikit-learn user guide)4 CS229 lecture notes: the k-means clustering algorithm

Worked example

Worked example: six points

Points 1, 2, 4, 9, 10, 12; start with centres 1 and 2.

PassCentresJJNew centres
11, 22171, 37/5
21, 37/540.487/3, 31/3
37/3, 31/39.33unchanged: stop
  • In pass 2 the points 2 and 4 both switch to the first centre (4 is 3 from it, 3.4 from the other).
  • JJ fell 217, 40.48, 9.33 and never rose.

Check yourself

Check: why the update step cannot hurt

Assignments are fixed. Why does moving a centre to the mean of its rows never raise the inertia?

Answer

For a fixed set of rows, the sum of squared distances to a point cc is smallest when cc is the mean of those rows. Moving the centre to the mean can only lower (or keep) that cluster’s term. The assign step does the same job for the rows. Both steps lower JJ or leave it unchanged, so it converges, though possibly to a local optimum.

Compare

Initialisation: k-means++ helps, restarts still matter

500 single-start runs on five blobs (two pairs close together):

StartRuns within 1% of best JJWorst JJ
Random rows0.72898.1
k-means++0.87709.9
  • k-means++ draws each next centre with probability proportional to squared distance from the nearest chosen centre; O(log k)-competitive in expectation.
  • Its worst run was still 2.4 times the best JJ: restart and keep the lowest.

Sources5 k-means++: The Advantages of Careful Seeding6 KMeans (scikit-learn API reference)

Worked example

Choosing k

Four blobs 6 apart, best of 5 starts:

k23456
Inertia21931219403357322
Silhouette0.4600.5330.6720.5880.496
  • Inertia always falls with kk: look for the elbow. Silhouette s=(b−a)/max⁡(a,b)s=(b-a)/\max(a,b) peaks at 4.
  • Real data rarely has so clean a knee; also check stability and usefulness.

Source3 Clustering (scikit-learn user guide)

Compare

When k-means fails

FailureMeasuredFix
Rings (non-convex)purity 0.522DBSCAN, single linkage
Noise column in big unitspurity 0.520 raw, 0.970 standardisedStandardise
One outlier at (0, 100)took a cluster in 30 of 30 datasetsRemove, cap, or label as noise
  • Cause in all three: the objective is a sum of squared distances to a mean.

Source3 Clustering (scikit-learn user guide)

Compare

DBSCAN and hierarchical clustering

eps (min_samples 5)Clusters on two rings (median)Noise points (median)
0.31232
0.551
0.820
  • DBSCAN: dense regions of any shape, no kk, noise labelled -1; eps is crucial.
  • Hierarchical: merge the closest pair repeatedly; linkage (Ward, complete, average, single) defines closest. Single linkage separated the rings (purity 1.000) by following chains; sklearn calls it the worst for even sizes. A dendrogram records the merges.

Sources3 Clustering (scikit-learn user guide)7 DBSCAN (scikit-learn API reference)

Math

PCA in five steps

Xc=X−xˉ,Σ=1n−1Xc⊤Xc,Σvj=λjvj,Z=XcVkX_c = X-\bar{x},\qquad \Sigma=\frac{1}{n-1}X_c^{\top}X_c,\qquad \Sigma v_j=\lambda_j v_j,\qquad Z=X_cV_k
  1. Centre (scikit-learn does not scale).
  2. Covariance, dividing by n−1n-1.
  3. Eigenvectors sorted by eigenvalue λj\lambda_j.
  4. Ratio =λj/∑λ=\lambda_j/\sum\lambda.
  5. Project onto the top kk.

Sources8 PCA (scikit-learn API reference)9 CS229 lecture notes: principal components analysis

Worked example

Worked example: six points

Points (8,18), (9,19), (10,21), (10,22), (11,20), (12,20): means 10 and 20.

Σ=(2112),Σ(1,1)⊤=3(1,1)⊤,Σ(1,−1)⊤=1⋅(1,−1)⊤\Sigma=\begin{pmatrix}2&1\\1&2\end{pmatrix},\quad \Sigma(1,1)^{\top}=3(1,1)^{\top},\quad \Sigma(1,-1)^{\top}=1\cdot(1,-1)^{\top}
  • Ratios 3/4 and 1/4. PC1 is (1,1)/2(1,1)/\sqrt2.
  • Dropping PC2 leaves squared error 5 =(n−1)×1=(n-1)\times1.

Check yourself

Check: axis-aligned data

After centring, the covariance matrix has rows (3, 0) and (0, 1). What are the principal components and the explained variance ratios?

Answer

There is no correlation, so the eigenvectors are the original axes: PC1 is column 1 with eigenvalue 3 and PC2 is column 2 with eigenvalue 1. The ratios are 3/4 and 1/4. PCA rotates only when columns are correlated.

Concept

How many components

  • Add the sorted ratios until you reach a target such as 90% or 95%.
  • Five columns from two hidden factors: ratios 0.645, 0.329, then 0.009, 0.009, 0.008; cumulative 0.974 after two.
  • Reconstruction error /(n−1)/(n-1) equals the sum of the dropped eigenvalues (10.2990, 0.7595, 0.4886 for 1, 2, 3 kept; checked in the script).
  • The decisive test is the downstream validation score. Fit PCA on training data only.

Source8 PCA (scikit-learn API reference)

Worked example

When PCA misleads

CaseResult
Raw columns, one in big unitsPC1 carries 0.999998 of the variance, loads (0, 0, 1)
StandardisedPC1 carries 0.605, loads (0.706, 0.707, 0.036)
Class signal in a quiet column, 5-NN on PC10.508
Same, 5-NN on PC21.000
  • PCA never sees labels; it is linear; components mix all columns.

Source10 Decomposing signals in components: PCA (scikit-learn user guide)

Compare

Beyond k-means: mixtures and anomalies

MethodIdeaCatch
Gaussian mixture (EM)Each cluster a Gaussian with its own covariance; E step gives soft assignments, M step refitsLocal optimum; k-means is the default start; BIC picks the count; needs regularised covariances
Isolation ForestRandom splits; anomalies isolate in noticeably shorter pathsOutlier detection (dirty training data) is not novelty detection (clean training data)
PCA reconstruction errorA row’s error is its squared coordinate in the dropped directions (derived)Misses anomalies that sit inside the main subspace
  • Validate any anomaly score on a small labelled review set (judgment).

Sources11 Gaussian mixture models (scikit-learn user guide)12 Novelty and Outlier Detection (scikit-learn user guide)13 IsolationForest (scikit-learn API reference)

Concept

t-SNE and UMAP: maps, not features

  • t-SNE is for 2-3 D visualisation. Its objective is not convex, so seeds give different embeddings; global structure is not explicitly preserved; TSNE has no transform; reduce to about 50 dimensions with PCA or TruncatedSVD first.
  • UMAP can transform new data, but does not completely preserve density and can create false tears in clusters: cluster on it with care.
  • Kernel PCA is a non-linear option with transform; autoencoders come later in the course.

Sources14 Manifold learning (scikit-learn user guide)15 TSNE (scikit-learn API reference)16 Using UMAP for Clustering (UMAP documentation)17 Transforming New Data with UMAP (UMAP documentation)10 Decomposing signals in components: PCA (scikit-learn user guide)

Check yourself

Check: an anomaly flag

A fraud team has no labels. Which would you try first, a Gaussian mixture log-likelihood, Isolation Forest or t-SNE, and how would you know the flags are useful?

Answer

Isolation Forest or a mixture score both give a number per row; t-SNE gives a picture, not a score for new rows. Use a small labelled review set (for example analysts checking the top flags) to measure how many flags are real. That check is judgment, not part of the library.

Math

SVM: margin and hinge loss

min⁡w,b 12w⊤w+C∑imax⁡(0, 1−yif(xi)),margin width=2∥w∥\min_{w,b}\ \tfrac12 w^{\top}w + C\sum_i \max\big(0,\,1-y_i f(x_i)\big),\qquad \text{margin width}=\frac{2}{\|w\|}
  • Hinge loss is zero beyond margin 1: only points near or past the boundary matter (the hinge from the linear-models lesson).
  • Low CC: wide, smooth margin. High CC: narrow margin that fits training points.
  • Not scale invariant; no direct probabilities.

Source18 Support Vector Machines (scikit-learn user guide)

Worked example

The effect of C

Subgradient fit, 200 rows, median of 15 datasets:

CCMargin widthPoints with margin at most 1Validation
0.012.98970.932
0.11.58500.930
11.08330.930
100.69250.928
  • The margin narrows as CC grows. Accuracy differs by less than 0.01 on this easy data.

Concept

Kernels in brief

  • A linear SVM on a disc scores 0.604, the majority-class rate; adding the column x12+x22x_1^2+x_2^2 gives 0.978.
  • A kernel gets the lifted inner product without building the lifted columns: (x⋅z)2=x12z12+2x1x2z1z2+x22z22(x\cdot z)^2=x_1^2z_1^2+2x_1x_2z_1z_2+x_2^2z_2^2, the dot product of the lifted vectors (derived by expansion).
  • Kernels: linear, polynomial, RBF, sigmoid. RBF has γ\gamma.
  • Kernel SVC fit time grows between n2n^2 and n3n^3 times the features; LinearSVC scales almost linearly.

Sources18 Support Vector Machines (scikit-learn user guide)19 CS229 lecture notes: kernel methods and support vector machines

Math

Naive Bayes

P(y∣x) ∝ P(y)∏j=1dP(xj∣y),θ^yi=Nyi+αNy+αnP(y\mid x)\ \propto\ P(y)\prod_{j=1}^{d}P(x_j\mid y),\qquad \hat\theta_{yi}=\frac{N_{yi}+\alpha}{N_y+\alpha n}
  • Assumes features are independent given the class: about dd numbers per class instead of exponentially many.
  • Smoothing α\alpha stops an unseen word from vetoing a class.
  • A decent classifier, a poor probability estimator.

Sources20 Naive Bayes (scikit-learn user guide)21 CS229 lecture notes: generative learning algorithms (naive Bayes)

Worked example

Worked example: spam by hand

Counts: spam (buy 2, free 3, meeting 0), ham (1, 1, 4). Priors 2/5 and 3/5.

Messageα\alphaP(spam)
free buy0144/169 = 0.852
free buy181/113 = 0.717
meeting free00
meeting free127/107 = 0.252
  • Without smoothing one unseen word makes spam impossible.

Worked example

Why it works anyway, and when it does not

8 binary features, each right 65% of the time (50 datasets):

FeaturesAccuracyStated confidence
8 distinct0.8000.810
Each copied 3 times0.8000.928
First copied 20 times0.6501.000
  • Evenly repeated evidence inflates confidence but keeps the sign of the log-odds (derived, balanced classes).
  • One dominant duplicate outvotes the rest.

Check yourself

Check: a smoothed probability

In 100 spam words, the word “refund” never appears. The vocabulary has 50 words. What probability does multinomial naive Bayes with α=1\alpha=1 give “refund” under spam?

Answer

(0+1)/(100+1×50)=1/150≈0.0067(0+1)/(100+1\times50)=1/150\approx0.0067. Without smoothing it would be 0, and any message containing “refund” would be ruled out as spam.

Compare

Choosing between classical models

ModelReach for it when (judgment)Scaling?Probabilities?
Regularised linearBaseline, coefficient storyYesYes (logistic)
k-NNSmall data, few good columnsYesVote fractions
Linear SVMMany sparse columnsYesExtra step
Kernel SVMMedium data, curved boundaryYesExtra step
Naive BayesText, tiny dataGaussian: no; multinomial: yes (derived)Overconfident
Trees and ensemblesMixed-type tablesNoCheck calibration
  • Fit a linear baseline, add one flexible model, compare on the same folds.

Code

Two loops in a few lines

Python

import math

def lloyd_step(X, C):
    """One k-means pass: assign each row to its nearest centre, then move centres to the means."""
    lab = [min(range(len(C)), key=lambda j: math.dist(x, C[j])) for x in X]
    new = []
    for j in range(len(C)):
        rows = [x for x, l in zip(X, lab) if l == j] or [C[j]]   # keep an empty cluster's centre
        new.append([sum(c) / len(rows) for c in zip(*rows)])
    return lab, new

def covariance(Xc):
    """Covariance of centred rows, dividing by n - 1."""
    n, d = len(Xc), len(Xc[0])
    return [[sum(r[i] * r[j] for r in Xc) / (n - 1) for j in range(d)] for i in range(d)]
  • The full script, with k-means++, DBSCAN, PCA by Jacobi rotations, an SVM and naive Bayes, is in the lesson.

Summary

Recap

  • k-NN stores the data; choose kk on validation; scale columns; distances concentrate as dimension grows and noise columns wreck neighbours.
  • k-means alternates assign and update and ends at a local optimum: use k-means++ and restarts, and expect trouble with rings, unscaled columns and outliers.
  • PCA: centre, covariance, eigenvectors, project; pick components by the cumulative ratio, then check the downstream score; it misleads on units and quiet signal.
  • SVM: wide margin with hinge loss and CC; kernels lift without building columns. Naive Bayes: product of per-feature evidence, decent decisions, overconfident probabilities.
  • Mixtures are soft k-means with covariances; Isolation Forest scores anomalies; t-SNE is a map, not a feature.

References

References & Sources (1 of 5)

  1. Nearest Neighbors (scikit-learn user guide) (opens in a new tab)

    scikit-learn2026Documentation

    Used for Nearest-neighbour classification is instance-based, non-generalizing learning that stores the training instances and takes a majority vote; a larger k suppresses noise but makes class boundaries less distinct; a KD tree is very fast for D below 20 and inefficient as D grows (the curse of dimensionality); a ball tree can out-perform a KD tree in high dimensions, though its performance depends on the structure of the data.

  2. When Is Nearest Neighbor Meaningful? (opens in a new tab)

    Kevin Beyer, Jonathan Goldstein, Raghu Ramakrishnan, Uri Shaft1999ICDT 1999Paper

    Used for Under a broad set of conditions, as dimensionality increases the distance to the nearest data point approaches the distance to the farthest; the effect can occur for as few as 10 to 15 dimensions; it does not mean high-dimensional indexing is never meaningful, and some high-dimensional workloads avoid it. Read from the abstract and introduction of the paper PDF.

  3. Clustering (scikit-learn user guide) (opens in a new tab)

    scikit-learn2026Documentation

    Used for K-means minimises inertia (within-cluster sum of squares) and assumes convex, isotropic clusters; it may converge to a local minimum that depends on initialisation, so it is run several times; k-means++ is the scikit-learn initialisation; PCA before k-means can help in very high dimensions; the silhouette coefficient s = (b - a) / max(a, b); DBSCAN core samples, eps and min_samples, noise labelled -1, arbitrary shapes, and eps being crucial; hierarchical linkage criteria (Ward, complete, average, single), the cost without connectivity constraints, and single linkage giving the most uneven cluster sizes. DBSCAN assumes a globally homogeneous density and may struggle with clusters of different densities (HDBSCAN section). The guide requires k to be specified and points to silhouette analysis as an example, not a rule for choosing it.

  4. CS229 lecture notes: the k-means clustering algorithm (opens in a new tab)

    Andrew Ng2020Book

    Used for K-means is coordinate descent on the distortion J (sum of squared distances to the assigned centroid), so J decreases monotonically and converges; J is non-convex so k-means can reach a local optimum; the suggested remedy is several runs from different random initial centroids, keeping the clustering with the lowest J.

  5. k-means++: The Advantages of Careful Seeding (opens in a new tab)

    David Arthur, Sergei Vassilvitskii2007SODA 2007Paper

    Used for Lloyd's algorithm assigns points to the nearest centre and recomputes centres as the mean, and the squared-distance potential decreases monotonically; k-means++ seeds by choosing centres at random from the data points weighted by squared distance to the closest centre already chosen; the seeding is O(log k)-competitive with the optimal clustering; experiments show better speed and accuracy. Read from the abstract and introduction.

References

References & Sources (2 of 5)

  1. KMeans (scikit-learn API reference) (opens in a new tab)

    scikit-learn2026Documentation

    Used for init defaults to k-means++ (the greedy variant, which makes several trials per sampling step) and n_init='auto' means 1 run for k-means++ and 10 for random init; Lloyd's algorithm is the classical EM-style default; inertia_ is the sum of squared distances to the closest centre; in practice k-means is very fast, one of the fastest clustering algorithms available, but falls in local minima so restarts are useful.

  2. DBSCAN (scikit-learn API reference) (opens in a new tab)

    scikit-learn2026Documentation

    Used for min_samples is the number of samples in a neighbourhood for a point to be a core point, and this includes the point itself; eps is the most important DBSCAN parameter; smaller values generally lead to more clusters.

  3. PCA (scikit-learn API reference) (opens in a new tab)

    scikit-learn2026Documentation

    Used for PCA is linear dimensionality reduction using the SVD, with the input centred but not scaled; a number between 0 and 1 for n_components selects the number of components whose explained variance exceeds that fraction (with svd_solver='full'); explained_variance_ratio_; explained_variance_ uses n_samples - 1 degrees of freedom and equals the largest eigenvalues of the covariance matrix.

  4. CS229 lecture notes: principal components analysis (opens in a new tab)

    Andrew Ng2020Book

    Used for Preprocess by normalising each feature to mean 0 and variance 1 (the rescaling may be omitted when the features share a scale, as with pixel intensities); maximising the variance of the projection gives the principal eigenvector of the covariance matrix, and the top k eigenvectors for a k-dimensional projection. The notes use 1/n in the covariance.

  5. Decomposing signals in components: PCA (scikit-learn user guide) (opens in a new tab)

    scikit-learn2026Documentation

    Used for Kernel PCA is non-linear dimensionality reduction through kernels and supports transform and an approximate inverse_transform. PCA decomposes a multivariate data set into successive orthogonal components that explain a maximum amount of the variance; it centres but does not scale each feature before the SVD; components are exclusively dense linear combinations of the original variables.

References

References & Sources (3 of 5)

  1. Gaussian mixture models (scikit-learn user guide) (opens in a new tab)

    scikit-learn2026Documentation

    Used for A Gaussian mixture assumes data from a mixture of Gaussians with unknown parameters and generalises k-means by including covariance structure; spherical, diagonal, tied or full covariance; EM computes per-point component probabilities then maximises the likelihood and converges to a local optimum; default initialisation uses k-means; BIC can select the number of components but recovers the true number only asymptotically; with too few points per component the covariances can diverge to infinite likelihood unless regularised.

  2. Novelty and Outlier Detection (scikit-learn user guide) (opens in a new tab)

    scikit-learn2026Documentation

    Used for Outlier detection (unsupervised anomaly detection: training data may contain outliers) versus novelty detection (clean training data, judging new observations); Isolation Forest randomly selects a feature and a split value, path length averaged over a forest is the normality measure, and random partitioning gives anomalies noticeably shorter paths.

  3. IsolationForest (scikit-learn API reference) (opens in a new tab)

    scikit-learn2026Documentation

    Used for IsolationForest isolates observations by random feature and split value; the score is the average path length; shorter paths are highly likely to be anomalies; contamination sets the threshold.

  4. Manifold learning (scikit-learn user guide) (opens in a new tab)

    scikit-learn2026Documentation

    Used for The main purpose of t-SNE is visualisation, best in two or three dimensions; the KL objective is not convex and different seeds give different embeddings; global structure is not explicitly preserved (PCA initialisation mitigates it).

  5. TSNE (scikit-learn API reference) (opens in a new tab)

    scikit-learn2026Documentation

    Used for TSNE exposes fit and fit_transform but no transform; the cost function is not convex; it is highly recommended to reduce very high-dimensional data first with PCA (dense) or TruncatedSVD (sparse), for example to 50 dimensions.

References

References & Sources (4 of 5)

  1. Using UMAP for Clustering (UMAP documentation) (opens in a new tab)

    UMAP project2026Documentation

    Used for UMAP, like t-SNE, does not completely preserve density and can create false tears in clusters; clustering on its output should be attempted with care; use a density-based method and validate the clusters.

  2. Transforming New Data with UMAP (UMAP documentation) (opens in a new tab)

    UMAP project2026Documentation

    Used for UMAP can transform unseen data with the transform method; transform is somewhat slow and assumes a consistent data distribution.

  3. Support Vector Machines (scikit-learn user guide) (opens in a new tab)

    scikit-learn2026Documentation

    Used for SVMs are effective in high-dimensional spaces and memory efficient because they use a subset of training points (support vectors); they do not directly provide probabilities (an expensive five-fold cross-validation); they are not scale invariant; the linear SVM objective 1/2 w^T w + C sum of hinge terms; low C gives a smooth decision surface and high C aims to classify all training examples correctly; LinearSVC uses the squared hinge loss and regularises the intercept; SVC fit time scales between n_features x n_samples^2 and n_features x n_samples^3, while LinearSVC scales almost linearly; the linear, polynomial, RBF and sigmoid kernels and the RBF gamma parameter.

  4. CS229 lecture notes: kernel methods and support vector machines (opens in a new tab)

    Andrew Ng, Tengyu Ma2020Book

    Used for The introduction states that kernels give a way to apply SVMs efficiently in very high or infinite-dimensional feature spaces; that is the only claim used. Margins and derivations were not read for specifics.

  5. Naive Bayes (scikit-learn user guide) (opens in a new tab)

    scikit-learn2026Documentation

    Used for Naive Bayes assumes conditional independence between every pair of features given the class; it has worked quite well in many real-world situations, famously document classification and spam filtering; it is a decent classifier but a bad estimator, so predict_proba outputs are not to be taken too seriously; Laplace/Lidstone smoothing alpha with the multinomial estimate (N_yi + alpha) / (N_y + alpha n) prevents zero probabilities; naive Bayes learners can be extremely fast and need a small amount of training data.

References

References & Sources (5 of 5)

  1. CS229 lecture notes: generative learning algorithms (naive Bayes) (opens in a new tab)

    Andrew Ng2020Book

    Used for Modelling p(x | y) over a 50,000-word vocabulary directly would need an enormous number of parameters, so the Naive Bayes assumption of conditional independence given y is made; the notes call it an extremely strong assumption and say the resulting algorithm works well on many problems.