Machine learning and AI

You write the rules. Or you let the machine find them.

A full engineering course in fourteen lessons, rewritten so anyone can follow it. No maths background required, nothing important left out.

14lessons, all on this page
99kwords distilled
0maths prerequisites
9things you can play with
00

Lesson zero

What machine learning actually is

Normally a programmer writes the rules. Machine learning flips this around: you hand over the data and the answers, and let the program work out the rules itself. The term dates to 1959, when Arthur Samuel at IBM built a program that learned to play draughts and described his field as giving computers the ability to learn without being explicitly programmed.

The two great families

Every technique in this course sits in one of these two boxes.

Machine learning Supervised the answers are given Unsupervised no answers at all Regression predict a number "what is the rent?" Classification predict a label "is this spam?" Clustering find the groups "who resembles whom?"
A person working through code on a laptop

Supervised learning is a music lesson

Your teacher plays an indie rock track and says "this is indie rock". Then a K-pop track. Then techno. After enough examples, you hear a song you have never heard and name the genre.

A fraud detector works the same way: thousands of past transactions, each marked fraudulent or not. Every time you complete a captcha and tick the squares with cars in them, you are producing labelled examples for somebody's model.

It splits by the kind of answer you want. Regression predicts a number on a continuous scale: the rent of a flat, the value of a currency. Classification predicts a label from a fixed set: spam or not spam (binary), pear or apple or peach (multi-class), or several tags at once for the same photo (multi-label).

Coloured straws arranged in a pattern

Unsupervised learning is an alien watching lunch

Imagine an alien embedded in a tech startup, watching people eat. Over a few weeks it notices that mornings involve cereal, bagels and granola bars. Lunch is a vegetable, a protein and a grain. Snacks are fruit or nuts.

Nobody explained meals. It grouped the observations by itself. That is clustering, and the interesting part is that it often groups things along lines a human would never have thought to draw.

The shape every model shares

from sklearn.linear_model import LinearRegression reg = LinearRegression() reg.fit(X, y) # learn the rule from the examples y_pred = reg.predict(new_X) # apply it to something unseen

Create the model, call .fit() on the data, call .predict() on something new. Almost every model in scikit-learn follows that pattern, which is why the library is worth learning once and reusing everywhere.

01

Lesson one

Features: preparing the data

A feature is one measurable thing about each item: the temperature, the number of bedrooms, the colour of the car. Real data arrives in the wrong units, on wildly different scales, and written as words rather than numbers. Fixing that is not a preliminary chore. It is frequently the difference between a model that works and one that does not.

Four ways a model can be broken

  • Performance. If it cannot predict the outcome on data it has already seen, it is reckless to trust it on data it has not.
  • Runtime. A model can be accurate and still take so long to run that it is useless in production.
  • Interpretability. An opaque model cannot answer "what actually drives this?", which is often the real question.
  • Generalisability. Data keeps arriving. The model has to keep working on data that looks slightly different.

Feature engineering is the set of knobs for each of the four.

Why scale matters, and what it does to a model

Two features on very different scales. Drag the slider to standardise them and watch the cloud become readable.

01

Centring

Subtract the mean so the new average is zero. Every value now tells you how far above or below average it sits.

02

Standardising

Centre, then divide by the standard deviation. Mean 0, spread 1. Required before PCA, k-means, k-nearest neighbours and any regularised model.

03

Min-max

Squash everything between 0 and 1. Simple, but one extreme outlier ruins it: 99 values between 0 and 40 plus a single 100 leaves the 99 crushed into 0 to 0.4.

04

Binning

Group a continuous number into buckets. Too narrow and the noise survives, too wide and the pattern is flattened. There is no rule, only judgement.

05

Log transform

Rescues right-skewed data. Odometer readings from 10,126 to 151,687 miles become 9.22 to 11.93. Not for negative values or left-skewed data.

06

Encoding

Turn words into numbers. Ordinal data has a real order (excellent, good, fair). Nominal data does not (black, white, blue).

The trap that catches everyone. Numbering colours black=2, blue=3, white=18 quietly tells the model that white cars are six times more something than blue ones. There is no such relationship, but the model cannot know that. For nominal data, one-hot encode: give every category its own yes/no column so no ordering is implied.
02

Lesson two

Linear regression and gradient descent

The simplest model you can fit to data is a straight line. Fitting it means finding two numbers: the slope and the intercept. Gradient descent is how you find them, and it is the same idea that trains almost everything else in modern AI.

