internalsGet Pro

Module 01 · Lesson 2 of 10Free

What machine learning is: rules learned from data

Level
Beginner
Topic
Machine learning fundamentals
Reading time
13 min

When you finish this page you can

  1. Explain learning as a search for the rule, and its numbers, that makes the fewest mistakes on past examples with known answers.
  2. Name the three parts every learning setup has: a family of rules with adjustable numbers, a score for how wrong they are, and a search.
  3. Show why a rule that is perfect on past data can be worse on new data, and check it on held-out examples.
  4. Find a churn threshold from made-up Kartly data with a short NumPy and pandas snippet.
  1. Introduction to machine learning engineering12 min
0:00 / 5:31
Show transcript

0:00 Kartly is our example online shop. Every Monday, Joseph’s growth team emails vouchers to customers who seem to be leaving. Joseph picks them with one rule: no order in the last 60 days. Farah, an ML engineer, asks where the 60 came from. Joseph shrugs. “It felt right,” he says. But Farah has something better than a feeling. She has last year’s customers. For each one, she knows how long it had been since their last order. She also knows whether they left. Left means no order in the next 60 days. So here is the question. Can a program find a rule like Joseph’s, and its number, from past customers? And how will we know it works on next Monday’s customers?

0:35 Start small. Ten past customers. Each one has a gap, the days since their last order. And each has an answer: did they leave, or stay? Farah keeps the shape of Joseph’s rule. Flag a customer if their gap is longer than some number of days. That number is called a threshold. Call it t. Only t is left open. Now Farah counts mistakes. A mistake is flagging someone who stayed, or missing someone who left. Try Joseph’s 60. It misses three leavers. Now try 45. It misses just one. She tries a few more numbers the same way. Of all the numbers she tries, 45 makes the fewest mistakes. Nobody chose 45. Farah chose the shape of the rule. The data chose the number. That is machine learning in its smallest form: a search for the rule that makes the fewest mistakes on past examples.

1:20 Every model has the same three parts. A model is just a rule whose numbers came from data. Part one is a family of rules with adjustable numbers. Here the family is: gap over t. The adjustable numbers are called the model’s parameters. Here there is just one, t. Part two is a loss. It is one number for how wrong a rule is on past examples. Here, it is the share of past customers the rule gets wrong. Lower is better. Each known answer, left or stayed, is called a label. Part three is a search. It is a way to find numbers with low loss. With one number, the search is easy. Try every value of t, and keep the best. Running that search is called training. Put the three together and they run in a loop. The rule makes predictions. The loss counts the mistakes. The search picks a new number to try. When no number does better, the loop stops. What comes out is the trained model: the rule’s code, plus its learned numbers. For Farah, that is one number, 45.

2:13 Real models read many inputs. These are called features. Say Farah adds a second one: orders in the last 90 days. Now the rule is a weighted score. Each input has a weight, which is how much it pushes the score. If the score is above zero, flag the customer. Take a 50-day gap. With some recent orders, the customer is not flagged. With none, the same gap is flagged. Trying every combination stops working fast. Add inputs, and the combinations explode. Ten inputs is already far too many to try one by one. So larger models follow the loss downhill, step by step. That is called gradient descent, and a later lesson explains it. Rule families come in different sizes. A single threshold. A weighted score. A decision tree. A neural network, with thousands to billions of weights. The family limits what a model can learn. One threshold can never say: a long gap is fine for customers who order every three months.

3:04 Now a trap. Many engineers assume the best rule makes zero mistakes on past data. Farah can build one. Flag a customer if the gap is over 45 days, or exactly 34 days. On the ten past customers, it makes no mistakes at all. Next Monday, many customers have a gap of exactly 34. Most of them stay. In Farah’s made-up data, only about a quarter leave. But the exception flags every one. So it is wrong for most of them. Customer three was one unusual leaver, not a pattern. This is overfitting. The rule learned one customer’s quirk, not a pattern. A rule that only repeats the answers it saw would score perfectly on them, and predict nothing useful. What Joseph needs is generalization. That means a rule that does well on customers it has never seen. So how should Farah check a rule before Joseph uses it? She could count mistakes on the same past customers. That is fast, but it rewards memorizing. She could use the rule on Monday’s list and wait. That measures the real thing, but the answers arrive 60 days later. The best choice costs nothing and runs today. Keep some past customers out of training, and count mistakes only on them. Those held-out customers are called the test set. Farah keeps a quarter of her past customers aside, and trains on the rest. Then she compares the two mistake rates. If they are close, the rule generalizes. If training looks far better, it memorized. Farah tries it on made-up data. The search never sees the hidden pattern. It still finds a number close to 45. Training and held-out mistakes come out about the same. And Joseph’s 60 makes more mistakes. These are expected values from made-up data, not measured results.

