Lesson 21 of 227 min
Drift
A saved model meets a world that keeps moving, so watch each input against its own past every month, watch the score when the answers come, and learn again from recent data.
After this lesson you can notice when live data stops looking like the training data.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Put each call in its month
Put bank-additional-full.csv from UCI’s Bank Marketing dataset next to your notebook. The file has a month but no year. Its rows are in date order, so a new year starts each time the month jumps back. The other blocks on this page use calls, inputs and order.
import pandas as pd
calls = pd.read_csv("bank-additional-full.csv", sep=";")
names = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]
m = calls.month.map(names.index) + 1
year = 2008 + (m.diff() < -6).cumsum()
calls["ym"] = year.astype(str) + "-" + m.astype(str).str.zfill(2)
inputs = calls.columns[:8].tolist() + ["campaign", "pdays", "previous", "poutcome"]
order = list(dict.fromkeys(calls.ym))
print(order[0], order[-1], len(order), "months")2008-05 2010-11 26 months
Other measures, and a test
A test of two samples asks whether two months could come from the same calls. With thousands of calls, it says no to tiny moves: May and November 2008 differ by less than a year of age, and the model was right in both. Watch the size. Banks often use the population stability index (PSI): 0.25 is a lot.
from scipy.stats import ks_2samp, wasserstein_distance
may = calls[calls.ym == "2008-05"].age
nov = calls[calls.ym == "2008-11"].age
print(round(wasserstein_distance(may, nov), 2), "years")
print(f"{ks_2samp(may, nov).pvalue:.0e}")0.65 years 1e-12
import numpy as np
def psi(a, b, bins):
pa = pd.cut(a, bins).value_counts(normalize=True).clip(lower=1e-4)
pb = pd.cut(b, bins).value_counts(normalize=True).clip(lower=1e-4)
return float(((pb - pa) * np.log(pb / pa)).sum())
in2008 = calls[calls.ym < "2009"].age
for ym in ["2008-11", "2009-03", "2010-05"]:
print(ym, round(psi(in2008, calls[calls.ym == ym].age, [0, 30, 40, 50, 60, 120]), 2))2008-11 0.03 2009-03 1.48 2010-05 1.47
Evidently's report
Evidently runs a check on every input and writes a report you open in a browser. It picks a measure for each input and calls an input drifted past 0.1. Version 0.7.23 does not import with pandas 3 yet, so run this block in a Python with pandas 2.3.
from evidently import Report
from evidently.presets import DataDriftPreset
before = calls[calls.ym < "2009"][inputs]
may2010 = calls[calls.ym == "2010-05"][inputs]
run = Report([DataDriftPreset()]).run(current_data=may2010, reference_data=before)
print(run.dict()["metrics"][0]["value"])
run.save_html("drift.html"){'count': 9.0, 'share': 0.75}Watch the model's own chances
The model's chances come before any answer: watch them too. First learn the bank's model from 2008, as in earlier lessons. Then put its chances in bands and compare each month's bands with 2008's. They moved most in March 2009, but in May 2010 they look almost like 2008's. Watching the chances alone would have missed 2010.
from sklearn.compose import make_column_transformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
prep = make_column_transformer((StandardScaler(), ["age", "campaign", "previous"]),
(SimpleImputer(missing_values=999, add_indicator=True), ["pdays"]),
(OneHotEncoder(handle_unknown="ignore"), inputs[1:8] + ["poutcome"]))
in2008 = calls.ym < "2009"
model = make_pipeline(prep, LogisticRegression(max_iter=1000)).fit(calls[in2008][inputs], calls.y[in2008] == "yes")calls["chance"] = model.predict_proba(calls[inputs])[:, 1]
bands = pd.cut(calls.chance, [0, 0.05, 0.1, 0.2, 0.5, 1])
before = bands[in2008].value_counts(normalize=True)
for ym in ["2008-11", "2009-03", "2010-05"]:
now = bands[calls.ym == ym].value_counts(normalize=True)
print(ym, round(now.sub(before, fill_value=0).abs().sum() / 2, 2))2008-11 0.23 2009-03 0.36 2010-05 0.1
Learn again from how many months?
The video learned again every month from the three months before. All the past is more calls, but most of them are from a world that has moved. On a schedule, you run this every month. On an alarm, you run it only in a month when an input crosses its line.
from sklearn.base import clone
from sklearn.metrics import roc_auc_score
def learn_again(keep):
chance = pd.Series(float("nan"), index=calls.index)
for k, ym in enumerate(order):
now, past = calls.ym == ym, calls.ym.isin(order[max(0, k - keep):k])
if ym >= "2009":
fit = clone(model).fit(calls.loc[past, inputs], calls.y[past] == "yes")
chance[now] = fit.predict_proba(calls.loc[now, inputs])[:, 1]
return chancein2010 = calls.ym >= "2010"
yes = calls.y[in2010] == "yes"
for keep in [3, 99]:
chance = learn_again(keep)[in2010]
print(keep, round(chance.mean(), 2), round(roc_auc_score(yes, chance), 2))3 0.53 0.7 99 0.32 0.68
A live AI app’s inputs
An AI app has inputs too: the questions people ask it. Sort each question into a topic, by hand or with a model, then watch each month’s topics the same way. This log is made up, eight questions over two months.
log = pd.DataFrame({
"month": ["2026-09"] * 4 + ["2026-10"] * 4,
"topic": ["billing", "billing", "login", "refund", "billing", "agents", "agents", "agents"]})
shares = log.groupby("month").topic.value_counts(normalize=True).unstack(fill_value=0)
print(shares.round(2))
print("moved", shares.diff().abs().sum(axis=1).iloc[-1] / 2)topic agents billing login refund month 2026-09 0.00 0.50 0.25 0.25 2026-10 0.75 0.25 0.00 0.00 moved 0.75
Run on Python 3.13.3, pandas 3.1.1, scikit-learn 1.9.1, SciPy 1.18.1; Evidently 0.7.23 with pandas 2.3.3. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Training, validation and test data
A tree gets all 256 of the penguins it learned from right. What does that tell you about new penguins?
2 of 3
A loan model learned from last year's applicants, almost none of them students. This month, a third of the applicants are students. Whether a loan is repaid shows only a year later. What is this, and when can you see it?
3 of 3
An input has three bars. In the training months: student 0.01, retired 0.04, any other job 0.95. This month: student 0.15, retired 0.10, any other job 0.75. What is the share that moved?
The ideas in this lesson
- Data drift
- The inputs a model meets stop looking like the ones it learned from; count the share of each input's bars that moved.
- Concept drift
- How the answer follows from the inputs changes: the same kind of case now gets a different answer.
- Watching a model
- Every month, check each input against its own line, and the model's chances once the answers come; learn again when they move.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Drift
Here's a question. The bank's model learned from its early calls. Its chances matched what really happened. Then the bank saved it, and kept using it. Two years later, is it still right?
Keep your guess
Hold on to your guess.
These are the bank's calls, from May 2008 to November 2010. Each call offered a customer a savings deposit, and they said yes or no.
The model is the bank's model from the earlier lessons. It gives each call a chance of a yes.
The saved model
It learned from about twenty-eight thousand calls from 2008. For those months, it said five in a hundred would say yes, on average. And five in a hundred did. Its chances were right. It was tested on calls from that same year, too. Then the bank saved it, kept it as it was, and used it every month after.
Two years later
Now, your guess.
Month by month, the share that said yes climbs. Twenty in a hundred in 2009. Fifty-two in a hundred in 2010.
And the model still says about five. It says one in twenty. Half the customers say yes.
The model didn't change. The calls did.
The inputs moved
A model learns from one stretch of time, and is used on the next. So what changed here?
First, who the bank called.
A campaign is a round of calls about one offer. In 2008, about one call in a thousand went to someone called in an earlier campaign. In May 2010, how many?
Forty in a hundred. And students: fewer than one call in a hundred, then fifteen.
An input's bars are the share of calls with each value. Those bars have moved.
Drifting means slowly moving away.
The inputs are the facts a model reads. When they stop looking like the ones it learned from, that's called data drift.
The share that moved
How far did they move?
Think of a city map printed in 2008. By 2010, some streets have changed.
Here, set the two sets of bars side by side. In 2008, almost every call went to someone never called before. In May 2010, sixty in a hundred did. So about forty calls in a hundred would have to move from one bar to the other, to make them match.
The share that moved: zero point four.
Zero means the same bars. One means nothing alike. And month by month, it climbs.
The answers moved
The facts a model reads can move. Can the way people answer move too?
Take one kind of customer: never called before, aged thirty to forty-nine, and called on a cell phone.
In 2008, six in a hundred said yes. In 2009, fourteen. In 2010, forty-seven.
The same facts, a different answer. That's called concept drift.
A changed street, you can see on the ground.
A change in how people answer, you can't see in the inputs. Only the answers show it.
Watch both
A model's inputs can move, and so can the answers.
So what do you watch, and when?
The inputs, every month, as they come in. They don't need any answers.
Then how right the model is, once the answers come in.
At this bank, the answer comes at the end of each call. For a loan, it comes a year later. So the inputs warn you first.
Each input's own line
How much movement is too much? Try one line, zero point one, for every input. Which input passes it every month, even in 2008?
The phone: whether the bank called a cell phone or a landline. In May 2008, every call went to a landline, while across all of 2008 it was about half and half. That's a move of zero point five, within 2008, while the model's chances were still right. So give each input its own line, a little above the most it moved in any month of 2008.
Then comes March 2009, the first month with calls after 2008. Five inputs cross their lines, including age and job.
Learn again
When they cross, learn again from recent months. That's called retraining. The model learns again each month, from the three months before it. Now its chances follow the yeses. In 2010, it says fifty-three in a hundred, on average, and fifty-two in a hundred said yes.
In code
In real code, with pandas.
An input's bars are its values counted as shares: for the months of 2008, and for one month.
Add up the gaps between them, and divide by two, since each call that moves leaves one bar and joins another.
That's the share that moved.
Each input's line is the most it moved in any month of 2008, plus zero point zero five.
A loop over the months prints the inputs past their lines.
March 2009 comes first, with those five.
Then you learn again on the last three months.
This check can run every week on a live model. Tools like Evidently do it for you.
Three ideas
So: in data drift, the inputs move. In concept drift, the answers move. Watch each input against its own line every month, watch the model's chances once the answers come in, and learn again.
The lab
That's the end of this unit. In the lab, you use these two lessons to give a model a check-up: by group, and month by month.
Watch the model
So watch a saved model, because the world keeps moving. Now try it on this lesson's page, and take the quiz. Learn again, and find the month even the new model misses.
You use this lesson in Lab 8: A check-up for a model in use, which comes next.
Facts last checked on .