For each data point the model's prediction is wrong by some amount, called the loss. We use the squared distance from the point to the line, so that points above and below both count against us equally. If point A sits 3 units away it contributes 9; point B at 1 unit contributes 1; total loss 10. Any line with a lower total is a better model.

Now picture that loss as a landscape. Move the slope and intercept around and the loss rises and falls like terrain. Somewhere there is a valley floor, and you want to stand in it. The gradient points uphill in the steepest direction, so stepping in the opposite direction takes you down. Repeat enough times and you reach the bottom. That is the whole algorithm.

Gradient descent, and why the step size decides everything

The curve is the loss. The dot is your current guess. Press run and watch it walk downhill. Then try a learning rate at each end of the slider.

0.030

Too small

One inch at a time. You will get there eventually, or run out of time and cycles first.

About right

Big steps while the slope is steep, small ones as it flattens. Settles in the valley. This is convergence.

Too large

A mile per step. You clear the valley entirely and end up on a mountain. The loss goes up and never settles.

A laptop showing a data chart

Reading the result

House price does not depend only on size. Multiple linear regression uses many inputs at once, and returns one coefficient per feature. A positive coefficient means the output rises with the input, a negative one means it falls, and near zero means the feature barely matters.

The summary score is R squared: the percentage of the variation in the output that your inputs together explain. On 5,000 New York rentals, the Manhattan model scored 0.81 on the test set and the Brooklyn model 0.58, which says something important was missing from the Brooklyn feature set.

There is a second route to the same answer, ordinary least squares, which solves it exactly with matrix algebra instead of iterating. It breaks on multicollinearity (two features that are linear copies of each other, such as temperature in both Fahrenheit and Celsius) and it gets expensive on very large data. Scikit-learn gives you both: LinearRegression uses OLS, SGDRegressor uses gradient descent.

Why this one idea keeps coming back. Gradient descent works on any model whose loss is a smooth function of its parameters. Logistic regression, support vector machines, neural networks. Whenever the loss looks like rolling terrain, even terrain in thousands of dimensions you cannot picture, you can walk downhill on it.

03

Lesson three

Classification basics

Regression gives you a number. Classification gives you a label. The two workhorses are logistic regression, which bends a straight-line model so its output is always a probability, and k-nearest neighbours, which classifies a new point by looking at what its closest neighbours are.

Why the straight line fails, and the trick that fixes it

Predict whether a student passes an exam from hours studied. The answer is 1 or 0. Fit a straight line and it will happily predict 1.4, or -0.3. Neither means anything.

Logistic regression applies a logit link function to the linear equation, so it predicts the log-odds of the outcome rather than the outcome. The result is an S-shaped curve that never goes above 1 or below 0, and the output can honestly be read as a probability.

The odds of an event are the probability it happens divided by the probability it does not. A student with a 0.7 chance of passing has odds of 0.7/0.3 = 2.33, so they are 2.33 times more likely to pass than fail. Odds can only be positive, running from 0 to infinity. Take the natural logarithm and you stretch that into the full range from negative to positive infinity, which is exactly what a linear equation produces. The inverse, the sigmoid, turns it back into a probability.

The sigmoid: how a line becomes a probability

The straight line runs off to infinity in both directions, which is meaningless for a yes-or-no question. The curve never leaves the range 0 to 1.

The threshold is a decision, not a fact. Scikit-learn calls anything at or above 0.5 a positive. That is a convention, not a law. For a cancer screen, telling someone they are clear when they are not is far worse than the reverse, so you lower the threshold to 0.3 or 0.4 and accept more false alarms. Set it according to which mistake costs more. That is a domain decision, not a statistical one.

K-nearest neighbours: ask the neighbours

Points with similar attributes tend to fall into similar categories. To classify an unknown point, find the k points nearest to it and take a vote.

The value of k changes the answer. With k = 3 the circle around an unknown point might catch two green neighbours and one red, so it is green. Widen it to k = 5 and it catches three red and two green, so the same point is now red.

Watch k decide the answer

The white point is unclassified. The circle expands as you raise k. The vote is recounted at every step.

Normalise, or the biggest number wins

The largest gap between two film release dates is about 125 years. The largest gap between two budgets is hundreds of millions. The distance formula treats all dimensions equally, so a 70-year gap counts exactly the same as a 70-dollar gap. Budget swamps everything. Normalising is not optional here.

