Anything you notice during exploration needs confirming on data you did not explore. The more you look, the more flukes you find.
ExampleFifty charts from an agent in a minute: some will show patterns that are pure chance.
Dictionary
206 terms · examples drawn from the course
206 shown
Anything you notice during exploration needs confirming on data you did not explore. The more you look, the more flukes you find.
ExampleFifty charts from an agent in a minute: some will show patterns that are pure chance.
The share of predictions that were correct. Misleading when one answer is very common.
ExampleA car-park model that always says 'full' is 96% accurate and never finds an empty space.
Also: accuracy paradox
When one outcome is rare, a model that always predicts the common outcome scores high accuracy and is useless. Accuracy cannot tell a useful option from a useless one.
ExampleContacting nobody is 73.5% accurate on churn and 92% accurate on the upsell data, and catches no one.
Also: summary statistic
Reducing many values to one summary, such as a mean, sum, count, minimum or maximum.
Exampledf['left'].mean() is the share of customers who left: about 26.5%.
Also: agent, LLM agent
An LLM that plans a step, uses a tool (runs code, queries data, calls an API), reads the result and decides what to do next, in a loop.
ExampleEarth Agent proposes the search space and objective, runs experiments on Earth through its API, reads the results and suggests the next experiment.
Also: AI
Named in 1956 as the umbrella for making machines act intelligently (rules, search, logic, learning). Today it usually means deep learning and generative AI.
ExampleWhen someone says 'AI', ask which circle they mean.
Also: area under the curve, ROC, roc_auc
The chance that the model scores a random real case above a random non-case. 0.5 is a coin flip, 1.0 is perfect. Good for comparing pipelines; hard to explain to the business.
ExampleOn the upsell data: random 0.50, rule 0.74, logistic regression 0.77.
Also: axis=0, axis=1
The direction of an aggregation on a table. axis=0 runs down the rows and gives one answer per column; axis=1 runs across and gives one answer per row.
Exampleservices.sum(axis=1) counts how many services each customer has.
Also: no-brainer model, benchmark
The simplest sensible answer, used as the bar any real model must beat. A model is never good on its own, only better than something.
ExampleAlways predicting 'stays' is 73.5% accurate on our data and finds no leavers. In the smoothie story, always guessing the average is off by 85 calories.
Also: data bias
When historical data reflects unfair or unrepresentative decisions, a model learns them and applies them at scale.
ExampleA model trained on ten years of biased hiring decisions repeats the bias a thousand times a day.
Also: bands, buckets, cut, qcut
Turning a number into bands. cut uses edges you choose; qcut makes bands with equal numbers of rows.
ExampleTenure bands 0-12, 13-24, 25-48 and 49-72 months make the churn pattern readable at a glance.
Also: mask, filter
An array or column of True/False values used to select rows. The mean of a mask is the share of True values.
Examplehigh = charges > 80 selects high payers; churned[high].mean() is the share of them who left.
The share of calls that must succeed for calling to pay for itself: cost of a contact ÷ value of a success. Above it, capacity, not cost, limits how many to call.
ExampleOffer ₪50, saved customer ₪2,000, one in four contacted leavers saved: 50 ÷ (2,000 × 0.25) = 10%.
Good partial choices (a group of columns, a model setting) that can be recombined into better wholes. When good solutions share building blocks, crossover pays off.
ExampleIn the room exercise, #1's depth, leaf and columns plus #6's learning rate give 0.82, better than both parents.
Also: success metric, KPI
The number the business uses to judge success, agreed with the domain expert before modelling. It decides which pipeline wins.
ExampleHit rate of a 400-call list, or the shekel value of the list.
Also: calibrated probabilities, CalibratedClassifierCV
Whether predicted probabilities match reality: of customers scored 30%, do about 30% really upgrade? Matters when probabilities are turned into money; ranking alone does not need it.
ExampleLogistic regression's top 10% average a predicted 31% and really upgrade at 29%: reasonably calibrated.
Also: contact capacity, budget
How many cases the business can act on in one round: calls, visits, offers. With a fixed capacity, the job is to rank everyone and act on the top of the list.
ExampleThe retention team can make about 400 calls a month; the upsell call centre about 600 per campaign.
Separating what no list could do from what the model got wrong. Leavers beyond the capacity are missed by any list, however good; the model's own errors are the wasted calls inside the list.
Example1,494 leavers, 400 calls: at least 1,094 leavers are out of reach. The model's errors are its 78 wasted calls.
Also: segment check
Testing whether a pattern holds inside each segment, not only on average. Sometimes an overall pattern disappears or reverses within groups.
ExampleMonthly contracts leave more within every internet service type.
Also: imbalance
How evenly the labels are spread. With imbalance, a model can look accurate by always predicting the common label.
ExampleAbout 1 in 4 customers left; 96 of 100 car-park spaces are full.
A supervised task where the answer is a category.
ExampleSpam or not spam; will leave or will stay.
Cleaning is done once, before the split, on the whole dataset: duplicates, impossible values, columns you will not use. Preprocessing (impute, encode, scale) learns something from data, so it goes inside the pipeline and learns from training rows only.
ExampleRemoving the 22 duplicate rows is cleaning; filling missing charges with the training median is preprocessing.
Also: k-means
Grouping similar rows together. k-means places k centres and assigns each row to the nearest one, repeating until stable.
ExampleSegmenting customers before anyone has defined the segments.
Also: weight, coef_
The number a linear model learns for each column. The sign gives direction (towards the outcome or away from it), the size gives strength, after scaling and given all the other columns. It describes the model, not the world.
ExampleTenure −1.4 (longer customers stay); month-to-month contract +0.6 (leans towards leaving).
A new user or item with no history for a recommender to learn from.
ExampleWhat do you recommend to someone who signed up a minute ago?
Also: multicollinearity, correlated features
Two or more columns carrying largely the same information. Predictions can still be fine, but weights split between the columns in confusing ways.
ExampleTotalCharges ≈ tenure × MonthlyCharges: the model gives TotalCharges +0.7 and MonthlyCharges −0.3.
The scikit-learn tool that applies different preparation to different columns (numbers: impute and scale; categories: one-hot encode) and joins the results.
ExampleColumnTransformer([('num', numeric_steps, NUM), ('cat', OneHotEncoder(handle_unknown='ignore'), CAT)]).
Also: confusion_matrix
A table of the four possible outcomes of yes/no predictions: who we flagged and who we didn't, against what really happened. Every classification metric is a way of summarising these four numbers.
ExampleThe rule on 5,638 training customers: 789 leavers caught, 729 wasted calls, 706 missed leavers, 3,414 correctly left alone.
A condition every candidate must meet, whatever its score. A candidate that breaks one is not allowed, however good it looks.
ExampleOnly columns known at prediction time; preparation inside the pipeline; explainable enough if the business requires it.
Also: hold-out group, A/B test
A randomly chosen group that does not receive the action, kept to measure what the action really adds.
ExampleKeep a random 10% of eligible customers out of the September calls and compare their upgrade rate with those called.
Also: Pearson correlation, chi-square test
How strongly two columns move together, from −1 to 1. Pearson correlation suits two numeric columns; for a category against a yes/no outcome, compare the outcome rate per category or use a chi-square test.
ExampleTenure and TotalCharges are strongly correlated; churn rate by contract type shows the contract effect directly.
Also: project steps
The seven steps of a simple ML project: frame the use, build the dataset, explore, design the evaluation, build the baseline, diagnose and improve, confirm and hand over.
ExampleSession 1 covers the first three steps; Sessions 2 and 3 cover the rest.
Also: CV, k-fold, cross_validate
Split the training data into K parts (folds). Train on K−1, validate on the one left out, rotate until every part has been the validation part once. Gives K honest scores instead of one, while the test set stays locked.
Example5-fold cross-validation on 5,628 churn customers: five scores between 0.68 and 0.85, mean 0.76.
Also: recombination
Building a child from two parents by taking each gene from one parent or the other. Good building blocks from different parents can meet in one child.
ExampleParent #3 gives depth 3, parent #1 gives learning rate 0.03: a combination neither parent had.
Also: contingency table, cross tabulation
A table of counts for two columns at once. With normalize='index', each row shows shares that add up to 1.
Examplepd.crosstab(df['PaymentMethod'], df['Churn'], normalize='index'): electronic check payers leave far more often.
Complex models need very large datasets and compute; organisations without them should keep models simple.
ExampleGoogle can afford a deep network; a 5,000-row customer table usually can't.
Asking the data owner for new columns when the existing ones cannot tell two groups apart. Often worth more than more tuning, because the model can only see what we give it.
ExampleUsage, complaints, recent price history, competitor offers.
Also: pandas DataFrame, df
pandas' table: a set of named columns (Series) that share one row index.
Exampledf = pd.read_csv('telco_churn_teaching.csv') gives a DataFrame of 7,071 rows and 22 columns.
The line or surface a classifier draws between labels. Different algorithms are allowed different boundary shapes.
ExampleLinear model: one straight line. Decision tree: vertical and horizontal cuts. Neural network: a flexible curve.
Also: use statement
One sentence that says who uses a prediction, when, for how many, and for what goal. If a bracket stays empty, the project isn't ready.
ExampleEvery Monday we score active customers and the retention team calls the 100 most likely to leave in the next 30 days, so that we keep more revenue than the calls cost.
Also: DecisionTreeClassifier, tree
A model that learns a sequence of yes/no questions about the features. Without limits it can memorize the training data.
ExampleAn unlimited tree is 99.7% right on training customers and 72.6% on new ones; limited to depth 4 it gets about 79% on both.
One choice the search is allowed to change. Together they make up the search space; each becomes one gene in a genetic algorithm.
ExampleModel family; C and class weight; depth, learning rate and leaf size; a yes/no switch for each of the 19 columns.
Neural networks with many layers that learn their own features from raw data. Strong on images, sound and text; needs much data and compute.
ExamplePixels to edges to shapes to 'cat'. On a modest business table, tree ensembles usually match it.
Also: defaults, out-of-the-box settings
The values a library uses when you set nothing. A starting point chosen for typical data, not for yours; on small tables they often overfit.
ExampleGradient boosting with defaults: training 0.96, validation 0.77. With gentle settings: training 0.86, validation 0.81.
Also: data mining
Exploring data to understand it and get inspired, without claiming the findings hold beyond the data at hand.
ExampleLooking at last quarter's sales by region.
Also: drift, data shift
When the data a model meets in use differs from the data it learned from. Performance degrades quietly, with no error message.
ExampleThe users a model learned from were mostly older; the users it now serves are mostly young.
Three questions asked at every project step: what can I do myself (level 1), what must I raise with a data scientist or the business (level 2), and what can an AI agent take on.
ExampleSplitting the data: I implement it; I raise whether 'new data' means future months or new customers; an agent can write the code.
Also: data type
The type of the values in an array or column, such as int64, float64 or text (object or str). One wrong value can change the type of a whole column.
ExampleTotalCharges is read as text because 11 rows contain a blank space instead of a number.
scikit-learn's ready-made baseline. With strategy='most_frequent' it always predicts the most common label.
ExampleDummyClassifier(strategy='most_frequent') scores 0.735 on the test set.
Also: duplicated, repeated records
Rows that repeat: exact copies, or the same key (such as a customer ID) appearing more than once, sometimes with conflicting values.
ExampleThe teaching data has 22 exact copies and 6 customers who appear twice with different monthly charges.
Also: elite
Copying the best candidates unchanged into the next generation, so the best found so far can never be lost. Re-checking them costs nothing: their score is already known.
ExampleCandidate #3 (0.81) moves to generation 2 as it is; only the children cost new evaluations.
Also: fresh toast, spurious pattern
A metaphor for finding patterns that aren't there. People see faces in toast; flexible algorithms find patterns in noise. Only fresh data exposes them.
ExampleA model trained on coin-flip labels scores 100% on what it studied and 49% on new data.
A model built from many models whose predictions are combined. Usually more accurate and stable than any single member.
ExampleA random forest averages hundreds of trees; gradient boosting adds hundreds of small trees one after another.
Reading a model's mistakes row by row and segment by segment, instead of only its average score. It tells you whether a better model, better data or a business decision is needed.
ExampleInside the 400-call list, the 78 wasted calls look just like the 322 hits in every column we have, so the next step is a data request, not more tuning.
Also: raise
Raising a consequential choice with someone who can decide it. Knowing when to escalate is a skill, not a weakness.
ExampleWhether a downgrade counts as leaving goes to the retention lead, not to the analyst alone.
Also: fit, predict, scikit-learn API
The four methods every scikit-learn model shares: learn from examples, label new rows, give a score per label, and report accuracy.
ExampleSwapping LogisticRegression for DecisionTreeClassifier changes one line; the rest of the code stays the same.
Also: churn_eval.py, objective function
One function that takes a candidate set of choices, builds the pipeline, cross-validates it and returns one honest number. Earth calls it thousands of times in the labs.
Exampleevaluate({'C': 1.0, 'columns': 'all'}) returns the cross-validated hit rate of a 400-call list.
Also: new evaluations, search budget
How many new evaluations (and how much time) a search may spend. Re-checking a candidate whose score is already known costs nothing, so a fair comparison of methods gives each the same number of new evaluations.
Example40 new evaluations in class (about 20 seconds); thousands on Earth.
Also: genetic algorithm, GA, evolutionary algorithm
A search that keeps a population of candidates and breeds each new generation from the better members of the last: selection, crossover, mutation and elitism, repeated until the stop rule. Earns its place on huge, expensive spaces with mixed choices and recombinable parts. The method behind Earth.
ExampleEarth evolves whole pipelines over thousands of evaluations; in class we only drew the idea.
Also: EV, value of a call list
Chance of success × value of success − cost of acting. Ranking by expected value rather than by chance alone puts the most valuable customers first.
ExampleTwo customers equally likely to upgrade: call the Basic one first (₪50 a month) before the Standard one (₪30).
One row per change tested: change, hypothesis, result, decision. Keeps failed ideas from being tried again and makes every kept change explainable.
Example+ price_change | customers whose price rose leave more | −2 points, worse in 4 folds | not kept; needs a real price history.
Also: exploration
Looking at the data to understand it: distributions, comparisons between groups, and checks across segments. Done on training data only.
ExampleShare who left by contract, by tenure band and by internet service, each with counts.
Also: F1, F-measure
One number that balances precision and recall (their harmonic mean). Common on imbalanced data, but its fixed balance may not be the one the business needs.
ExampleWith a fixed list of 400 calls, the hit rate of that list says more than F1 does.
Also: FP, FN, TP, TN, type I error, type II error
The two kinds of mistake. A false positive flags someone who is not a case (a wasted call); a false negative misses someone who is (a leaver we never called). True positives and true negatives are the correct cases.
ExampleCalling a happy customer costs a call; missing a leaver costs the customer. Which mistake hurts more is a business question.
Also: input, variable, column, X
A piece of information about each instance that the model can use as input. It must be known at the moment of prediction.
Exampletenure, Contract and MonthlyCharges are features; LastContactReason is not, because it is recorded after the outcome.
Also: domain knowledge
Creating inputs that help the model, usually from domain knowledge. A new column is a hypothesis written in code.
ExampleThe smoothie: adding grams of fat, carbs and protein cut the error from 47 to 4 calories, and the model rediscovered nutrition labels.
Also: permutation importance, SHAP
A measure of how much a model relies on each column. Useful for checking a model, not a business rule, and it shifts with settings and correlated columns.
ExampleGradient boosting reports which columns its trees split on most; permutation importance measures how much the score drops when a column is shuffled.
Also: ablation, feature pruning
Choosing which columns go into the model. Done honestly by dropping a group, retraining under cross-validation and comparing; done carelessly, it is a source of leakage.
ExampleDrop the weakest columns and compare: if far fewer columns score the same, keep the smaller, cheaper model.
Also: self-fulfilling model
When a model's decisions shape the data it is later retrained on. It keeps confirming its own choices and its blind spots become permanent.
ExampleIf the model picks who gets called each month, almost every upgrader in the data was called by the model, and customers it never called never get a chance to prove it wrong.
Retraining a model's parameters on your own examples. Powerful and costly; it turns the work into a supervised learning project.
ExampleTeaching a model a consistent house style from thousands of approved answers.
Also: shape, head, describe, value_counts
Five commands to run on any new data before anything else: shape, head, dtypes (or info), describe and value_counts.
ExampleOn our data they reveal 7,071 rows, a money column stored as text, and that most customers are on monthly contracts.
Also: fit_transform, replay
fit learns from data (a median, the list of categories, the weights); transform or predict applies what was learned. In a pipeline, fit runs on training rows only and the same learned steps are replayed on every new row.
ExampleThe imputer learns the median monthly charge from training customers and fills gaps in new customers with that same number.
Also: fitness function
The score of a candidate in a genetic algorithm: the same evaluate() any search method calls. Fitness decides who becomes a parent.
ExampleFitness = cross-validated hit rate of the candidate's 400-call list.
Also: landscape
A picture of every possible candidate as a point on a map, with its score as the height. Search methods differ in where they choose to look next on this map.
ExampleGrid points spread evenly, random points scatter, Bayesian and evolutionary points gather on the high ground.
Before believing any number: missing is not zero, the same thing twice, implausible values, categories that hide structure, identifiers posing as features.
ExampleIn the teaching data: 11 blank totals, 28 repeated rows, and a 'No internet service' value in six columns.
One of the K parts in cross-validation. In each round one fold validates and the others train.
ExampleWith 5 folds of about 1,125 customers, every customer is validated once by a model that never saw them.
Also: problem formulation
The optimization problem written down by people before any search starts: decision variables, objective, constraints, budget, stop rule, what is fixed and never searched, and how the winner will be protected from optimism. Earth needs exactly this.
ExampleFixed by people: the decision, the population, the label, the metric, the validation scheme and the test set.
Also: frozen pipeline
Fixing the pipeline and the policy, out loud and in writing, before opening the test set. After that, the test result is reported as it is, never used to reopen the search.
ExampleFrozen: gentle boosting, rank and call the top of the list. Test, 101 calls: 0.85.
Also: re-check on fresh folds
A new cross-validation split that played no part in choosing a winner, used to re-score it. The drop from the score that picked it to the fresh score measures how much of the win was luck.
ExampleThe top 5 of 40 random candidates: 0.801 on the folds that chose them, 0.790 on fresh folds (seed 7).
One position in a genome, holding the value of one decision variable. Genes that do not apply to a candidate (C for a tree) are carried along unused.
ExampleThe "max depth" gene holds 3; the "TotalCharges" switch gene holds 1 (column in).
Also: one job
How well a model does on data it has never seen. Machine learning has one job: succeed on new data.
ExampleDay 61: for days 1 to 60 you look the dose up; a model is only useful if the pattern still holds on day 61.
Also: chromosome, individual, candidate
One candidate written as a list of genes, one per decision variable. For us, a genome describes a whole pipeline.
ExampleBoosting · depth 3 · learning rate 0.05 · leaf 40 · 19 column switches on.
Also: GBM, boosting, HistGradientBoostingClassifier
A tree ensemble built step by step: each new small tree corrects the mistakes of all the trees before it, and its contribution is scaled down by a learning rate. Usually the strongest family on tables with enough data; needs careful settings on small data.
ExampleHistGradientBoostingClassifier with default settings overfits the 4,800 upsell customers; gentler settings match logistic regression.
Also: GridSearchCV
Trying every combination of a few chosen values for each setting. Simple and complete on a small grid, but the number of runs multiplies with every setting added.
Example5 settings with 5 values each = 3,125 runs.
Also: GroupKFold
A split that keeps all rows of the same customer (or store, or patient) on one side. Otherwise the model meets people it trained on in the exam.
ExampleSession 1's duplicates put 10 customers in both training and test; we drop them from training. With many repeats, use GroupKFold.
Also: split-apply-combine
Split rows into groups, compute a summary for each group, and combine the results into one table.
Exampledf.groupby('InternetService')['left'].agg(['mean', 'size']): fibre about 42% left out of 3,113 customers.
When an LLM produces fluent, confident text that is false.
ExampleInventing a policy clause that isn't in the HR handbook.
Also: model handover
Five to eight lines for the person who will run the model: what it does, expected performance with its uncertainty and baseline, inputs and what must be true of them, known limits, what to watch and who owns it.
ExampleKnown limits: reaches almost only month-to-month customers; predicts who leaves, not who a call would save.
Also: precision at K, hit rate of the call list, hit_rate_at_k
Rank everyone by score, take the top K, and measure the share of real cases among them. Precision at the team's capacity: the metric that matches a fixed call list.
ExampleTop 400 by score: random 27%, rule newest first 65%, rule fibre first 76%, logistic regression 76%.
Also: wasted call, compare_hits_vs_wasted
The two groups inside an action list. Hits are customers on the list who really are cases (called, and left). Wasted calls are customers on the list who are not (called, and stayed): the model's false positives.
ExampleGentle boosting's 400 calls: 322 hits, 78 wasted calls. Tenure 3.3 vs 3.7 months, charges ₪80 vs ₪78: nothing separates them.
Also: setting, knob
A setting chosen before training that shapes how the model learns: how strongly to simplify, how deep a tree may grow, how many trees. Chosen by comparing validation results, never test results.
ExampleC for logistic regression; max_depth for a tree; learning_rate and number of trees for gradient boosting.
Also: tuning, grid search, random search
Trying many settings and pipelines and keeping the one with the best validation score on the fixed metric. Done by hand, by a grid, by random sampling, or by an optimizer such as Earth.
ExampleFour values of C in Session 2; Earth explores thousands of pipeline configurations in the labs.
Also: validation curve, parameter sweep
Trying one setting across a range of values, all else fixed, and plotting training and validation scores side by side. Shows where the model starts to overfit.
ExampleTree depth 1 to no limit: validation peaks at 0.76 at depth 4, then falls to 0.44-0.52 while training reaches 1.00.
A stated guess about why the outcome happens, written before looking at the data and linked to a column that could test it.
Example'Customers leave because they aren't locked in by a contract' is tested with the Contract column.
Also: ID, key
A column that names a row, such as a customer ID. It carries no meaning about the outcome, but a flexible model can memorize it.
ExamplecustomerID is kept as a key for joins and duplicate checks, never used as a feature.
Also: outliers, sanity checks
Values that can't be right: impossible ranges, wrong units, misread formats. A domain expert often spots them in seconds.
ExampleDates in the year 0040 that were really two-digit years; a negative age; a premium plan billed at 0.
Also: SimpleImputer, fillna
Filling missing values with a learned substitute: the median or mean, the most common value, a value from similar rows, or a rule from domain knowledge.
ExampleSimpleImputer(strategy='median'); but tenure 0 means TotalCharges 0, where a median would be wrong.
Also: row labels
The row labels of a DataFrame or Series. Operations line rows up by index, not by position.
ExampleAfter filtering, the index keeps the original row numbers, which is why loc and iloc can give different rows.
Also: scoring, prediction
Using a trained pipeline on new rows to produce predictions. Every learned step is replayed exactly as it was learned.
ExampleEach month the pipeline scores all current customers and the top 400 go to the retention team.
Also: row, example, observation
One example the model learns from or makes a prediction for: one row of the dataset.
ExampleOne customer in our data; one email in a spam filter.
The running Python process behind a notebook. It holds everything in memory: variables, imported libraries, loaded data.
ExampleRestarting the kernel wipes memory, which is how you find cells that depend on something run earlier.
Also: target, ground truth, y
The answer the model learns to predict. Someone has to define it: what counts, over which window, from which moment.
ExampleChurn = 'left within the month before the snapshot' in our data; our project needs 'cancels within 30 days of the scoring Monday'.
Also: target definition
The precise rule for what counts as a positive example, including ambiguous cases. It is a business decision, not a fact found in the data.
ExampleDoes a downgrade count as leaving? A customer who cancels and returns two weeks later? Someone has to rule.
Also: noisy labels
Errors or inconsistencies in the recorded answers.
Example'Spam' is whatever users moved to the spam folder; bakery sales undercount demand on sold-out days.
Also: language model
A model trained to predict the next word over a vast library of text, then tuned on examples and human preferences. Fluent is not the same as correct.
ExampleAsk the same question twice and get two different answers; when it doesn't know, it still sounds sure.
Also: deployed candidate, current best pipeline
The pipeline you would deploy if you had to choose now. Error analysis, improvements and the final check all belong to it, because a different model gives a different list.
ExampleGentle boosting led after the morning. Its 400-call list shares only 272 customers with logistic regression's list.
Also: eta, step size
How big a step each training update takes. In gradient boosting: how much each new tree may correct. Smaller is more careful but needs more trees.
Examplelearning_rate=0.03 with 300 trees instead of the default 0.1 with 100.
Autonomous (the agent does it and reports), semi-autonomous (the agent proposes, a person approves), manual (a person decides). Autonomy follows reversibility.
ExampleTrying hyperparameters is autonomous; defining success is manual.
Also: selection, indexing
Two ways to select rows and columns: loc by label or condition, iloc by position.
Exampledf.loc[df['tenure'] == 0, ['customerID', 'TotalCharges']] selects brand-new customers and two columns.
Also: LogisticRegression
A simple, fast classification model that combines the features with learned weights and outputs a probability.
ExampleOn our split it reaches about 80% test accuracy, against 73.5% for the baseline.
Also: loss, objective, log-loss, cost function
The error a learning algorithm minimises during training, built into the algorithm (for logistic regression, log-loss). It is not the business metric; the data scientist makes sure the two point the same way.
ExampleThe model is trained to reduce log-loss; the retention team judges it by how many of its 400 calls reach a leaver.
Also: ML
A way of getting a recipe that turns inputs into outputs: instead of a person writing the rules, an algorithm stitches them together from examples with answers.
ExampleNobody writes rules for spam; the filter learns them from emails people marked as spam.
Also: map
Replacing values using a dictionary. Anything missing from the dictionary becomes NaN, which works as an alarm.
Exampledf['PaperlessBilling'].map({'Yes': 1, 'No': 0}) turns text into 1/0.
Also: chaining
Writing a sequence of pandas steps as one expression, one step per line, so the whole recipe reads top to bottom.
Examplepd.read_csv(path).assign(TotalCharges=...) builds the cleaned table in one readable block.
A blank can mean 'not yet', 'unknown' or 'not applicable'. Filling it with 0, the average, or dropping the row are three different claims about the world.
ExampleBlank TotalCharges belong to customers in their first month: set to 0 ('no bill yet'), never to the average.
Also: NaN, null, NA
A value that isn't there. pandas shows it as NaN. Missing data can also hide as a blank space, a zero or a placeholder word.
Exampleisna() finds nothing in TotalCharges because the blanks are spaces; converting to numbers reveals 11 missing values.
Also: missing indicator, add_indicator, was-missing flag
An extra 0/1 column saying whether a value was missing, kept alongside the filled value. Useful when the fact that something is missing carries information.
ExampleUpsell data: customers whose handsets don't report usage upgrade about twice as often; the flag keeps that signal.
Also: recipe
The recipe that comes out of machine learning: instructions that turn inputs into outputs. Once learned, it is used like any other program.
ExampleThe fitted logistic regression is a model; given a new customer's features it outputs a score.
Also: complexity dial, model capacity
How flexible a model is allowed to be. Every family has its own dial: depth and leaf size for trees, C for logistic regression, number of trees and learning rate for boosting. Too little underfits; too much overfits.
ExampleTurning the tree's depth up from 1 to no limit takes training hit rate from 0.41 to 1.00.
Also: two columns
Two kinds of finding in error analysis. A better model or better data can fix mistakes inside the list; who is on the list at all (value per customer, fairness, strategy) is a business decision to raise.
ExampleBoard, Cycle 4. MODEL CAN FIX: 78 wasted calls → data request. BUSINESS DECIDES: 0 of 172 long-contract leavers reached → raise with the retention lead.
Also: algorithm family
A group of algorithms that learn the same kind of shape: linear models (logistic regression), trees, tree ensembles (random forest, gradient boosting), neural networks. Choosing a family is choosing what patterns the model can express.
ExampleOn a table of a few thousand customers, a linear model and gentle gradient boosting perform about the same.
Also: Bayesian optimization, surrogate model, Optuna
A search that fits a quick guess of where good scores are, from the candidates tried so far, and spends the next evaluations where the guess is most promising. Useful when each evaluation is expensive.
ExampleAfter a few random tries, the next candidates cluster around the region that has scored best.
Also: model monitoring
Checking a deployed model regularly: its real hit rate, the mix of the data it scores, missing values. With a rule for when to retrain, and an owner.
ExampleEach month: hit rate of last month's list, the share of contract types, missing values; retrain if the hit rate falls below the rule.
A small random change to a child's genes. Most mutations make things worse; some bring in values no parent had, which keeps the search from getting stuck.
ExampleMin leaf 40 → 20 in the child.
Layers of simple mathematical units connected by learned weights. Allows very flexible decision boundaries.
ExampleThe squiggly boundary in the wine example.
Also: Jupyter, Colab notebook
An interactive document that mixes code cells, their outputs and text. Cells can run in any order; the number in brackets shows the order they actually ran.
ExampleA variable defined in a lower cell works in an upper one only because it was run earlier. Restart and run all to check the notebook really works top to bottom.
Also: ndarray, array
A grid of values that all share one type, stored so that whole-array operations run in fast compiled code.
Examplechurned = (df['Churn'] == 'Yes').to_numpy() gives an array of True/False values, one per customer.
Also: controlled experiment
Testing one idea by changing one thing only and keeping the folds, the metric and everything else fixed, then reading the difference fold by fold. If you change two things and the score improves, you don't know why.
ExampleAdd price_change to gentle boosting, same folds: 0.812 → 0.792, worse in 4 folds, a tie in 1. Not kept.
Also: dummy variables, get_dummies
Turning a category into several 0/1 columns, one per value, so a model can use it without inventing an order.
ExampleContract becomes Contract_One year and Contract_Two year; month-to-month is the row with both zeros.
Also: optimisation
Choosing the values of some decision variables to make an objective as good as possible, while respecting constraints, within a budget. Tuning a pipeline is one: the variables are the choices, the objective is the validated metric.
ExampleMaximize the hit rate of a 400-call list over model family, settings and columns, using columns known at prediction time, in 40 new evaluations.
Also: cross_val_predict, OOF
A score for each training row from the model that did not see that row during training. Lets you judge the whole training set honestly.
Examplecross_val_predict gives every churn customer a probability from a model trained on the other four folds.
Also: memorizing
When a model memorizes quirks of its training data instead of learning patterns that hold on new data. Great on what it studied, poor on anything else.
ExampleThe unlimited decision tree, or the student who learns that 8 divided by 4 is infinity by turning the 8 on its side.
Also: same-fold comparison, fold-by-fold comparison
Comparing two pipelines on the same folds, fold by fold: count the wins and ties and look at the difference per fold. Much of the noise is shared by both pipelines, so this is fairer than comparing two means with their spreads.
ExampleLogistic regression vs gentle boosting on the same five folds: boosting wins 4, ties 1, mean difference +0.052.
Also: learned parameter
A value the algorithm learns from data during training: the weights of a logistic regression, the questions and cut-offs of a tree.
ExampleLogistic regression learns a weight of −1.4 for scaled tenure.
Also: make_pipeline
Preparation steps and a model packaged as one object, so new data is treated exactly the same way as training data. Covered properly in Session 2.
Examplemake_pipeline(StandardScaler(), LogisticRegression()) scales and models in one fit.
Also: step, transformer
One step of a pipeline: filling gaps, flagging missing values, scaling, encoding categories, selecting columns, or the model itself. Components are what a search may change.
ExampleSwap median for mean imputation, or logistic regression for gradient boosting, and keep everything else fixed.
Also: pivot_table
A two-way summary: rows by one column, columns by another, any aggregation in the cells.
ExampleShare who left by contract type within each internet service: the monthly-contract effect holds in every group.
Also: generation
A genetic algorithm works on many candidates at once (the population). Each round of scoring and breeding produces the next generation.
ExampleA population of 6 cards in the room exercise; Earth's populations are much larger.
Also: positive predictive value
Of everyone we flagged, the share that really are cases: caught ÷ calls. Protects the team's time.
ExampleThe rule calls 1,518 customers and 789 of them leave: precision 52%.
Lowering the threshold flags more people: recall goes up, precision goes down. Raising it does the opposite. Where to stand is a business decision about costs and capacity.
ExampleChurn model: threshold 0.3 gives about 2,140 calls (precision 0.54, recall 0.78); 0.7 gives about 350 calls (0.76, 0.18).
Also: predict_proba, score
The model's estimate of how likely each label is. predict() turns it into a label using a cut-off of 0.5 unless told otherwise.
ExampleA month-to-month fibre customer scores 0.68 'likely to leave'; the retention team might call the top 100 scores whatever the cut-off.
Also: horizon, window
How far ahead the label looks from the prediction point.
Example'Cancels within the next 30 days' has a 30-day horizon.
Also: prediction time, scoring time
The moment a prediction is made. Only information available at that moment may be used as a feature.
Example'Every Monday': anything recorded after Monday, such as a cancellation call, is off limits.
Also: decision log
A written record of every data fix: what, how many rows, what was done, and why. Every fix is a decision.
Example'Blank TotalCharges, 10 rows, set to 0, all tenure 0: no bill yet.'
Also: pipeline leakage
Learning a preparation step (a median, a scale, a column selection) on rows that are later used to validate or test. The validation score becomes optimistic. Prevented by putting every learned step inside the pipeline.
Example2,000 columns of pure noise: selecting the best 20 on all rows gives AUC 0.59; the same selection inside the pipeline gives 0.49, a coin flip.
One line per cycle recording what was decided and why. It becomes the project file that later sessions build on.
Example'Test set locked: 20%, stratified, seed 42.'
Also: levels
Four levels of ML projects: routine application, applied DS decisions, specialist ML, research. The programme trains full capability at level 1 and foundations of level 2.
ExampleBuilding a churn model on agreed data is level 1; choosing how to define churn when the business disagrees is level 2.
The project is the business need and its limits. The pipeline is every step that turns a raw record into a score, learned on training data and replayed on new rows. The model is one component of the pipeline: the algorithm that learns from examples.
ExampleProject: a list of 400 customers every month. Pipeline: impute, encode, scale, logistic regression. Model: logistic regression.
Also: prompt engineering
Steering an LLM with instructions and examples in the request. Cheapest way to adapt it; can be fragile.
ExampleAdding three examples of good answers to the request.
Also: RandomForestClassifier
A tree ensemble of many deep trees, each built on a random sample of rows and columns, whose votes are averaged. Robust with little tuning.
ExampleRandomForestClassifier(n_estimators=300) is a common second model after logistic regression.
Also: RandomizedSearchCV
Drawing candidates at random from the search space. It does not learn from what it has seen, but on small, cheap problems it is hard to beat, which makes it the baseline for any smarter method on the same number of new evaluations.
Example40 random candidates in about 20 seconds: the best five averaged 0.801, close to the hand-tuned 0.81.
Also: random_state, seed
A fixed starting number for a random generator, so that 'random' results come out the same every run.
Examplerandom_state=42 makes the train/test split identical each time, so results can be compared.
Threshold metrics (accuracy, precision, recall, F1 at a cut-off) judge one yes/no policy. Ranking metrics (AUC, hit rate at K) judge how well the scores order customers. With a fixed capacity, ranking metrics match the decision.
ExampleOn the upsell data, logistic regression at threshold 0.5 flags only 41 customers (recall 5%), yet its top-10% list reaches 29% upgraders.
Also: top-N policy, decision policy
Instead of a threshold, rank every customer by score and act on the top N, where N is the capacity. Always gives exactly the list the team can handle.
ExampleNo threshold gives exactly 400 calls; ranking and cutting at 400 always does.
Also: small-sample caution
Always show how many rows sit behind a percentage. Small groups produce extreme rates by chance.
Example67% of 12 customers says almost nothing; 42% of 3,113 customers is a pattern.
Also: sensitivity, true positive rate
Of all real cases, the share we flagged: caught ÷ all leavers. Protects the customers.
ExampleThe rule reaches 789 of 1,495 leavers: recall 53%.
Also: recommender
A model that predicts the missing cells of a user-by-item table and shows each user their best few. Content-based, collaborative or hybrid.
Example'Customers also bought'. Traps: cold start, popularity bias, feedback loops.
A supervised task where the answer is a number. (In statistics the word means fitting a line; in ML it just means a numeric answer.)
ExampleCalories in a smoothie; tomorrow's demand for a bakery item.
Also: C, L1, L2, shrinkage, penalty
A penalty that keeps a model simple by shrinking its weights or limiting its growth, to reduce overfitting. In scikit-learn's logistic regression, C is the inverse: smaller C means stronger regularization.
ExampleC=0.01 gives small, cautious weights; C=10 lets weights grow large.
Also: RL
Learning by trial and error from a score for actions, often delayed, where actions change what the learner sees next.
ExampleA system learning the game Breakout discovers a tunnel strategy nobody taught it.
Also: fold seed, repeated k-fold
Running cross-validation again with differently shuffled folds (a new fold seed). If a ranking holds across seeds, it is not an accident of one split.
ExampleFold seeds 1, 2 and 3: logistic regression 0.755, 0.770, 0.770 against boosting 0.815, 0.800, 0.805. Boosting stays ahead every time.
Also: sampling bias
Whether the training data looks like the world the model will be used in. The training data is the only world a model knows.
ExampleUsers from an island near Antarctica, then a launch in New York; or data from before a price change.
Also: model refresh
Fitting the pipeline again on fresh data at regular intervals and re-checking it against the success bar. A model in production is a service, not a finished product.
ExampleRetrain every month on the latest labelled month; if the new pipeline misses the bar, go back and fix it.
Also: retrieval
Fetching relevant documents and giving them to an LLM with each question, so it answers from your sources.
ExampleAn HR assistant that answers from the company's policy handbook. This course hub's chat works the same way.
Also: standardization, normalization, StandardScaler
Rescaling each number column to a comparable range, usually mean 0 and standard deviation 1. Matters for models that add up weighted columns or apply regularization; trees don't need it.
ExampleTenure (0-72 months) and monthly charges (₪20-120) become comparable before logistic regression.
Also: objective to maximize
The single number a search tries to maximize, with how it is measured. It is the business metric under honest validation, not the loss the algorithm minimizes during training.
ExampleHit rate of a 400-call list, 5-fold stratified cross-validation, seed 42: what evaluate() returns.
Also: winner's curse
When you try many models or settings and keep the best score, that score is too good: some of it is luck. The harder you search, the more you must discount the winner.
ExampleAn agent tries 200 settings and reports the best validation score; on new customers it will usually do worse.
Everything a search is allowed to change: pipeline components, model families and their hyperparameters. The project, the data decisions, the metric and the validation scheme stay fixed.
ExampleImputation {median, mean}, missing flag {yes, no}, model {logistic regression, gradient boosting}, max_depth {2..8}.
Also: segment_table
For each group of customers: how many there are, their churn rate, how many left, how many we call and how many leavers we reach. Shows who the list serves and who it never touches.
ExampleContract: month-to-month 400 calls, 322 of 1,322 leavers reached; one-year 0 of 136; two-year 0 of 36.
Also: tournament selection, parent selection
Choosing parents for the next generation. Fitter candidates are picked more often, but weaker ones still get a chance, which keeps variety in the population.
ExampleTournament selection: draw three candidates at random; the best of the three becomes a parent.
Also: selection bias, treatment effect
When the people who received an action were chosen, not random, a difference in outcomes mixes who was chosen with what the action did. The two cannot be separated without a comparison group.
ExampleJune: one in four called customers upgraded, against fewer than one in twenty of the others. Marketing chose likely upgraders, so the gap does not prove the calls work.
Hiding part of the data and learning to fill it in, so the data labels itself. How LLMs are pre-trained.
Example'The patient missed the ___ because of rain' teaches the model 'appointment' with no human labelling.
Learning from a few labelled examples plus many unlabelled ones, usually because labelling is expensive.
ExampleA million support tickets and the budget to label two thousand.
A single pandas column: values of one type, with a name and a label for each row.
Exampledf['Contract'] is a Series; df[['tenure', 'Churn']] is a DataFrame.
Better than what? Measured how? On which data? Could anything have leaked? How much would it move? How hard did we search? Does it change the decision?
Example“The model's 400-call list reaches 76%.” Better than what? The best rule: also 76%. A tie.
Also: logistic function
The function that turns any number into a probability between 0 and 1. Logistic regression adds up weighted evidence and passes the total through it.
ExampleA large positive sum gives a probability near 1; zero gives 0.5; a large negative sum gives near 0.
Also: fold variance, standard deviation across folds
How much the K cross-validation scores differ. A difference between two pipelines smaller than this spread is not a difference yet.
ExampleLogistic regression: 0.76 ± 0.06 across folds, while four values of C differed by 0.01: no winner.
Also: simplest first
Try the fast, cheap options first (a rule, then a linear model) and make every extra piece of complexity earn its place against the success bar.
ExampleOn churn, three lines of pandas tie logistic regression at 400 calls.
Using data to make one or a few important decisions carefully, with uncertainty on the table.
ExampleDeciding whether to open a new branch, or whether a model is safe to launch.
Also: termination criteria, stopping rule, plateau
When a search ends: the budget is spent, there has been no improvement for a few generations, a good-enough target is reached, or time is up, whichever comes first. Decided before the search, like the metric.
ExampleStop after 60 new evaluations, or earlier if the best score has not improved for 2 generations.
Also: StratifiedKFold
Cross-validation in which every fold keeps the same share of each class as the whole training set, so no fold is accidentally easy or hard.
ExampleEach churn fold keeps 26.5% leavers; StratifiedKFold(5, shuffle=True, random_state=42).
Also: stratify
Splitting so that each part keeps the same share of each label as the whole dataset.
ExampleAbout 26.5% of customers left; stratify=y keeps that share in both the training and test parts.
Also: not applicable
A category value that means the question doesn't apply, rather than 'no'.
Example'No internet service' in TechSupport: the customer couldn't have tech support at all.
Also: bar
How much better than the baseline a model must be to justify building and maintaining it. Write it down before seeing any model results, or you will bargain with yourself.
Example“A model is worth it only if its 400-call list beats the best rule (about 76%) by at least 5 points.”
Also: learning with labels
Learning from examples that come with the correct answer attached. The most common and most reliable framing when labels can be had.
ExamplePast customers with a known outcome (left or stayed) teach the model to score current customers.
The setting of the complexity dial where the validation score is best, between underfitting (both scores low) and overfitting (training high, validation falling).
ExampleDepth 4: training 0.76, validation 0.76. A single tree there matches logistic regression.
Also: leakage, data leakage
When a feature contains information that only exists after the outcome. The model looks brilliant in testing and fails in real use.
ExampleLastContactReason: for most leavers the last contact was the cancellation call itself; 96% of 'Cancellation request' customers left.
Also: holdout set, locked test set
Data set aside before exploring or modelling and opened once, at the very end. Anything you look at stops being a fair exam, including for you.
Exampletest_locked.csv is saved in Session 1 and opened in Session 3.
A deliberately plain description of machine learning: it makes many small, repeated decisions by putting a label on each thing that comes in.
ExampleEmail in, 'spam' out. Frame of a game in, 'move left' out. Patient on day 61 in, '34 mg' out.
Also: cut-off, decision threshold
The score above which a prediction counts as positive. Where to put it is a business decision about the cost of each mistake.
ExampleLower the threshold and the team catches more leavers but also calls more customers who would have stayed.
Also: forward-chaining, TimeSeriesSplit, rolling validation
Train on earlier periods and validate on later ones, so the model never learns the future to predict the past. Needed whenever rows come from different dates.
ExampleWith monthly snapshots: train on January to April, validate on May, then roll forward.
Also: rules-based system
A person writes the recipe (the rules) by hand; the computer applies it to data to get answers.
ExampleA VAT calculation: the rule is known and fixed, so there is nothing to learn.
The difference between a pipeline's score on the rows it trained on and on rows it never saw. A large gap is the signature of overfitting.
ExampleUpsell data: an unlimited tree hits 77% on training customers and 15% on validation customers.
Also: data snooping
Any way information from the test (or validation) rows reaches training: shared customers, preparation learned on all rows, or choices made by looking at test results. A form of leakage.
Example10 customers sat in both the training data and the locked test set until they were removed.
Also: holdout, train_test_split
Dividing the data into a part the model learns from and a part kept aside to measure how it does on rows it has never seen.
Example80% of customers for training, 20% for testing, stratified and with a fixed seed.
Also: max_depth, min_samples_leaf
The two main brakes on a tree. max_depth limits how many questions in a row; min_samples_leaf sets the smallest group a final box may describe. Without them, a tree memorises the training rows.
Examplemax_depth=3 gives a readable flowchart; no limit gives a perfect training score and poor validation.
Also: wrong question
Giving the right answer to the wrong question. The most expensive mistake in data science; no algorithm can fix it.
ExampleThe car park model answered 'is this space full?' with 96% accuracy when the real question was 'where are the empty spaces?'.
Also: to_numeric, astype
Turning a column into another type. With errors='coerce', values that can't be converted become NaN instead of stopping the code.
Examplepd.to_numeric(df['TotalCharges'], errors='coerce') turns 11 blank spaces into NaN.
A model too simple to capture real patterns: mediocre on training data and on new data. The opposite failure of overfitting.
ExampleA tree with depth 1 asks a single question and misses most of the signal.
Also: grain
What one row represents. Choosing it is a design decision that changes the dataset and the problem.
ExampleOne row per customer (our snapshot) versus one row per customer per Monday (what weekly scoring really needs).
Also: handle_unknown
A category value that appears in new data but never in training. The pipeline must decide what to do with it instead of crashing.
ExampleA new payment method “Crypto wallet” arrives; OneHotEncoder(handle_unknown='ignore') simply leaves all its columns at 0.
Learning from data without answers: the algorithm finds structure, such as groups, and people decide what the groups mean.
ExampleClustering photos of two cats may group them by sunny versus cloudy, not by cat.
Also: treatment-effect modelling, persuadability
Predicting who will respond because of an action, rather than who will respond anyway. Needs data from a randomized comparison. A level 2 topic: recognise when it is needed and raise it.
ExampleCall the customers the call would convince, not the ones who would upgrade on their own.
Also: practice exam
Data used to compare options and tune a model: the practice exams. In this course it is carved out of the training part with cross-validation (Session 2).
ExampleComparing tree depths 3, 4 and 6 on validation data, never on the test set.
Also: vectorized operation
Applying an operation to a whole array or column at once instead of looping over values one by one. Shorter code, far faster.
Examplechurned.mean() instead of a for-loop: about 150 times faster on a million customers.
Also: XGBoost, LightGBM, CatBoost
Popular, fast libraries of gradient boosting. They differ in speed and in how they handle categories (CatBoost and LightGBM natively; XGBoost with an option). You will meet them in Earth.
ExampleXGBoost's n_estimators, learning_rate and max_depth play the same roles as scikit-learn's max_iter, learning_rate and max_depth.