AI and Machine Learning with Python
Frame, train, evaluate and ship models you built yourself.
Go from a naive baseline in a notebook to a tested, tracked and monitored model: data preparation, classical supervised and unsupervised learning, honest evaluation, PyTorch, foundation model adaptation, reproducible experiments, serving and production monitoring. Modules 1–2 are beginner ML and maths, modules 3–6 are intermediate modelling, and modules 7–11 cover advanced model development, operations and a capstone. You need Python, basic algebra and Git; the statistics and linear algebra are taught as you go. Python from Zero and SQL & PostgreSQL cover the prerequisites, and AI Engineering with Python is the companion path for RAG and LLM applications. Everything runs on a CPU with free, local tools; GPUs and cloud hardware are optional.
01Problem framing and the first baseline
Beginner. What ML is and is not, how to define data and labels, and a first reproducible notebook with a baseline. Prerequisites: Python, basic algebra and Git.
- AI, machine learning and deep learning: choose the right problem typeMachine learning is one way to build AI: instead of writing every rule by hand, you let a program learn patterns from examples. Before training anything, decide whether the question is supervised (you have past answers to learn from), unsupervised (you only want to find structure), or not an ML problem at all. Then write down a simple baseline and the measure that will tell you whether the model is worth keeping.11 min
- Features, targets and labels for a machine learning datasetA dataset only makes sense once you have written down what one row means, what you are predicting, and where each column came from. This data definition names the unit of observation, the target and how it was labelled, the features, their provenance, and which facts are truly known at the moment a prediction is made. Getting it right early prevents models that look brilliant in a notebook and fail in real use.10 min
- Your first reproducible ML notebook with a naive baselineYour first notebook should prove two things: that anyone can rerun it and get the same numbers, and that a trained model beats a naive baseline. You pin the environment in a virtual environment, load and profile a small dataset with pandas, fix random seeds, and compare a DummyClassifier with a simple logistic regression on the same test split. If the model does not clearly win, you have learned something important before spending more effort.10 min
02Useful maths and trustworthy datasets
Beginner. The linear algebra, statistics and optimisation behind models, and preprocessing pipelines that fit on training data only.
- Linear algebra for machine learning with NumPyA feature table is a matrix: each row is one example and each column is one feature, so a row is a vector of numbers. A linear model's prediction is the dot product of that row with a weight vector, plus a bias, and NumPy computes it for every row at once with a matrix-vector product. Reading array shapes, such as (rows, features), is the skill that catches most bugs before they happen.10 min
- Statistics and probability for machine learning in PythonStatistics tells you how much to trust a number computed from a sample. You will simulate distributions, compute the mean, variance and standard error, work through conditional probability, and use the bootstrap to put a confidence interval around a result. You will also see why a strong correlation does not prove that one thing causes another.11 min
- Loss functions, gradient descent and regularisation explainedTraining a model means finding the weights that make a loss function as small as possible. Gradient descent does this by repeatedly measuring the slope of the loss and taking a small step downhill, with the learning rate controlling the step size. Regularisation adds a penalty for large weights, which trades a little training accuracy for better results on new data.11 min
- Data preprocessing with scikit-learn pipelinesReal data has gaps, text categories and columns on wildly different scales, and most models need clean numbers. scikit-learn's ColumnTransformer applies the right steps to each column type, such as imputing, encoding and scaling, and a Pipeline joins those steps to the model. Fitting the whole pipeline on the training split only keeps test data truly unseen.10 min
03Train supervised models
Intermediate. Regression and classification models, decision thresholds, and tree ensembles compared on the same data.
- Linear, ridge and lasso regression comparedLinear regression predicts a number as a weighted sum of the features plus an intercept, choosing the weights that make the squared errors as small as possible. Ridge and lasso add a penalty on the size of the weights, which trades a little bias for more stable predictions; lasso can also push weights to exactly zero. You compare them on held-out data with MAE and RMSE, and you read the residuals to see where each one goes wrong.13 min
- Logistic regression, k-NN and decision trees for classificationA classifier predicts a category, and most scikit-learn classifiers can also give a probability for each class through predict_proba. Logistic regression draws a linear boundary and outputs probabilities, k-nearest neighbours votes among the closest training rows, and a decision tree asks a series of yes or no questions. By default predict uses a 0.5 cut-off for binary problems, but the right threshold depends on what a false alarm and a missed case cost.12 min
- Random forests and gradient boosting in scikit-learnA single decision tree is easy to read but changes a lot when the training data changes, which is high variance. A random forest averages many deep trees, each trained on a bootstrap sample with random feature choices, to cut variance. Gradient boosting builds shallow trees one after another, each fixing the errors of the ones before, which reduces bias and is often the strongest choice on tabular data.12 min
04Trust the score
Intermediate. Splits that match how the model will be used, leakage checks, classification metrics and a repeatable error-analysis loop.
- Train-test splits, cross-validation and data leakageA test score is only worth trusting if the test rows look like the data the model will meet in use and nothing from them reached training. That means choosing a split that matches reality: stratified for rare classes, grouped when rows belong to the same customer or patient, and time-ordered when you predict the future. Cross-validation on the training part is used for tuning, and the held-out test set is scored once at the end.12 min
- Precision, recall, ROC-AUC and calibration on imbalanced dataWhen positives are rare, accuracy is misleading: a model that never predicts fraud is 99 percent accurate if only 1 percent of cases are fraud. The confusion matrix, precision, recall and F1 show what kinds of mistakes the model makes, while ROC and precision-recall curves show how that changes across thresholds. Calibration checks whether a score of 0.2 really means about a 20 percent chance, which you need before turning scores into costs.13 min
- Error analysis for machine learning modelsOne overall score hides where a model fails. Error analysis breaks the score down by meaningful slices such as region, device or age band, measures how uncertain each number is, looks at the worst mistakes by hand and writes down what the data cannot tell you. It turns evaluation into a repeatable loop that tells you what to fix next and what to warn users about.12 min
05Structure and anomalies
Intermediate. Clustering, dimensionality reduction and anomaly scoring, with honest limits on what the scores mean.
- K-means and DBSCAN clustering in PythonClustering groups rows that look alike when you have no labels to learn from. K-means finds a fixed number of round groups around centre points, while DBSCAN finds dense regions of any shape and marks lonely points as noise. Both depend heavily on feature scaling, and neither proves that the groups mean anything in the real world.13 min
- PCA and visual projections without over-reading themDimensionality reduction squeezes many columns into a few new ones. PCA builds straight-line combinations of the features that keep as much variance as possible, and t-SNE or UMAP draw 2D maps that keep near neighbours close. Kept variance is not the same as kept usefulness, so always test reduced features on the real task.11 min
- Anomaly detection with thresholds and isolation forestsAnomaly detection gives each row a score for how unusual it looks, then a threshold turns scores into alerts. Simple statistical rules such as z-scores work well for one well-behaved number, while an isolation forest can score rows across many features. Every threshold trades missed incidents against false alerts, and the alert volume decides whether anyone keeps watching.13 min
06Time and ranking
Intermediate. Forecasting with rolling backtests and recommendation systems evaluated with ranking metrics.
- Time series forecasting with lag features and backtestsForecasting predicts future values of a series, such as daily sales, from its own past and from known calendar facts. You turn the series into a table with lag and rolling features, compare against naive and seasonal naive baselines, and test with a rolling-origin backtest that only ever trains on the past. A useful forecast also says how uncertain it is, with an interval rather than a single number.13 min
- Build a simple recommender and measure it with recall@k and NDCGA recommender ranks items, such as products or articles, for each user. Collaborative filtering uses what similar users or items did, while content-based methods use item descriptions, and real systems combine them to handle new users and new items. Because the output is a ranked list, you measure it with ranking metrics such as recall@k and NDCG on interactions held out by time.13 min
07PyTorch from tensors to training
Advanced. A CPU-friendly PyTorch training loop, generalisation controls, convolutional models with transfer learning, and transformer foundations.
- Write a PyTorch training loop from scratchA PyTorch training loop is a few lines you write yourself: take a batch, run the model forward, measure the loss, let autograd compute gradients, and let the optimiser nudge the weights. Writing it by hand on a CPU shows exactly where data, shapes and gradients flow, which makes every later bug easier to find.11 min
- Early stopping, checkpoints and reproducible PyTorch runsA neural network can memorise its training data, so the real goal is a model that does well on data it has not seen. Validation curves tell you when that starts to fail, and tools such as weight decay, dropout, a sensible learning rate and early stopping keep it in check. Checkpoints and seeds make the best run something you can reload and repeat.11 min
- Convolutional networks and transfer learning in PyTorchConvolutional networks slide small learned filters across an image, so they reuse weights and keep spatial structure that a dense network throws away. Transfer learning starts from a network already trained on millions of images and retrains only its last layers, which gives strong results with little data and CPU-sized compute. The result only counts if you test on images that are genuinely different from the training ones.11 min
- Embeddings, attention and transformer blocks explainedTransformers turn text into token IDs, map each ID to an embedding vector, and then let every token look at every other token through attention. Stacking attention and small feed-forward layers into blocks gives the models behind modern language tools. Knowing these parts helps you decide whether to use a pretrained model as is, fine-tune it, or only run inference.11 min
08Foundation models and adaptation
Advanced. How language models generate text, how to choose an adaptation method, and how to use them responsibly.
- How language models generate text: sampling and temperatureA language model writes text one token at a time: it scores every possible next token, a decoding rule picks one, and the choice is appended and fed back in. Settings such as temperature, top-k and top-p change how that pick is made, trading predictability for variety. Because the model only predicts likely text, it can produce fluent claims that nothing supports.11 min
- Prompting, retrieval or fine-tuning: choosing how to adapt a modelThere are four main ways to make a foundation model fit your task: better prompting, retrieval of your own documents, full fine-tuning, and parameter-efficient fine-tuning such as LoRA. They differ in cost, in the data you need and are allowed to use, and in how you prove they work. Start with the cheapest option, write the evaluation first, and move up only when the numbers say so.12 min
- Responsible machine learning: privacy, fairness and model cardsA model that scores well can still leak personal data, treat groups of people unequally, fail silently on unusual inputs or break a licence. Responsible machine learning means checking those risks on purpose, writing them down in a model card, and designing human review and safe fallbacks for when the model is wrong. It is part of the engineering work, not an afterthought.12 min
09Reproducible development
Advanced. Track experiments, package and test the full pipeline, and choose between batch and online serving.
- Experiment tracking with MLflow: runs, metrics and lineageExperiment tracking means recording everything that produced a model: the data version, the split, the features, the parameters, the random seed, the metrics and the saved files. MLflow is a free, open-source tracker that stores each training attempt as a run you can search and compare. Without it, a good result from last week is often impossible to reproduce or explain.11 min
- Package and test a scikit-learn model pipelinePackaging turns a trained model into something another machine can load and trust. In scikit-learn that means saving the whole Pipeline, preprocessing included, pinning the library versions, and loading files only from sources you control. A pytest test then proves the packaged model gives the same predictions as the one you evaluated.10 min
- Batch or online inference: serving patterns for ML modelsThere are two main ways to serve a model. Batch inference scores many rows on a schedule and stores the results; online inference answers one request at a time through an API, usually within a strict time limit. The right choice depends on how fresh a prediction must be, and either way you need a written prediction contract and a staged release plan.11 min
10Production ML health
Advanced. Monitor data, drift and performance, retrain and roll back safely, and govern a model until retirement.
- Monitoring ML models: data drift, concept drift and delayed labelsA model can keep running without errors while its predictions quietly get worse. ML monitoring watches six different things: the quality of incoming data, drift in the inputs, changes in the relationship between inputs and outcomes, accuracy once true labels arrive, service health and cost. Each one fails in a different way and needs its own signal and threshold.11 min
- Retraining triggers, canary checks and model rollbackModels age, so you need clear rules for when to retrain, how to test a new version safely and how to go back if it misbehaves. A model registry stores numbered versions and lets you point a named alias such as champion at the one in use. Promotion then means moving the alias after shadow or canary checks pass, and rollback means moving it back.11 min
- ML model governance from approval to retirementGovernance means someone can always answer: who approved this model, on what evidence, what data it uses, how long that data is kept, who owns it today and when it will be retired. It turns the artifacts you already make, such as tracked runs, model cards and monitoring dashboards, into a record that survives staff changes and audits. Frameworks such as the NIST AI Risk Management Framework give a shared structure.11 min
11Build and evaluate a model
Advanced. Build, evaluate and ship a CPU-first tabular model with a baseline, leakage review, model card and monitoring plan.
- ML capstone: dataset, model brief and naive baselineThe first capstone milestone fixes the ground rules before any real model is trained. You pick a tabular dataset you are allowed to use, write a one-page model brief, freeze a versioned split and score a naive baseline that every later model must beat. You finish with a written leakage review, so the numbers you report later can be trusted.13 min
- ML capstone: train, compare and report by sliceThe second milestone trains several candidate models on the same folds and compares them with the baseline in one table. You pick metrics and a decision threshold that match how the predictions will be used, then break the errors down by slice to find where the model fails. Everything is saved as one reproducible pipeline with its data version, code version and settings.13 min
- ML capstone: ship, monitor and document the modelThe last milestone turns the saved pipeline into something others can call: a batch scoring job or a small HTTP API with a written inference contract. You add tests that pin the contract and some recorded sample predictions, set monitoring thresholds with named owners, and publish a model card and a rollback plan. The capstone is done when another person could run, check and retire your model without asking you.14 min