The regression version

Identical, except that instead of voting on labels you average their values. Better still, weight the average by closeness: three neighbours rated 5.0, 6.8 and 9.0 give a plain mean of 6.93, but if the 9.0 is by far the most similar film, the weighted answer is 7.9.

04

Lesson four

Decision trees

A decision tree is a flowchart of yes-or-no questions. Follow the answers down the branches and you arrive at a leaf, which holds the prediction. The clever part is not following the tree, it is building it: at every branch the algorithm has to decide which question to ask, and it does that by measuring how much each possible question tidies up the data.

Gini impurity: putting a number on the mess

A leaf containing a 50-50 mixture is a coin flip. A leaf containing one class only is certain. Gini impurity measures where you sit between the two.

Information gain: which question helps most

Impurity alone does not tell you which feature to split on. Information gain does: it is how much impurity the split removed.

Take a real car-acceptability tree. The root node has impurity 0.4185. Split on safety rating, pushing 912 higher-safety cars left and 470 low-safety cars right, and the two new impurities are 0.495 and 0 (a perfectly pure leaf). Weight them by how many samples went each way and the combined impurity is 0.3267.

Information gain = 0.4185 - 0.3267 = 0.0918

The data is tidier after the split than before. The higher the gain the better, and a gain of zero means the split was useless. The algorithm calculates this for every possible feature at every node and takes the winner. Then it recurses, and stops when no feature produces any gain at all. That node becomes a leaf.

A tree, and where the questions come from

Splits go True to the left, False to the right. The greener a node, the purer it is.

safety rating is low? 1382 cars · gini 0.418 False True seats only 2 people? 912 cars · gini 0.495 not acceptable 470 cars · gini 0 · a leaf keep splitting 604 cars · gini 0.434 not acceptable 308 cars · gini 0 · a leaf

What trees are good at

They are interpretable: you can read the decision path and explain it to anyone, which almost no other model gives you. They need almost no data preparation, no scaling or normalising. And they are fast to train and to predict.

The two real weaknesses

They are greedy: each split takes the best immediate gain without considering what it does further down, so the tree is never globally optimal. And they overfit: left to grow freely a tree memorises the training set. Limit the depth, prune it, or use many trees instead of one.

05

Lesson five

Judging a model: accuracy is usually the wrong measure

Build a spam filter for top-secret government accounts that never receive spam. Write a classifier that answers "not spam" every single time. It will be astonishingly accurate, and it will never find a single spam email, which was the entire point.

Split the data three ways, before you touch it

  • Training set. What the model learns from. This is where learning happens.
  • Validation set. Used during training to tune hyperparameters and guide decisions. The model does not learn its parameters here, but you use it to make choices, so it is no longer neutral.
  • Test set. Determines the performance of the final model. Often called the holdout set, because the moment you use it to make a decision it stops being an unbiased measure.

Around 70 percent training and 15 percent each for validation and test is a sensible start. When the dataset is too small to carve up, use n-fold cross-validation: divide the training data into N chunks, rotate which one serves as validation, and average the results. Every point gets a turn, so you learn how the model performs on average rather than how it happened to perform on one arbitrary slice.

Move the threshold. Watch the trade you are making.

A medical test on 200 patients. The slider is the probability above which the model calls a case positive. There is no setting that makes both kinds of mistake disappear.

0.50
Predicted no
Predicted yes
Actually no
0true negative
0false positive
Actually ill
0false negative
0true positive
0Accuracy
0Precision
0Recall
0F1

Recall asks: of all the real positives, how many did the model find? Precision asks: of everything the model flagged, how much really was? Recall alone is gameable, because a classifier that answers "spam" every time has perfect recall and useless precision. So the F1 score combines them using the harmonic mean, which punishes imbalance: a model with recall 1 and precision 0.02 has a plain average of 0.51, which sounds acceptable, and an F1 of about 0.04, which correctly says it is a disaster.

Your situationWatch thisBecause
Balanced classes, both mistakes cost the sameAccuracySimple and honest when nothing is skewed
Missing a positive is expensive: disease, fraud, safetyRecallOf all the real cases, how many did you find?
A false alarm is expensive: blocking real users, wasted calloutsPrecisionOf everything you flagged, how much was real?
You need one number and both errors matterF1Falls towards zero if either precision or recall does
Predicting a number rather than a labelR squared, RMSEThere are no positives and negatives to count

