I asked an AI to build me a customer churn model. It wrote clean, working code in about nine seconds. The model scored 99.93% accuracy. I was delighted for roughly two minutes, which is how long it took me to realise the model was completely worthless.
That gap, between code that runs and code that is right, is the whole story of learning data science in the age of AI. This post is an honest account of how I am actually doing it: the roadmap I follow, how I use AI without letting it hollow out my skills, and a reproducible lab that shows exactly how a beginner ends up with a perfect-looking model that would lose a company money.
I am writing this as someone still in the middle of it, not from the far side. I finished a BCA, I work on security and web projects, and I am learning data science in the evenings with free tools and a laptop in Nepal. If that sounds like you, this is written for you.
What this guide covers
- Will AI replace data scientists? The honest answer
- What AI actually changed, and what it did not
- The lab: a 99.93% model that is worthless
- The roadmap I am actually following, stage by stage
- How I use AI while learning: six rules
- Setting up, free, on a modest laptop
- Projects that prove something
- Beginner mistakes that cost the most time
- Doing this from Nepal
- Frequently asked questions
- Reproduce the lab yourself
Will AI replace data scientists? The honest answer
This is the question that stops people before they start, so let us deal with it first.
The honest answer is that AI has already replaced a large part of the job, and that part was never the valuable part. Writing a pandas groupby from memory, remembering the scikit-learn import path, producing a matplotlib chart with readable axis labels: all of this is now typing a sentence. If your plan was to be the person who remembers syntax, that plan is finished.
What has not been replaced is the judgment that decides whether the output is worth anything. In the lab below, the AI-written code was flawless. Every line did what it claimed. The result was still garbage, because the mistake was not in the code, it was in the framing: a column had been included that would not exist at prediction time. No amount of better code generation fixes that. It needs someone who understands what the data means.
In plain words: AI took over the typing. It did not take over the thinking. The skill that pays is no longer writing the model, it is knowing when the model is lying to you.
Be careful with the confident numbers you will see on this topic. A lot of articles quote exposure percentages and automation forecasts with no methodology attached. Treat those as opinion. What you can verify yourself is the thing this post demonstrates: that a model can score near-perfect and be useless, and that catching it requires knowledge no tool currently supplies.
What learning data science in the age of AI actually changed
When I compare how I learn now against how the tutorials from a few years ago assumed I would learn, four things are genuinely different.
1. Syntax is no longer a bottleneck, so it is no longer a filter
It used to take a beginner a week to get a messy CSV loaded, cleaned and plotted. That week taught you something, mostly stubbornness. Now it takes a prompt. The upside is real: you reach interesting problems far sooner. The cost is that the struggle which used to build intuition has been removed, and nothing has replaced it automatically. You have to put it back deliberately.
2. The expensive mistakes moved upstream
Beginners used to fail at the keyboard: syntax errors, shape mismatches, broken joins. Those failures are loud and quick to fix. The failures that survive now are quiet ones: a leaked column, a target defined slightly wrong, a test set that is not representative, a metric that flatters a useless model. Nothing crashes. The notebook runs top to bottom and prints a number you like.
3. Reading code matters more than writing it
I now generate far more code than I type, which means most of my working time is spent reading. Reading critically is a separate skill from writing, and it is the one I have had to train hardest. If you cannot look at twenty lines of modelling code and say what assumption it is making, you are not supervising the tool, you are just forwarding its homework.
4. Statistics went from optional to load-bearing
This is the part people most want to skip and the part that has become least skippable. Every trap in the lab below is a statistics problem wearing a programming costume. Class imbalance, base rates, train and test independence, the difference between ranking and classification: these are the things that decide whether your work is real.
The lab: a 99.93% model that is worthless
Everything below is measured, not asserted. The script is at the end of the post, it is deterministic, and it runs in about three seconds on a laptop. If you only do one thing from this article, run that file and read its output.
The setup
I generated a small telecom-style table of 5,000 customers with four columns and a churn flag. Real churn rate: 6.64%. The honest predictors are tenure in months, monthly charges and support ticket count. Churn genuinely depends on all three, so there is real signal to find.
I also added one more column, exit_survey_score, and this is the trap. In a real data warehouse this column exists and is populated. What is not written down anywhere in the table is that it is only filled in after a customer has already cancelled. It is a record of the past, not a predictor of the future. Nothing about the column name, type or distribution announces this. You would only know by asking someone who works there.
Trap 0: the baseline nobody computes
Before any model, predict that nobody churns. Every customer, same answer, no maths involved.
That scores 93.33% accuracy.
Sit with that for a second, because it reframes everything that follows. If you train a model, get 93% accuracy and feel pleased, you have built something exactly as useful as a function that returns False. Any accuracy figure you are shown is meaningless until you know the base rate it is competing against. On imbalanced data, which is most interesting data, accuracy is not a weak metric, it is an actively misleading one.
Trap 1: target leakage, the one that looks like success
Now train a logistic regression on all four columns, the leaky one included. This is precisely what you get if you hand a table to an assistant and say “build me a churn model”, because the assistant has no way to know what that column means.
| Model | Accuracy | ROC AUC | Precision | Recall |
|---|---|---|---|---|
| Always predict “no churn” | 0.9333 | 0.500 | 0.00 | 0.00 |
| With leaked column | 0.9993 | 1.000 | 1.00 | 0.99 |
| Honest features only | 0.9333 | 0.7005 | 0.50 | 0.01 |
A ROC AUC of 1.000 is a perfect score. On a held-out test set the leaky model got 99 of 100 churners right and raised exactly zero false alarms. Every validation check a beginner knows how to run comes back clean. The train and test split was done correctly. There is no overfitting in the usual sense.
And in production it would predict nothing at all, because on the day you need an answer, exit_survey_score is empty for every customer who has not yet left. The model learned to detect customers who had already churned. It is a very accurate description of the past dressed up as a forecast.
The tell: a near-perfect score on a messy real-world problem is not good news, it is a smoke alarm. Churn, fraud, default and disease prediction are hard. If you score 0.99 on your first attempt, assume leakage and go looking for it before you celebrate.
Trap 2: scaling before the split, and an honest null result
Every tutorial warns you about this one: if you fit a scaler on the whole dataset before splitting, the scaler has seen your test data, and information leaks. The textbook fix is to put the scaler inside a pipeline so it is fitted on training folds only.
I measured it, expecting a nice scary number. I did not get one.
| Approach | ROC AUC |
|---|---|
| StandardScaler fitted on all data, then split (wrong) | 0.7005 |
| Scaler inside a pipeline, 5-fold cross-validation (right) | 0.7281 ± 0.0344 |
The difference is not meaningful here, and I am reporting that rather than pretending otherwise. The reason is that StandardScaler only learns two numbers per column, a mean and a standard deviation, and with 5,000 rows those are nearly identical whether or not the test set is included.
So should you ignore the advice? No, and the reason matters more than the rule. The leak is small for this transformer on this much data. It becomes large when the transformer learns a lot from the data: target encoding of a categorical column, imputation using the median, SMOTE oversampling, or feature selection that peeks at the label. Those can move a score by a wide margin. Use the pipeline always, because it costs you nothing and it is the same habit that saves you on the day the transformer is a hungry one.
In plain words: the rule is right, the usual explanation of why is exaggerated. Knowing which transformers actually leak is the difference between following a rule and understanding it.
Trap 3: the honest model is not useless, you are reading it wrongly
Look again at the honest model in Table 1: accuracy 93.33%, recall 0.01. It found one churner out of a hundred. By any normal reading that is a failure, and most beginners delete it here and go hunting for a fancier algorithm.
But its AUC is 0.70, and AUC does not care about the decision threshold. An AUC of 0.70 says the model can rank customers by risk, it just cannot find any customer whose probability of churning exceeds 50%, which is unsurprising when only 6.64% of people churn at all. The default threshold is wrong for the problem, not the model.
So stop asking “will this customer churn?” and start asking “who are the riskiest customers I can afford to call?” Rank all 1,500 test customers by predicted risk and take the top slice:
| Contact the riskiest | Customers called | Churners caught | Recall | Precision | Lift vs base rate |
|---|---|---|---|---|---|
| Top 5% | 75 | 17 of 100 | 0.17 | 0.227 | 3.4× |
| Top 10% | 150 | 25 of 100 | 0.25 | 0.167 | 2.5× |
| Top 20% | 300 | 42 of 100 | 0.42 | 0.140 | 2.1× |
| Top 30% | 450 | 53 of 100 | 0.53 | 0.118 | 1.8× |
Calling the riskiest 5% of customers finds churners at 3.4 times the rate of calling people at random. If a retention call costs a few hundred rupees and a saved customer is worth thousands, that is a profitable programme built on the model everyone deleted. Nothing about the model changed between “useless” and “profitable”. Only the question changed.
In plain words: most real-world machine learning is ranking under a budget, not classification. Ask how many people you can act on, then take that many from the top.
What the lab actually proves
Three traps, one pattern. In every case the code was correct and the conclusion was wrong. An assistant that writes perfect scikit-learn cannot save you from any of them, because none of them are coding errors:
- The leak required knowing what a column means in the business, which is not in the data.
- The preprocessing question required knowing which transformers learn enough to matter.
- The threshold required knowing what decision the model is feeding, and what it costs.
That is the job now. Everything in the roadmap below is chosen to build exactly that judgment.
The roadmap I am actually following
Most of the data science roadmaps for beginners you will find online list the same topics in the same order and never say which ones actually bite. This is not a list of everything in data science. It is the order I am going in, with honest time estimates for someone studying perhaps ten hours a week alongside other work. The stages overlap; the order matters more than the dates.
Stage 1 — Python, properly, not frantically
You need less Python than you think: lists, dictionaries, loops, functions, comprehensions, reading files, and enough object-oriented syntax to read other people’s code. You do not need decorators, metaclasses or async.
Type this stage out by hand. This is the one place I deliberately do not use AI completion. The muscle memory of writing a loop that is off by one and finding it yourself is what later lets you read generated code and feel that something is wrong. Skip this and you will spend the next five stages unable to audit anything.
Our own Python expense tracker walkthrough covers the exact subset that matters in a single buildable project.
Stage 2 — SQL and data wrangling
Most real data lives in a database, and most real analysis is a GROUP BY away from done. Learn SELECT, WHERE, JOIN (all four kinds), GROUP BY with HAVING, window functions, and subqueries. Then learn the pandas equivalents of each, because you will switch between them constantly.
Practise SQL in the browser on our SQL Lab, then read DBMS fundamentals for the model underneath it, and NoSQL and the CAP theorem once relational makes sense.
The habit to build here: after every join, check your row count. A join that silently duplicates rows is the single most common way an analysis goes quietly wrong.
Stage 3 — Statistics (the long one)
Everything that went wrong in the lab lives here. Specifically, learn:
- Base rates and class imbalance — why 93% accuracy meant nothing.
- Sampling and independence — why the test set must be untouched, and what “untouched” really includes.
- Distributions, mean versus median, and variance — enough to know when an average is lying.
- Conditional probability and Bayes — the backbone of every “given what we observed” question.
- Hypothesis testing and confidence intervals — and their limits, especially p-hacking.
- Correlation versus causation, confounders, and Simpson’s paradox.
Free and genuinely good: Think Stats by Allen Downey, and Khan Academy’s statistics track for the parts that do not stick.
Stage 4 — Visualisation and communication
matplotlib for control, seaborn for speed. But the tooling is the small part. The real skill is writing the one sentence that says what the chart means, and being willing to present a result that disappoints the person who asked for it.
A practical test I use: if I cannot explain a finding to someone non-technical in four sentences without using the word “model”, I do not understand it yet.
Stage 5 — Machine learning
Start with linear and logistic regression and stay there longer than feels comfortable, because they are the models you can fully interrogate. Then decision trees, random forests and gradient boosting, which is what actually wins on tabular data. Then k-means and PCA for the unsupervised side.
Spend at least as much time on evaluation as on algorithms: train/validation/test, cross-validation, the confusion matrix, precision, recall, F1, ROC AUC, and choosing a threshold for a real decision. Table 3 above is that skill in miniature.
Deep learning comes after this, if at all. For tabular business problems, gradient boosting usually wins. If you want the mathematical foundation of modern models, our derivation of scaled dot-product attention builds it from scratch, and TinyML shows machine learning under hard memory constraints.
Stage 6 — Ship something, and keep shipping
A notebook on your laptop is not evidence. Put the work where someone can check it: a repository with a readable README, a short write-up of what you found and what you got wrong, and ideally a small deployed app. Learn enough Git, virtual environments and Docker basics to make that reproducible.
If you want to understand the systems your work will live inside, our system design guide for beginners is the companion to this one.
How I use AI while learning: six rules
You can learn data science with AI tools far faster than I could have five years ago, and I use assistants every single day. I also think most beginners are using them in a way that will leave them unemployable. These are the rules I hold myself to.
Rule 1: predict before you generate
Before asking for code, I write down in a comment what I expect the output to look like: the shape of the result, the rough magnitude, the direction of the effect. Then I generate. If the output disagrees with my prediction, exactly one of us is wrong, and finding out which is where the learning happens. Without the prediction there is nothing to be surprised by, and surprise is the mechanism of learning.
Rule 2: ask it to explain, then ask it to attack
My most valuable prompt is not “write this”, it is: “What assumptions does this code make about the data? What would make this analysis wrong?” Assistants are substantially better at critiquing a given analysis than at knowing, unprompted, that your column is leaky. Make the critique an explicit step.
Rule 3: never paste a number you have not sanity-checked
Row counts, null counts, the minimum and maximum of every column, the class balance. Thirty seconds of checking catches most disasters. The 99.93% model would have survived every code review and died instantly against the question “what is this column, and when is it populated?”
Rule 4: it is a tutor that is sometimes confidently wrong
Assistants state incorrect things with exactly the same fluency as correct ones, and the mechanism is structural rather than a bug that will be patched soon — we wrote about why AI confidently makes things up separately. For anything load-bearing, verify against documentation. For statistics in particular, verify against a textbook.
Rule 5: protect one thing a week from automation
Once a week I do a whole small analysis with no assistant at all. It is slower and mildly unpleasant, and it is the only reliable way I have found to know whether a skill is actually mine or whether I have been borrowing it. Treat it as the test, not the lesson.
Rule 6: be careful what you paste
Real datasets contain real people. Customer records, phone numbers, exam results and medical data should not be pasted into a chat window. Work on a sample with identifiers stripped, or generate synthetic data like the lab above. If you build tools on top of assistants later, understand prompt injection before you connect one to anything that matters.
Setting up, free, on a modest laptop
You do not need a powerful machine. Everything in this post, including the lab, runs comfortably on an ordinary laptop with 8 GB of RAM. You will not need a GPU until deep learning, and by then you can rent one by the hour or use a free cloud notebook.
Install Python, then create an isolated environment so that a broken package never breaks everything else:
python3 -m venv ds-venv
source ds-venv/bin/activate # Windows: ds-venv\Scripts\activate
pip install pandas scikit-learn matplotlib seaborn jupyterlab
jupyter labThat is the entire stack for the first six months. If installing locally is a problem, Google Colab gives you a notebook in the browser with these libraries preinstalled and a free GPU allowance, which matters when your electricity or bandwidth is unreliable.
One habit worth more than any tool: start every new dataset with the same five lines — df.shape, df.dtypes, df.isna().sum(), df.describe(), and the class balance of your target. I have caught more problems with those five lines than with every clever technique combined.
Projects that prove something
Most portfolio projects prove nothing, because everyone has done the same three. A Titanic notebook tells a reviewer that you can follow a tutorial. Here is what distinguishes a project that gets read.
- Use data nobody else has. Scrape Nepali job listings, collect load-shedding schedules, pull your own bank statements, parse your college results. Messy local data is more impressive than a clean famous dataset, because cleaning it is the work.
- Answer a question, do not showcase a technique. “Which faculties have the widest pass-rate gap between campuses?” beats “applying XGBoost to a dataset”.
- Write down what went wrong. A README that says “my first model scored 0.99 and here is the leak I found” is far stronger evidence of competence than one that reports only a good number. Reviewers who know the field will trust you more for it.
- State the limitation yourself. Sample too small, data from one year only, selection bias in how it was collected. Naming it first shows you understand it.
- Three finished projects beat twelve abandoned ones. Finished means written up and reproducible by a stranger.
Beginner mistakes that cost the most time
| Mistake | What it costs | The fix |
|---|---|---|
| Collecting courses instead of finishing one | Months, and confidence | One course, finished, with every exercise done |
| Jumping to deep learning in month two | You learn to call APIs, not to think | Linear and logistic regression until you can explain every coefficient |
| Reporting accuracy on imbalanced data | Credibility, instantly, in any interview | Always quote the base rate next to the score |
| Letting AI write code you cannot read | A portfolio you cannot defend | Rule 1 and Rule 5 above |
| Skipping statistics “for now” | Every trap in this article | Stage 3, at full length |
| Tuning the model before understanding the data | Weeks spent gaining 0.3% | Better features and cleaner labels beat better algorithms |
| Never finishing anything publicly | No evidence you can be hired on | Ship three small things rather than plan one large one |
Doing this from Nepal
Most advice on data science for beginners assumes a context that is not ours. A few things are specific to studying in Nepal, and they are rarely written down.
Your degree is not the obstacle you think it is. BCA, BSc CSIT and BIT all give you more than enough mathematics to start. Nobody reviewing a portfolio asks which campus you attended; they look at whether your analysis holds up.
Paid courses are mostly unnecessary. The expensive bootcamps advertised locally teach the material that is already free and well taught. Spend money on exam fees and a reliable internet connection before spending it on another video course.
Remote work is the realistic first destination. The domestic data science market is small and most listings want experience. Freelance data cleaning and analysis work is a genuine entry point, and it pays in currency that goes further here. A public portfolio matters far more for this route than a degree certificate does.
Local data is your advantage. Every applicant from a big market is analysing the same public datasets. Almost nobody is analysing Nepali government open data, local e-commerce pricing or transport patterns. Being the person with the unusual dataset is worth more than being the person with the slightly better model.
Frequently asked questions
Is it too late to start learning data science in 2026?
No, but the target has moved. The job of producing standard models from clean data is being automated. The job of deciding what to measure, noticing when a result is wrong, and translating a messy business question into something answerable is not, and there is no sign of it being so. Learn for the second job.
How much mathematics do I really need?
Less than the gatekeepers claim, more than the bootcamp advertisements claim. For the first year: solid statistics and probability, comfort with linear algebra notation (vectors, matrices, dot products), and the idea of a derivative as a slope. You do not need to compute integrals by hand. You do need to know why dividing by a near-zero number is a problem.
Should I learn Python or R?
Python. R is excellent for statistics and still strong in academia, but Python has the larger job market, the better engineering ecosystem, and far more learning material. Learn R later if a specific role asks for it.
Do I need a master’s degree?
For most industry data roles, no. For research positions and some international visa routes, it helps considerably. A portfolio of finished, honest work is the cheaper and faster path into industry.
Is using AI to learn cheating?
Not inherently. Using it to produce work you cannot explain is self-harm rather than cheating, because the person it misleads most is you. The test is simple: could you defend every line in an interview with no help? If not, you have a portfolio piece that will fail at exactly the wrong moment.
Why did the honest model have the same accuracy as doing nothing?
Because only 6.64% of customers churned, and at the default 0.5 threshold the model almost never predicted churn, so it agreed with the do-nothing baseline on nearly every row. Its AUC of 0.70 shows the signal was there all along. Accuracy simply could not see it. This is the single most common way beginners discard a useful model.
How long until I can get a job?
Honestly: longer than the advertisements say. Seven to nine months of consistent study gets you to junior competence on the roadmap above. Getting hired then depends on evidence and luck. Anyone promising a job in twelve weeks is selling something.
Reproduce the lab yourself
Save this as lab-churn-leakage.py and run it. It needs only pandas, scikit-learn and numpy, it is seeded, and it prints the exact numbers quoted in Tables 1 to 3. Change the seed and watch which conclusions survive — that is the real exercise.
#!/usr/bin/env python3
"""
Three ways a beginner (or an AI assistant with no context) gets a great-looking
churn model that is worthless. Deterministic: same numbers every run.
python3 lab-churn-leakage.py
"""
import numpy as np, pandas as pd, json
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.metrics import (accuracy_score, roc_auc_score, precision_score,
recall_score, confusion_matrix)
RNG = np.random.default_rng(42)
N = 5000
def build_data(n=N):
"""A small telecom-style churn table. Churn is ~8% of customers."""
tenure = RNG.integers(1, 72, n) # months as a customer
monthly = RNG.normal(65, 20, n).clip(15, 130) # monthly bill
support = RNG.poisson(1.2, n) # support tickets
# Real signal: short tenure + high bill + many tickets -> more likely to churn
logit = (-3.4 - 0.030*tenure + 0.016*monthly + 0.42*support)
p = 1/(1+np.exp(-logit))
churn = RNG.binomial(1, p)
# THE LEAK: this column is only ever filled in *after* a customer churns.
# In a real warehouse it is the exit-survey score. It is not available at
# prediction time, but nothing in the data says so.
exit_survey = np.where(churn == 1, RNG.normal(2.1, 0.8, n), np.nan)
exit_survey = np.nan_to_num(exit_survey, nan=0.0)
return pd.DataFrame({
"tenure_months": tenure, "monthly_charges": monthly.round(2),
"support_tickets": support, "exit_survey_score": exit_survey.round(2),
"churned": churn,
})
def evaluate(name, model, Xtr, Xte, ytr, yte):
model.fit(Xtr, ytr)
pred = model.predict(Xte)
proba = model.predict_proba(Xte)[:, 1]
r = {
"model": name,
"accuracy": round(accuracy_score(yte, pred), 4),
"roc_auc": round(roc_auc_score(yte, proba), 4),
"precision": round(precision_score(yte, pred, zero_division=0), 4),
"recall": round(recall_score(yte, pred, zero_division=0), 4),
}
tn, fp, fn, tp = confusion_matrix(yte, pred).ravel()
r["confusion"] = {"tn": int(tn), "fp": int(fp), "fn": int(fn), "tp": int(tp)}
return r
def main():
df = build_data()
rate = df.churned.mean()
out = {"rows": len(df), "churn_rate": round(float(rate), 4), "results": []}
honest_cols = ["tenure_months", "monthly_charges", "support_tickets"]
leaky_cols = honest_cols + ["exit_survey_score"]
y = df.churned
# ---- Trap 0: the baseline nobody computes -------------------------------
# Predict "nobody churns" for every single customer.
_, yte0 = train_test_split(y, test_size=0.3, random_state=0, stratify=y)
out["results"].append({
"model": "Baseline: always predict 'no churn'",
"accuracy": round(float((yte0 == 0).mean()), 4),
"roc_auc": 0.5, "precision": 0.0, "recall": 0.0,
"confusion": {"tn": int((yte0 == 0).sum()), "fp": 0,
"fn": int((yte0 == 1).sum()), "tp": 0},
})
# ---- Trap 1: target leakage --------------------------------------------
Xtr, Xte, ytr, yte = train_test_split(df[leaky_cols], y, test_size=0.3,
random_state=0, stratify=y)
out["results"].append(evaluate(
"With leaked column (exit_survey_score)",
make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)),
Xtr, Xte, ytr, yte))
# ---- The honest model ---------------------------------------------------
Xtr, Xte, ytr, yte = train_test_split(df[honest_cols], y, test_size=0.3,
random_state=0, stratify=y)
out["results"].append(evaluate(
"Honest features only",
make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)),
Xtr, Xte, ytr, yte))
# ---- Trap 2: scaling before the split (preprocessing leakage) ----------
# Wrong: the scaler sees the test set's mean and standard deviation.
scaled_all = StandardScaler().fit_transform(df[honest_cols])
Xtr_w, Xte_w, ytr_w, yte_w = train_test_split(scaled_all, y, test_size=0.3,
random_state=0, stratify=y)
wrong = LogisticRegression(max_iter=1000).fit(Xtr_w, ytr_w)
wrong_auc = roc_auc_score(yte_w, wrong.predict_proba(Xte_w)[:, 1])
# Right: the scaler is fitted inside the pipeline, on training data only.
right = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
right_cv = cross_val_score(right, df[honest_cols], y, cv=5, scoring="roc_auc")
out["preprocessing"] = {
"scaled_before_split_auc": round(float(wrong_auc), 4),
"pipeline_cv_auc_mean": round(float(right_cv.mean()), 4),
"pipeline_cv_auc_std": round(float(right_cv.std()), 4),
}
# ---- Trap 3: the default 0.5 threshold ---------------------------------
# The honest model is not useless - it is being read wrongly. Rank every
# customer by risk and contact the riskiest slice instead.
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
pipe.fit(Xtr, ytr)
risk = pipe.predict_proba(Xte)[:, 1]
sweep = []
for pct in (5, 10, 20, 30):
k = int(len(risk) * pct / 100)
idx = np.argsort(risk)[::-1][:k]
caught = int(yte.iloc[idx].sum())
total = int(yte.sum())
sweep.append({
"contact_top_pct": pct, "customers_contacted": k,
"churners_caught": caught, "of_total_churners": total,
"recall": round(caught / total, 4),
"precision": round(caught / k, 4),
})
out["threshold_sweep"] = sweep
print(json.dumps(out, indent=2))
with open("results-churn.json", "w") as f:
json.dump(out, f, indent=2)
if __name__ == "__main__":
main()
Expected output on first run: churn rate 0.0664, the leaked model at accuracy 0.9993 and ROC AUC 1.0, the honest model at accuracy 0.9333 and ROC AUC 0.7005, and a threshold sweep matching Table 3.
If you remember one thing
The assistant wrote correct code three times and handed me a wrong answer three times. Not because it is bad at writing code — it is better at that than I am — but because every one of those mistakes required knowing something that was not in the data: what a column means, what a transformer learns, what decision the number is feeding.
That is what learning data science in the age of AI actually means in practice, and it is why I am still grinding the fundamentals in an era where the code writes itself. Not out of nostalgia, and not because I enjoy statistics textbooks. It is because the fundamentals are now the only part of the job that is mine. Everything else, I can generate in nine seconds.
Start with Stage 1. Type it by hand. Run the lab and break it on purpose. That is the whole method.
References and free resources
- Think Stats, Allen B. Downey — free, Python-based, the best statistics starting point for programmers.
- Python for Data Analysis, Wes McKinney — written by the author of pandas.
- An Introduction to Statistical Learning — free PDF, the standard first machine learning text.
- Kaggle Learn — short free courses with exercises in the browser.
- scikit-learn user guide, especially the sections on cross-validation and model evaluation.
- Google Colab — free notebooks with libraries preinstalled, useful on a slow connection.
Related reading on CSSNepal
- Build a Mini Python Expense Tracker CLI — the Stage 1 Python subset, as one buildable project.
- Database Management System Explained — the model underneath every SQL query you will write.
- NoSQL Databases and the CAP Theorem — where data actually lives at scale.
- System Design for Beginners — the companion guide, same measured-lab format.
- The Mathematics of Attention — derived step by step, for when Stage 5 makes you curious.
- TinyML: Machine Learning Under a Memory Constraint — machine learning where every byte counts.
- Why AI Confidently Makes Things Up — essential background for Rule 4.
- Prompt Injection: The AI Security Flaw That Cannot Be Patched — before you build on top of an assistant.