4:38 Last, what learning can’t do. It only knows the past. The festival sale from the last lesson broke a rule that held all year. It needs answers, and they come late. Farah learns who left only 60 days after each Monday. And it finds patterns, not causes. Long gaps go with leaving. That doesn’t mean a voucher will stop it. So treat 45 as what last year’s customers say, and relearn it when customers change.

4:59 Five points to keep. One. Learning is a search for the rule with the fewest mistakes on past examples. Two. Every model has three parts: a family of rules, a loss, and a search. Three. The trained model is the rule plus its learned numbers. Four. A perfect fit on the past can be memorizing, so check on held-out examples. Five. Learning only knows the past, and finds patterns, not causes. Farah had an answer for every past customer. But many problems have no answers to learn from. Next lesson: supervised, unsupervised and reinforcement learning.

Why 60 days?

is our example online store. Its ML team works on a sample that fits in a free notebook: about 1 million orders from 200,000 customers. Every Monday, Joseph’s growth team emails 20,000 vouchers of ₹100 to customers who seem to be leaving.

Today the list comes from a rule Joseph wrote: flag anyone with no order in the last 60 days. Farah, an ML engineer, asks him where the 60 came from. “It felt right,” he says.

Farah has something better than a feeling. For last year’s customers she knows two things: how many days had passed since their last order on 1 January, and whether they then left. Here “left” means no order in the next 60 days. Each customer is a past example with a known answer.

So the question this lesson answers is: how can a program find a rule like Joseph’s, and its number, from past customers, and how do you know that rule will work on next Monday’s customers?

Learning is a search for fewer mistakes

Farah starts small, with ten past customers from the sample. The rule stays the same shape as Joseph’s: flag a customer if their gap since the last order is longer than some number of days, called t. Only t is open.

Customer Days since last order Then left?
1 5 No
2 12 No
3 34 Yes
4 38 No
5 42 No
6 50 Yes
7 55 Yes
8 70 Yes
9 90 Yes
10 120 Yes

These ten customers are a made-up example for this lesson.

Check yourselfAnswer in your head first, then reveal
Joseph’s rule flags a customer when the gap is over 60 days. On these ten customers, does t = 60 or t = 45 make fewer mistakes?Show answerHide answer
t = 45 makes one mistake (it misses customer 3); t = 60 makes three (it misses customers 3, 6 and 7). A mistake is either flagging someone who stayed or missing someone who left.

Farah counts the mistakes for a few values of t:

t = 30

flags customers 3–10; customers 4 and 5 stayed = 2 mistakes

It catches every leaver but sends vouchers to two loyal customers.

t = 45

flags 6–10; misses customer 3 = 1 mistake

The fewest mistakes of the four.

t = 60 (Joseph’s rule)

flags 8–10; misses 3, 6 and 7 = 3 mistakes

It waits too long and misses customers who were already leaving.

t = 90

flags only 10; misses 3, 6, 7, 8 and 9 = 5 mistakes

Almost nobody gets a voucher.

That is machine learning in its smallest form. Nobody chose 45. Farah chose the shape of the rule, and the data chose the number.

Try other thresholds yourself:

Flagged050100150 dayst = 60
Mistakes on 10 customers
3
Expected mistakes on 200,000 made-up customers
14%

Too high: leavers are missed

Drag t and watch the mistakes on the ten customers, and on 200,000 made-up ones.
Mistakes at four thresholds
Threshold tMistakes on 10 customersExpected on 200,000
30 days216%
45 days111%
60 days314%
90 days522%

Three parts every model shares

Write Farah’s rule as notation. The rule predicts y^\hat{y} for a customer with gap xx:

y^=1 if x>t, otherwise 0\hat{y} = 1 \text{ if } x > t, \text{ otherwise } 0
  • y^\hat{y}: the prediction, 1 for “will leave” and 0 for “will stay”.
  • xx: the customer’s days since last order.
  • tt: the threshold, the number the data chooses.

Its is the share of past customers it gets wrong:

L(t)=1n∑i=1n∣y^i−yi∣L(t) = \frac{1}{n} \sum_{i=1}^{n} \lvert \hat{y}_i - y_i \rvert
  • L(t)L(t): the loss for one value of t.
  • nn: the number of past customers.
  • y^i\hat{y}_i and yiy_i: the prediction and the true answer for customer i. Both are 0 or 1, so their difference is 1 exactly when the rule is wrong.