Decide which of these matters before you build the model. Deciding afterwards means picking whichever number flatters your work.

06

Lesson six

Choosing which features matter

You are predicting a disease from patient records with hundreds of measurements. Having all that data is a good position to be in; feeding all of it to a model is not. Many columns duplicate each other, many are irrelevant, and every irrelevant one adds noise.

FamilyHow it worksAdvantageDrawback
FilterRank features by a statistical test, before any model existsCheap, works with any modelCannot see relationships between features
WrapperFit a model on a subset, score it, try another subsetOptimal for your specific model, sees interactionsExpensive: refits for every subset
EmbeddedSelection happens during model fittingSees interactions, cheaper than wrappersOnly works with models that support it

A worked filter pass

Ten pupils, six features, predicting exam score. Three features get eliminated in three steps:

  • Variance threshold drops grade_level. Every pupil is in year 8, so it carries no information at all.
  • Pearson's correlation drops hours_TV. It correlates at -0.78 with hours_study, so the two say the same thing from opposite directions. Keep the one more strongly correlated with the target.
  • Mutual information drops height_cm, which scores exactly 0 against exam score.
Never drop a feature on correlation alone. In that same dataset, hours_sleep has a Pearson correlation of 0 with exam score, and a mutual information score of 0.186. There is a relationship, but it is not a straight line, so correlation could not see it. Pearson only detects linear relationships. Mutual information detects dependence of any shape, and works on discrete variables too.

Forward selection

Start with nothing, add the most helpful feature each time. On a forest fire dataset, one feature reached 93.9 percent accuracy, two reached 97.5, three reached 98.0. The full six-feature model managed 98.4.

Backward selection

Start with everything, remove the least missed each time. It often lands on a different set from forward selection on the same data, which tells you something about how contingent these choices are.

Recursive elimination

Rank by coefficient size, drop the weakest, retrain, repeat. Much faster than backward selection because it fits one model per removal rather than one per candidate. Standardise first or the ranking is meaningless.

Feature importance, and its blind spot

Gini importance is nearly free, because it falls out of training a tree. But it is biased towards numerical features over categorical ones, and it ignores correlation: if two correlated features are both important, one may show near-zero importance because all its explanatory power was credited to the other. Permutation importance avoids that by shuffling one feature and measuring how much accuracy drops, and it works with any model, at the cost of refitting many times.

07

Lesson seven

Learning without labels

So far every model has been shown the right answers. Unsupervised learning has none. It is given raw data and must find the structure itself, which turns out to be useful in three ways: grouping things that belong together, squeezing many features into a few, and labelling data that arrived unlabelled so supervised methods can then be used on it.

K-means, one step at a time

The crosses are centroids. Press step to assign every point to its nearest centroid, then move each centroid to the average of what it captured. Repeat until nothing moves.

iteration 0

When the points stop changing cluster and the centroids stop shifting, the algorithm has converged. That iterative process is the training. Assigning a new point afterwards is instant, and that is called inference.

On the classic Iris flower dataset, which happens to come with true species labels, you can check the result against reality: setosa clusters perfectly, versicolor about 96 percent correctly, and virginica poorly. That is a fair picture of what unsupervised learning can do. It found real structure without being told anything, and it did not exactly recover the botanical categories, because the measurements alone do not fully separate them.

Choosing how many clusters: the elbow

Inertia measures how tightly bunched the clusters are. It always falls as you add clusters, so the trick is to stop at the bend, where extra clusters stop paying off.

Principal component analysis

Two features are easy to look at. Twenty are not, and both computation and complexity start to bite. PCA builds new features that are mixtures of the old ones, ordered by how much information each carries. Information here means variance: a column where every row reads 500 has data but no information.

Mathematically it computes a covariance matrix, then finds its eigenvectors, the directions in which to rotate the whole dataset so it can be viewed from a simpler angle, and their eigenvalues, which say how much variation each direction accounts for. The trade-off is interpretability: the new axes no longer correspond to "revenue" or "amount of cheese", they are weighted mixtures of everything.

How many components do you actually need?

A sixteen-feature bean dataset. The bars are how much each component explains; the line is the running total. Four components carry 95 percent of the information.

Does it work? Measurably.

A classifier trained on those four principal components scores comparably to one trained on all sixteen original features. Training is faster, and there is a second benefit: the principal axes are uncorrelated with each other by construction, which often improves performance in its own right.

The eigenface demonstration

