Loss & gradient descent
Lesson opener
In one line: Loss is one number for "how wrong" — C0001's spend 35.17 versus the file mean 50.60 misses by −15.43 (squared 238.20) — and gradient descent nudges a guess downhill.
Why it matters: .fit() is this loop: measure the miss, see which way reduces it, take a small step, repeat. If you cannot say what the loss is, you cannot tell whether training did anything.
Before this lesson: Dot product. Same data/customers.csv. Pins: numpy==2.1.3, pandas==2.3.3.
Practitioner focus: We use squared error on monthly_spend so you can check the arithmetic without a neural net. This is not a churn loss. The 50.60 mean is
df["monthly_spend"].mean()rounded to two decimals.
What you will learn
By the end of this lesson you will be able to:
- Compute one customer's error and squared error against the mean spend.
- Average squared error on the first three customers (MSE 1884.19).
- Say in one sentence what a gradient is (the direction of steepest increase).
- Take one gradient-descent step on a toy intercept.
- See the loss drop after that step.
- Connect that step to what
.fit()does, without writing backprop.
Worked example: how wrong is the mean?
Step 1 — One customer. The lazy guess for everyone's spend is the mean. C0001 is below it.
import pandas as pd
df = pd.read_csv("data/customers.csv")
mean = df["monthly_spend"].mean()
spend = float(df.iloc[0]["monthly_spend"])
err = spend - mean
print(round(mean, 2))
print(round(spend, 2))
print(round(err, 2))
print(round(err ** 2, 2))Expected output:
50.6
35.17
-15.43
238.2Loss for this one row, if we use squared error, is 238.2. Lower would be better. A perfect guess would be 0.
Step 2 — Mean squared error on three rows. Average the squares so one huge Platinum spend cannot hide.
import pandas as pd
import numpy as np
df = pd.read_csv("data/customers.csv")
mean = df["monthly_spend"].mean()
sp = df.head(3)["monthly_spend"].to_numpy(dtype=float)
mse = np.mean((sp - mean) ** 2)
print(np.round(sp, 2))
print(round(float(mse), 2))Expected output:
[ 35.17 121.3 71.01]
1884.19C0002's ₹121.30 is far above 50.6 — that square dominates the 1884.19. That is what "sensitive to outliers" means.
Step 3 — One downhill step on a toy intercept. Pretend the only parameter is a single guess g for C0001's spend. Loss = (35.17 - g) * 2. The derivative with respect to g is -2 (35.17 - g). A step is g := g - lr * derivative.
Start at g = the file mean, lr = 0.1.
import pandas as pd
df = pd.read_csv("data/customers.csv")
spend = float(df.iloc[0]["monthly_spend"])
g = float(df["monthly_spend"].mean())
lr = 0.1
deriv = -2 * (spend - g)
g_new = g - lr * deriv
print(round(deriv, 2))
print(round(g_new, 2))
print(round((spend - g) ** 2, 2))
print(round((spend - g_new) ** 2, 2))Expected output:
30.87
47.52
238.2
152.45Loss fell from 238.2 to 152.45. The guess moved toward 35.17. That is gradient descent on one number.
Step 4 — What .fit() is. In BA 2 and sklearn, .fit() repeats a step like this (or a smarter cousin) for every weight. You do not write the derivative by hand. You still pick the loss, and you still look at whether it went down.
Pause and think
Q1. Why square the error?
So misses above and below the guess do not cancel. −15 and +15 would average to 0 without the square.
Q2. What if the learning rate is huge?
The guess jumps past the target and loss can rise. That is a step that was not small.
Q3. Is 1884.19 a "bad" model?
It is the MSE of guessing the global mean on three very different customers. It is a baseline, not a verdict.
Guided practice: squared error of C0003 vs the mean
import pandas as pd
df = pd.read_csv("data/customers.csv")
mean = df["monthly_spend"].mean()
spend = float(df.loc[df["customer_id"] == "C0003", "monthly_spend"].iloc[0])
print(round((spend - mean) ** 2, 2))Expected output:
416.42Independent practice: MSE of all 300 vs the mean
This is the variance of monthly_spend (population style: divide by n).
import pandas as pd
import numpy as np
df = pd.read_csv("data/customers.csv")
mean = df["monthly_spend"].mean()
mse = np.mean((df["monthly_spend"] - mean) ** 2)
print(round(float(mse), 2))Expected output:
10802.48Common mistake
The deliberate mistake
Symptom: after a "training" loop the loss is higher than at the start.
Diagnosis: the step added the derivative instead of subtracting it, or
lrwas wild.Correction:
g = g - lr * derivwhenderivis the slope of loss (uphill).Prevention: print loss before and after one step. If it rose, do not run 1,000 more steps.
Where this connects
What you can now do:
- Compute a squared error you can check by hand.
- Take one downhill step and watch loss fall.
- Describe
.fit()as that loop, not as magic.
Next lesson: eˣ, log & loss. Churn needs a probability in (0, 1). That squash uses \(e^{-z}\).