is finding the t with the lowest loss:

t∗=arg⁡min⁡tL(t)t^{*} = \arg\min_{t} L(t)

On the ten customers, L(45)=0.1L(45) = 0.1 and L(60)=0.3L(60) = 0.3.

Every you will meet in this course has the same three parts:

The rule family, the loss and the search run in a loop. What comes out is the rule plus its learned numbers.
  1. A family of rules with adjustable numbers. Here, “gap over t”. The adjustable numbers are the model’s .
  2. A loss. One number for how wrong a set of parameters is on past examples with known answers. Each known answer is called a . Counting every mistake the same is a choice; Loss functions shows how to weigh them.
  3. A search. A way to find parameters with low loss.

A classic definition says the same thing: a program learns if its performance on a task, as measured by some score, improves with experience. Google’s introduction calls a model a mathematical relationship derived from data.2

The trained model is the rule family’s code plus the learned numbers. For Farah’s rule, that is one number: 45. That is what the model store from Introduction to machine learning engineering keeps, with its version.

One input and one parameter is easy: try every t from 0 to 180 and keep the best. Real churn models read many inputs, which Data, features and labels calls . Say Farah adds a second one: orders in the last 90 days. Now the rule is a weighted score:

s=w1x1+w2x2+bs = w_1 x_1 + w_2 x_2 + b
  • ss: the customer’s score; flag the customer if it is above 0.
  • x1x_1: days since last order, and x2x_2: orders in the last 90 days.
  • w1w_1 and w2w_2: weights, how much each input pushes the score.
  • bb: a constant that moves every score up or down.

With example weights w1=0.1w_1 = 0.1, w2=−1.5w_2 = -1.5 and b=−4b = -4, a customer with a 50-day gap and 2 recent orders scores 5−3−4=−25 - 3 - 4 = -2: not flagged. With no recent orders, the score is 5−0−4=15 - 0 - 4 = 1: flagged. The second input changed the answer for the same gap.

Trying every combination stops working fast. Ten inputs with 100 candidate values each is 100¹⁰ = 10²⁰ combinations. So larger models use a search that follows the loss downhill, step by step: Gradient descent explains how.

Rule family Its parameters Taught in
Threshold on one input 1 number This lesson
Weighted score 1 weight per input, plus b Module 07
Decision tree Which input to split on, and where Decision trees
Neural network Thousands to billions of weights Module 09

The family limits what the model can learn. A single threshold can never say “a long gap is fine for customers who order every three months”. A richer family can, but it also brings a new risk.

A perfect fit on the past can fail

Many engineers assume the rule with zero mistakes on past data is the best rule. Farah can build one for the ten customers: flag if the gap is over 45 days, or exactly 34 days. It makes zero mistakes on them.

Check yourselfAnswer in your head first, then reveal
Next Monday, 100 new customers have a gap of exactly 34 days. Will the zero-mistake rule do better or worse on them than plain t = 45?Show answerHide answer
Worse. In Farah’s made-up data only about 25 of every 100 customers with a 34-day gap leave, so flagging all of them is wrong about 75 times, against about 25 for t = 45. Customer 3 was one unusual leaver, not a pattern.
The extra exception fits one past customer and is wrong for most new ones.

The exception learned one customer’s quirk, not a pattern. This is . scikit-learn’s guide puts it bluntly: testing a model on the data it learned from is a mistake, because a model that only repeats the answers it saw would score perfectly and predict nothing useful.1 What Joseph needs is : a rule that does well on customers it has never seen. Overfitting and underfitting goes further.

How should Farah check a learned rule before Joseph uses it?

Count mistakes on the same past customers it learned from.

Fast, but it rewards memorizing. The zero-mistake exception rule would win here and lose on Monday.

Use the rule on Monday’s list and wait to see who leaves.

Measures the real thing, but the answers arrive 60 days later, and meanwhile each week’s ₹20 lakh of vouchers follows an untested rule.

Why this choice

Holding out part of the data as a is common practice for exactly this reason.1 Farah keeps 50,000 of the 200,000 past customers aside, and trains on the other 150,000. If the two mistake rates are close, the rule generalizes. If training looks far better, it memorized.

The choice changes when the world changes. Held-out customers come from the same past as the training ones, so they can’t warn about a festival sale that never happened before. Then only live results show the truth, and the wait is worth it.

Try it yourself

This snippet runs in a free Colab or Kaggle notebook, or on a laptop with NumPy and pandas, in a few seconds. It makes up 200,000 Kartly customers with a hidden pattern: the longer the gap, the likelier they leave, with even odds at 45 days. The search never sees that pattern. It only sees gaps and answers.