An image is a row of numbers, one per pixel. Run PCA on 4,096-pixel face images and the components come out as ghostly composite faces. Rebuild the originals from under 1 percent of the features and they are still clearly recognisable.

08

Lesson eight

Advanced classifiers

Three more ways to sort things into categories. Naive Bayes updates a prior belief with new evidence, which makes it excellent at text. Support vector machines find the widest possible corridor between two classes. Linear discriminant analysis finds the single direction along which the classes separate best.

The doctor's problem

A test for a rare disease is correct 99 percent of the time. The disease affects 1 in 100,000 people. The test comes back positive. Does your patient have it?

Intuition says almost certainly yes. Intuition is badly wrong. There are two ways to get a positive:

p_disease_and_correct = (1 / 100000) * 0.99 # 0.0000099 p_no_disease_and_incorrect = (99999 / 100000) * 0.01 # 0.0099

Both are rare, but the second is about a thousand times more likely than the first. A positive result is overwhelmingly more likely to be a false alarm than a real case, because the disease is so much rarer than the test's error rate. This works because we used more than the accuracy of the test: we used how rare the disease is. That extra information is the prior, and Bayes' theorem is how you combine the two.

Why "naive"

To classify a review, the algorithm needs the probability of that exact sequence of words. Intractable, so it assumes each word is independent of the others. That is plainly false about language, which is why it is called naive. It works remarkably well anyway.

Smoothing, and why typos would otherwise kill it

If a word never appears in the training data its probability is 0, and since everything multiplies, the whole calculation collapses. A single typo in a real review would do it. So add 1 to every numerator and N to every denominator, and no term is ever zero.

Support vector machines: the widest corridor

There are infinitely many lines that separate two classes. The best one is furthest from the training points on both sides. Drag C to see the model trade margin width against tolerating outliers.

The support vectors are the training points closest to the boundary, and they define it. Every other training point can be ignored, which is why SVMs are fast: most algorithms use every point to make a prediction, even the irrelevant ones.

When no straight line can separate the classes at all, kernels transform the data so that it can. A polynomial kernel maps each two-dimensional point into three dimensions, where the classes pull apart and a flat plane separates them; project that plane back down and you have a curved boundary. The default in scikit-learn is the radial basis function kernel, which maps into an infinite number of dimensions. Its gamma parameter behaves like C: high gamma overfits, low gamma underfits.

Do not reach for a kernel too early. If a dataset is nearly separable by a straight line and fails only because of a handful of outliers, drawing a boundary that correctly separates every single point is textbook overfitting. Most models should tolerate some error.

LDA, and how it differs from PCA

Both reduce dimensions using linear algebra. The difference is what they optimise for. PCA maximises overall variance and ignores the labels entirely, which makes it unsupervised and well suited to regression. LDA maximises class separation and uses the labels, which makes it supervised and suited to classification.

On a wheat seed dataset with seven features, logistic regression scored 0.943. Compress to a single LDA dimension first and it scores 0.993. The one-dimensional version is more accurate than the seven-dimensional one, because the compression removed noise as well as dimensions.

LDA has real constraints, though. The smallest class must have more observations than there are variables, the variables must be roughly normal, and every class must have a similar covariance matrix. It is also sensitive to outliers and prone to overfitting.

09

Lesson nine

Regularisation and tuning

Every model has to answer one question: how well does it generalise from the data it has seen to data it has not? Regularisation is the technique that keeps it accurate there, and it works by punishing the model for having large coefficients. Machine learning models are rarely put into production without it.

The bias-variance tradeoff

Slide model complexity from simple to elaborate. Training error only ever falls. Test error, the one you actually care about, is a U.

Underfitting is high bias

The structure of the model overpowers the data. It performs badly on the training set and the test set. In k-nearest neighbours this is k set too high: every unknown point gets the same answer, and distance stops mattering.

Overfitting is high variance

The data overpowers the structure. Excellent on training data, poor on test data. In k-nearest neighbours this is k set to 1: one stray outlier dictates the label of everything near it. The model has memorised a coincidence.

A set of balance scales

Lasso and ridge, and why the shape matters

Regularisation adds a penalty for large coefficients to the loss function. Training performance gets worse. That is the point: you are trading accuracy on data you have already seen for accuracy on data you have not.

L1, or lasso, uses the sum of absolute coefficients, which confines the answer to a diamond. Diamonds have corners on the axes, and the solution tends to land on one, which sets a coefficient to exactly zero. Zero means the feature is gone. Lasso shrinks and selects.

