TeleNova sells three mobile plans: Basic, Data Pro and Talk Max. New customers often pick the wrong one, get a big bill, and leave.
The marketing team has 240 customers who are happy with their plan, with their age and monthly usage. For a new customer, they want to say: "people who use the phone like you chose this plan".
Goal: Recommend a plan (one of three categories) for a new customer by looking at the most similar existing customers. That is exactly what K-Nearest Neighbours does.
240 customers, one row each.
| customer_id | age | data_gb_month | call_minutes_month | plan |
|---|---|---|---|---|
| 3001 | 28 | 6 | 640 | Basic |
| 3002 | 20 | 22 | 700 | Data Pro |
| 3003 | 47 | 15 | 1000 | Data Pro |
| 3004 | 49 | 3 | 370 | Basic |
| 3005 | 22 | 9 | 780 | Data Pro |
| 3006 | 52 | 7 | 1360 | Talk Max |
First 6 of 240 rows · realistic practice data
Press Run on each step in order, or run them all at once. You can change any code and run it again.
Starting Python…
Three plans, three classes. Check how many customers are on each plan and what typical usage looks like.
Plot data against calls. Each plan sits in its own area of the chart. KNN uses this: a new customer probably wants the same plan as the customers closest to them on this chart.
Keep 25% of customers for the test. stratify keeps the mix of plans the same in both parts.
KNN measures distance. Call minutes go up to about 2,000 while data stays below 60 GB, so a difference of 50 minutes counts more than a difference of 40 GB. The model ends up looking almost only at calls. Let's see the score.
StandardScaler puts every column on the same scale, so age, data and calls all count. A pipeline joins the two steps, so the scaler is always applied the same way, in training and in prediction.
K is the number of neighbours that vote. A very small K follows every odd customer (overfitting); a very big K ignores the groups. Cross-validation tests each K on 5 different splits of the training data and averages the score, so the choice does not depend on one lucky split.
Train with the best K and test on the hidden customers. The confusion matrix shows which plans get mixed up. Mix-ups usually happen at the edges, where a customer uses a bit of everything.
A 24-year-old uses 35 GB of data and 300 call minutes a month. The model finds the closest customers and lets them vote. Showing those neighbours is a simple way to explain the recommendation. Change the numbers and run again.
20 questions on new data. You write the code; hints point the way without giving it.