Python
import numpy as np
import pandas as pd

rng = np.random.default_rng(42)
n = 200_000  # customers in Kartly's notebook sample (made-up data)

gap = rng.exponential(scale=30, size=n).round().astype(int)
# Hidden pattern: even odds of leaving at 45 days, higher after.
p_leave = 1 / (1 + np.exp(-(gap - 45) / 10))
left = rng.random(n) < p_leave

customers = pd.DataFrame({"days_since_last_order": gap, "left": left})
train = customers.sample(frac=0.75, random_state=42)
held_out = customers.drop(train.index)


def mistake_rate(df: pd.DataFrame, t: int) -> float:
    """Share of customers the rule 'gap over t days' gets wrong."""
    flagged = df["days_since_last_order"] > t
    return float((flagged != df["left"]).mean())


thresholds = list(range(0, 181))
losses = [mistake_rate(train, t) for t in thresholds]
best_t = thresholds[int(np.argmin(losses))]

print("Learned threshold:", best_t)
print(f"Training mistakes:  {mistake_rate(train, best_t):.1%}")
print(f"Held-out mistakes:  {mistake_rate(held_out, best_t):.1%}")
print(f"Joseph's 60, held-out: {mistake_rate(held_out, 60):.1%}")

Expect a learned threshold close to 45, give or take a couple of days. Expect about 11% mistakes on both the training and the held-out customers, and about 14% for Joseph’s 60. These are expected values worked out from the made-up data, not measured results.

What to look for: the search found the hidden 45 from examples alone. The training and held-out rates are close, because one number can’t memorize 150,000 customers. On the full 200,000, three points fewer mistakes is about 6,000 customers sorted the right way.

What learning can’t do

A learned rule is only as good as its examples:

  • It only knows the past. The festival sale in the previous lesson broke a rule that held all year.
  • It needs answers, and they come late. Farah learns who left only 60 days after each Monday.
  • It finds patterns, not causes. Long gaps go with leaving; that doesn’t mean a voucher will stop it. Correlation is not causation covers why.

Where this shows up

Farah had an answer, “left” or “stayed”, for every past customer. Many problems have no answers to learn from, and some learn by trial and error; the next lesson sorts them out.

Common mistakes

  • Judging a model on its training data. It rewards memorizing. Always score on held-out examples.
  • Picking a richer rule family by default. More parameters can fit more quirks. Start with the simplest family that can express the pattern.
  • Treating the learned number as a law. 45 days is what last year’s customers say. Relearn it when the customers change.

Check your understanding

Check yourselfAnswer in your head first, then reveal
Farah’s learned rule makes 11% mistakes on training customers and 11% on held-out customers. A new rule makes 4% on training and 16% on held-out. Which should Joseph use?Show answerHide answer
The first. The second is better only on customers it learned from, which is the sign of memorizing. The tempting wrong answer is the 4% rule, but held-out mistakes are the estimate for next Monday.
Check yourselfAnswer in your head first, then reveal
Farah retrains the threshold on this year’s customers and gets 52 days instead of 45. Her code didn’t change. What changed the model?Show answerHide answer
The data. The rule family, the loss and the search are the same, but the examples are different, so the number with the fewest mistakes moved.
Check yourselfAnswer in your head first, then reveal
Joseph wants the rule to treat customers who usually order every three months differently. Can more data fix a single-threshold rule?Show answerHide answer
No. One threshold on one input can’t express “it depends on the customer’s usual rhythm”, however much data it sees. Farah needs a richer family, such as a weighted score with an input for the usual gap.
Check yourselfAnswer in your head first, then reveal
A model of Kartly’s churn makes zero mistakes on held-out customers. What should Farah check before celebrating?Show answerHide answer
That nothing in the inputs gives the answer away, such as a field filled in only after a customer leaves. A perfect score on churn is usually a sign of a bug in the data, not a perfect model.

Summary

  1. A program finds a rule from past examples with known answers by searching for the parameters that make the fewest mistakes; you check it on held-out examples it never saw.
  2. Every model has three parts: a family of rules with adjustable numbers, a loss that scores mistakes, and a search that lowers the loss.
  3. The trained model is the rule family’s code plus the learned numbers, such as t = 45.
  4. A rule that fits the past perfectly can memorize quirks; held-out mistakes, not training mistakes, estimate how it will do next week.
  5. Learning only knows the past, needs answers that may arrive late, and finds patterns rather than causes.

Report a mistake

Tell us what’s wrong in this lesson and we’ll fix it.