L2, or ridge, uses the sum of squared coefficients, which confines the answer to a circle. Circles have no corners, so coefficients get arbitrarily small but never reach zero. Nothing is eliminated, but relative importance is sharpened.

On a real student dataset, adding lasso raised the training error from 2.63 to 3.01 and lowered the test error from 4.99 to 4.27, and zeroed more than half the coefficients. Exactly the intended trade.

Searching for the right setting

Alpha sets the strength. It is a hyperparameter: unlike a coefficient, it is not learned during fitting, you choose it beforehand. Too small and you have effectively no regularisation. Too large and the coefficients are crushed and the model underfits.

alpha_array = np.logspace(-6, 0, 100) model = GridSearchCV(estimator=Lasso(), param_grid=[{'alpha': alpha_array}], scoring='neg_mean_squared_error', cv=5, return_train_score=True) model.fit(X, y) print(model.best_params_) # {'alpha': 0.1233}

That is 100 alpha values across 5 cross-validation folds, so 500 model fits, in four lines. logspace is the right tool when you have no idea of the order of magnitude, because it spaces values evenly on a logarithmic scale. Note neg_mean_squared_error: GridSearchCV maximises whatever score it is given, so the metric is negated.

Two things that catch people out in scikit-learn. Logistic regression is already regularised by default, with L2 and C=1.0; there is no unregularised default. And it takes C, not alpha, where C is the inverse of alpha, so a higher C means less regularisation.

There are four ways to search a hyperparameter space. Grid search tests every value on a list: exhaustive within the grid, and blind to everything outside it. Random search draws from a probability distribution instead, and often finds a good answer with far fewer fits because it explores more widely. Bayesian optimisation uses each evaluation to decide where to look next. Genetic algorithms mutate the best performers of each generation to produce the next.

Training accuracyValidation accuracyTest accuracy
alpha = 185%80%
alpha = 285%84%82%
alpha = 388%83%

Alpha of 2 wins on the validation set, so that is your choice. But you cannot then quote 84 percent as the model's accuracy, because that number came from the data you used to make the choice. The honest figure is 82 percent, measured once, on the test set. Train on the training set. Tune on the validation set. Report on the test set, once.

10

Lesson ten

Ensembles: many models, one answer

Why use one model when you can use a thousand? Ensemble learning builds a strong model out of deliberately weak ones. Counter-intuitively the parts are chosen to be bad: combining strong models is expensive and does not necessarily help, so you may as well use learners that cost less. What matters is that they are diverse, because their mistakes then cancel out.

The three ways to combine models

Which one you pick depends on how the base models are weak.

BAGGING parallel, independent majority vote base models overfit high variance random forest BOOSTING sequential, each fixes the last weighted sum base models underfit high bias AdaBoost, gradient boosting STACKING a model learns the weights a second model any models, even different kinds, even strong ones feature augmentation

Bootstrapping, the trick underneath bagging

Sampling with replacement. Put all 1,000 rows in a bag, pull one out, write it down, and put it back. Repeat 1,000 times. Because you replace each row you can draw the same one more than once, which is why you can draw 1,000 rows from 1,000 rows and still get a genuinely different dataset every time.

Each base model then trains on a different bootstrapped sample and a different random subset of features, so each overfits to a different slice. Their errors are uncorrelated, and averaging cancels most of them out.

A forest seen from above

The random forest, literally

A single decision tree is readable and fast, and it overfits badly. A random forest builds hundreds of them, each on a different bootstrapped sample, each drawing a fresh random handful of features at every split.

Every tree gets a vote and the most popular answer wins. Some individual trees are overfitted, but with enough of them, overfitting stops mattering. The rule of thumb for how many features to consider at each split is the square root of the total: with 25 features, draw 5.

AdaBoost changes the data

Fit a decision stump, a tree with a single split. Weight it by how few errors it made. Then give the points it got wrong a larger weight, so the next stump is pushed to pay attention to them. Repeat, and aggregate as a weighted sum.

Gradient boosting changes the target

Fit a model, then compute its residual errors. Fit the next model on those errors, not on the original target. It is literally learning the previous model's mistakes. Multiply by a learning rate, add to the running prediction, and repeat.

Stacking, and the overfitting trap inside it

Your decision tree generalises badly because it overfits. Your logistic regression is hard to tune because the features are correlated. Each has an advantage the other lacks, so use both, and train a later-stage model to learn how much to trust each one.

