EN VI

Your First Machine Learning Model With scikit-learn (and Why Accuracy Lies)

By ··9 min read

Short answer

To train a first model in scikit-learn, split the data into a train set and a test set, fit the model on the train set, and score it on the test set. Do not trust accuracy alone when one outcome is rare. In the example below, the model scores 94.6% accuracy and finds none of the customers who leave, so recall and the confusion matrix matter more.

In the last post we said that a model must be tested on rows it has not seen. Now we do it in code. On a customer table with a few thousand rows, a churn model has a hard job because most customers stay. That makes it a good first example, since the first number that we see can look excellent and still be wrong. All code below uses scikit-learn with fixed random seeds, so you can run it and get the same numbers.

Step 1: split the data first

To check a model honestly, we hold back part of the rows. We call the part used for learning the train set, and the held-back part the test set. The test set plays the role of next month's customers. If we scored the model on the same rows it learned from, the result would look better than real use, because the model has already seen the answers.

Step 2: train and score, and the trap

Here we train a logistic regression on 1,500 rows and score it on 500. In the test set, 27 of the 500 customers leave, which is the part we care about.

from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, recall_score

# 2,000 customers, about 5% of them churn
X, y = make_classification(n_samples=2000, n_features=8, n_informative=4,
                           weights=[0.95, 0.05], random_state=42)

# stratify keeps the same churn rate in train and test
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, stratify=y, random_state=42)

model = LogisticRegression(max_iter=1000).fit(X_train, y_train)
pred = model.predict(X_test)

# WRONG: accuracy alone looks excellent
print(round(accuracy_score(y_test, pred), 3))   # 0.946
print(recall_score(y_test, pred))               # 0.0

This is a class imbalance problem. When one outcome is rare, a model can score high accuracy by always predicting the common outcome. For this reason, we compare any model with that plain baseline first, and we look at metrics that focus on the rare group.

Step 3: read the confusion matrix

  • Recall asks how many of the customers who really leave the model found.
  • Precision asks how many of the customers the model flags really leave.
  • The confusion matrix holds the four counts behind both numbers.

To make the model look for the rare group, we tell it to give that group more weight with class_weight="balanced". The code below reuses the same split from step 2.

from sklearn.metrics import confusion_matrix, precision_score, recall_score

model = LogisticRegression(max_iter=1000, class_weight="balanced").fit(X_train, y_train)
pred = model.predict(X_test)

print(confusion_matrix(y_test, pred))            # [[305 168]
                                                 #  [  8  19]]
print(round(recall_score(y_test, pred), 3))      # 0.704
print(round(precision_score(y_test, pred), 3))   # 0.102

Now the model finds 19 of the 27 customers who leave, which is a recall of 0.704. The price is precision. Only about 10% of the customers that it flags really leave, since 168 customers who stay get flagged as well. Overall accuracy falls to 0.648, and that is fine, because accuracy was never the goal here.

Which trade-off is right?

Finding more churners saves more customers, but it also means calling more people who would have stayed anyway. The right balance depends on what a call costs and what a lost customer is worth. That is a business decision, so we agree on it with the team before we tune the model.

A checklist for every first model

  1. Split the data before you look at any score.
  2. Score a plain baseline, such as predicting the common outcome for everyone.
  3. Look at recall, precision and the confusion matrix, not accuracy alone.
  4. Write down the cost of a wrong flag and of a missed customer.

Frequently asked questions

Why is my model accuracy high but the model is useless?

When one outcome is rare, always predicting the common outcome already gives high accuracy. Check recall, precision and the confusion matrix for the rare group.

What is a train test split?

It divides the rows into one part for learning and one part held back for scoring. The held-back part shows how the model behaves on rows it has not seen.

What is the difference between precision and recall?

Recall is the share of real positives that the model finds. Precision is the share of flagged rows that are really positive. Raising one often lowers the other.

References

Keep learning, step by step.

Each lesson in Learn has a business context, a runnable example and a result check, so you practise this habit on real questions.