The catch is that if the base models predict on data they were trained on, those predictions are contaminated. The fix is K-fold cross-validation: train each estimator on nine folds, predict on the excluded tenth, and append those predictions as new columns. Rotate until every row has been augmented. The final model then sees not the raw data but what each estimator thought, and learns how to weigh the opinions.

11

Lesson eleven

The workflow and the pipeline

Everything so far has been a technique. This is the order you apply them in, and the tool that turns that order into code you can hand to someone else.

The ten-step workflow

No two projects sequence these identically, and steps get merged or skipped. The principle behind step 3 never moves.

Split before you transform anything. If you standardise the whole dataset first, the mean you used carries information from the test set into the training set. Your evaluation stops being honest. This is called data leakage, and it is the most common reason a model looks better in development than it performs in production.
An industrial assembly line

A pipeline is that workflow, written once

Doing it by hand means computing the training mean, filling the training set, fitting the scaler, transforming, then carefully repeating on the test set using the training statistics. Seven lines, and an easy opportunity to leak.

pipeline = Pipeline([ ("imputer", SimpleImputer()), ("scale", StandardScaler()), ("regr", LinearRegression()) ]) pipeline.fit(x_train, y_train)

Two lines, and it cannot make that mistake. Every intermediate step must have .fit() and .transform(); only the final step is allowed to be a model, which is what gives the whole object .predict() and .score().

Different treatment for different columns

Numeric columns need mean imputation and scaling. Categorical columns need most-frequent imputation and one-hot encoding. ColumnTransformer applies a different pipeline to each group, and because the transformer can itself be a pipeline, it composes cleanly.

preprocess = ColumnTransformer(transformers=[ ("num", num_vals, num_cols), ("cat", cat_vals, cat_cols) ])

Searching over models, not just settings

Because a pipeline is itself an estimator, you can hand the whole thing to a grid search. And you can put the estimator in the search space:

search_space = [ {'regr': [LinearRegression()], 'regr__fit_intercept': [True, False]}, {'regr': [Ridge()], 'regr__alpha': [0.01, 0.1, 1, 10, 100]}, {'regr': [Lasso()], 'regr__alpha': [0.01, 0.1, 1, 10, 100]} ] gs = GridSearchCV(pipeline, search_space, cv=5)

One call, three model families, their hyperparameters, preprocessing applied consistently, cross-validation throughout. The naming convention inside a pipeline is step name, double underscore, hyperparameter.

12

Lesson twelve

Engineering skills for ML

The difference between the title "scientist" and the title "engineer" is this lesson. The tools are unglamorous compared with the models, but without them a model stays in a notebook and never reaches anyone.

Object-oriented Python

A class is a template, an object is an instance of it. The four pillars are inheritance (a child class gets the parent's methods), polymorphism (the same operation applied to different types), abstraction (declaring what a class must implement without implementing it), and encapsulation (hiding data inside the object).

Python has no private

Everything is public. One underscore is a convention meaning "be careful". Two underscores trigger name mangling, which renames the attribute behind the scenes to avoid clashes in subclasses. It is still reachable. The @property decorator is the Pythonic way to get setter logic while keeping plain attribute syntax.

Functional Python

A pure function is deterministic and has no side effects. Loops maintain an external counter, which is a side effect, so functional code uses recursion. map, filter and reduce replace loops declaratively, and chain: "map only the values that have property x" is literally map(f, filter(p, items)).

Logging, not print

Print statements clutter the code, are hard to trace in a large application, and one always gets left behind. A logger gives you timestamps, module names, line numbers and severity levels. Moving to production means changing setLevel on one line, not deleting statements throughout the codebase.

Exceptions

A syntax error is caught before the program runs; an exception happens at runtime in valid code. Read a traceback from the bottom up: the last line gives the type and message. Use else rather than piling more code into try, so you do not accidentally catch an exception raised somewhere you were not protecting.

Unit testing

The goal is not only to find bugs but to find them quickly. Test the edge cases as well as the reasonable ones: zero, a very large number, a negative number. subTest turns a loop into individual tests so one failure does not stop the rest, and fixtures put every test into a known state.

Concurrency, explained at a deli counter

  • Sequential: one queue, one till. Everyone waits in single file.
  • Concurrent: several queues, one till. The cashier serves whoever is ready, so someone still deciding does not block the rest.
  • Parallel: several queues, several tills. The work is genuinely divided.
  • Asynchronous: a ticket system. Your number is called when your food is ready, not in the order you arrived.

A process is a running program, mostly independent, not sharing data. A thread is a sequence of instructions inside a process, sharing its memory, which makes communication between threads far cheaper than between processes. The cost is a whole class of bug that barely exists in sequential code: data races, where two threads modify the same data, and deadlocks, where threads wait on each other forever. Both depend on precise CPU timing, which makes them non-deterministic and very hard to test.

In Python: threading gives concurrency, multiprocessing gives true parallelism across cores, and asyncio gives asynchronous coroutines. Threading still speeds things up substantially whenever tasks spend most of their time waiting on something external.

The command line and git, in one breath

Pipes are what make the shell powerful: | sends the output of one command into the next, so sort file | uniq alphabetises and then removes duplicates, which is necessary because uniq only removes adjacent ones. > writes to a file and overwrites, >> appends. grep searches, sed finds and replaces.

A git project has three parts: the working directory where you edit, the staging area where you list changes, and the repository where they are stored permanently. git fetch is worth understanding precisely: it brings changes down onto a remote branch, not into your local branch, so you cannot see or use them until you merge. The collaborative workflow fetches and merges twice, before starting and before pushing, purely to avoid merge conflicts.

On pull requests: keep them small. A pull request touching fifty files will not be reviewed properly. And when reviewing, say why something should change, not only what.

13

Lesson thirteen, the last one

AI in the wild: everything above, pointed at a billion people

A recommendation engine is not conceptually exotic. It is supervised learning fed by an unusually rich stream of labels, where the labels are your own behaviour. Understanding it is the fastest route from "I know what a classifier is" to "I understand why my phone knows what I want".

A hand scrolling on a smartphone

A traditional feed shows you content from accounts you chose to follow. You curated it. A personalised feed does away with that: a machine learning algorithm is the curator, and no two feeds are the same.

The model draws on usage patterns, account settings, and data from the device, which can include contacts, social connections and links you have sent or opened. If you appear in a video, biometric and demographic information including gender, ethnicity and age can potentially be extracted from your face and added to the pool. In the vocabulary of lesson 01, your face becomes a set of features.

But the heart of it is the feedback loop: signals harvested from your responses to the feed itself. Likes, comments, and above all the length of time you watch before swiping away. Every action, and every absence of one, is data. Not swiping is data.

The structural insight, and why short-form video won

Same total viewing time. Thirty times the labelled examples.

Shortening the content did not make the recommendation problem easier. It made the data denser. Product design and model design turned out to be the same decision.

How something goes viral is less clear. The leading account is the batch theory: new content is shown to a small batch of users worldwide, and if it gains traction it is sent to a larger batch, then larger still. What counts as traction is contested, whether the ratio of likes to views, or whether people watch to the end, or some combination. The company has confirmed aspects of this without much detail, and there is no shortage of forum threads from users trying to reverse-engineer a system they suspect is periodically retuned.

The label problem is the hard problem

Every technique in this course assumes you have labelled examples. Most organisations do not. A feed solves this by making the user generate a label with every gesture, continuously and for free.

Feedback loops are self-reinforcing

The model shapes what you see, what you see shapes what you engage with, your engagement retrains the model. Nothing in the algorithm is designed to produce a filter bubble. It falls out of the loop.

Personal data is just features

To a model there is no difference between "square footage" and "estimated age from a face". Both are numbers in a column. The distinction is legal and ethical, which is why AI regulation concerns itself with what may be a feature rather than with the algorithms.

Big models are opaque to their owners too

Complexity plus data volume makes a system like this genuinely hard to characterise, even from inside. That is not evasion, it is a real property, and it is exactly why the explainability techniques in lesson 06 matter.

Where the rest of the course fits

Feature engineering turns behaviour into columns. Classification asks whether you will engage. Regression asks for how long. Clustering groups users and content. Ensembles combine weak signals into a ranking. Pipelines retrain it as new signal arrives.

The metric is the decision

Lesson 05 made the technical case that accuracy is often wrong. The same logic applies to a product. A feed optimised for engagement will find engagement, exactly as instructed.

The metric a system optimises for is the most consequential decision anyone makes about it, and it is usually made early, quietly, and never revisited. Whether engagement was the right thing to ask for is not a question the model can answer.

Reference

Glossary: every term, in one sentence

Ninety-three of them. Type to filter.