Quick answer
Scikit-learn is the standard Python library for classical machine learning: you give it a table of features and a target column, pick a model, and it handles training and prediction in a few lines. This post trains a logistic regression classifier on twenty fictional telecom customers to predict churn, and reads the result honestly.
A small telecom team keeps a spreadsheet of customers: tenure, monthly charge, and contract type. Every month a few customers leave, noticed only when the bill stops. Someone suggests guessing who will leave next from the pattern in the rows they already have. That is the moment scikit-learn earns its place. Nobody there wants to write a gradient descent routine from scratch. The library turns that spreadsheet into a trained model in about ten lines, and the interesting work is around those lines: preparing the data, splitting it fairly, and reading the score without fooling yourself.
What I would check before using it
My first check is whether the data fits in a table. Scikit-learn expects rows and columns: numbers, categories, and one target column to predict. The churn example below is exactly that shape. If the input is raw text, images, or audio, the main model probably belongs to a deep learning framework; the PyTorch post shows that side.
My second check is which kind of answer I need. Scikit-learn covers classification, regression, and clustering, plus scaling, encoding, splitting, and scoring. If I need a probability that a customer leaves, logistic regression gives me one directly. If I need to group customers with no labels at all, that is clustering, a different tool in the same library.
My third check is size and explainability. Scikit-learn loads data into memory and trains on one machine, which handles hundreds of thousands of rows, but not a dataset that needs a GPU or a cluster. A logistic regression model has coefficients you can read: longer tenure pushes the churn probability down, a month-to-month contract pushes it up.
My verdict, as judgement: adopt scikit-learn when the data is tabular, the model is a classifier or regressor, the data fits in memory, and the decision may need explaining. The recommendation flips the moment the input stops being a table, the data outgrows one machine, or the problem genuinely needs deep learning. Start with the simplest model that works.
Twenty customers, one churn model
The example is a fictional telecom company with twenty customers. Each row holds tenure in months, monthly charge in dollars, contract type, and whether the customer churned. Short tenure, high charge, and a month-to-month contract point toward leaving. The data is small and invented, so the result needs honest reading. The rows are plain Python lists, as in the Python List Comprehensions post, loaded into a table with Pandas.
"""Churn classifier demo for The Practical Developer (scikit-learn). A small fictional telecom company wants to spot customers who are likely to leave. The data is 20 invented customer rows: tenure in months, monthly charge in dollars, contract type, and whether the customer churned. The script trains a logistic regression model on scaled features, prints accuracy and a classification report, then deliberately passes a single customer as a flat 1-D list to predict, which scikit-learn rejects, and shows the fix. """ import numpy as np import pandas as pd from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score, classification_report, confusion_matrix from sklearn.model_selection import train_test_split from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler DATA = [ # tenure_months, monthly_charge, contract, churned (2, 70, "month-to-month", 1), (3, 65, "month-to-month", 1), (1, 80, "month-to-month", 1), (5, 72, "month-to-month", 1), (4, 68, "month-to-month", 1), (24, 45, "one-year", 0), (36, 40, "two-year", 0), (30, 50, "one-year", 0), (48, 38, "two-year", 0), (12, 55, "one-year", 0), (6, 75, "month-to-month", 1), (18, 48, "one-year", 0), (60, 35, "two-year", 0), (8, 70, "month-to-month", 1), (42, 42, "two-year", 0), (10, 60, "month-to-month", 0), (15, 58, "one-year", 0), (2, 85, "month-to-month", 1), (28, 46, "one-year", 0), (9, 66, "month-to-month", 1), ] df = pd.DataFrame(DATA, columns=["tenure", "charge", "contract", "churned"]) df = pd.get_dummies(df, columns=["contract"], dtype=float) print("Rows:", len(df), "| churned:", int(df["churned"].sum())) X = df.drop(columns=["churned"]) y = df["churned"] X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.25, random_state=42, stratify=y ) print("Train rows:", len(X_train), "| Test rows:", len(X_test)) model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)) model.fit(X_train, y_train) pred = model.predict(X_test) print("Accuracy:", round(accuracy_score(y_test, pred), 3)) print("Confusion matrix (rows actual, cols predicted):") print(confusion_matrix(y_test, pred)) print(classification_report(y_test, pred, zero_division=0)) Real output from the run:
Rows: 20 | churned: 9 Train rows: 15 | Test rows: 5 Accuracy: 1.0 Confusion matrix (rows actual, cols predicted): [[3 0] [0 2]] precision recall f1-score support 0 1.00 1.00 1.00 3 1 1.00 1.00 1.00 2 accuracy 1.00 5 macro avg 1.00 1.00 1.00 5 weighted avg 1.00 1.00 1.00 5 Accuracy 1.0 looks like a triumph until you read the support column: the test set has five rows. Five correct guesses on five rows proves the wiring works and nothing more. A real churn model would need hundreds of rows, and a score that holds up on a later sample. The confusion matrix is worth keeping: three who stayed were predicted to stay, two who left were predicted to leave.
The thing that went wrong came next: the model was asked about one new customer, six months in, paying $74, on a month-to-month contract. Passed as a flat list, scikit-learn refused:
print("Step 2: predict one new customer, the wrong way first") new_customer = [6, 74, 1.0, 0.0, 0.0] # 6 months, $74, month-to-month try: print(model.predict(new_customer)) except ValueError as exc: print("ValueError:", exc) Step 2: predict one new customer, the wrong way first ValueError: Expected 2D array, got 1D array instead: array=[ 6. 74. 1. 0. 0.]. Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample. Scikit-learn always expects a table, even for one row. A flat list looks like five samples with one feature each, so the library stops rather than guessing. The fix is a one-row table with the same column names:
print() print("Step 3: the same customer, as a 2-D row with feature names") new_row = pd.DataFrame([new_customer], columns=X.columns) print("Prediction:", model.predict(new_row)[0], "(1 means likely to churn)") Step 3: the same customer, as a 2-D row with feature names Prediction: 1 (1 means likely to churn) The model flags the new customer as likely to churn, which matches the pattern: short tenure, high charge, no long contract. The scaler was fitted inside the pipeline, on the training rows only. The NumPy post explains the arrays underneath, and a chart follows the Matplotlib post.
Common mistakes and how to fix them
First, scaling the whole dataset before splitting it. The symptom is a test score that looks too good, because the scaler has already seen the test rows' means and spreads. The fix is to fit the scaler on the training data only, which a pipeline does automatically.
Second, passing a single sample as a flat list to predict. The symptom is ValueError: Expected 2D array, got 1D array instead. The fix is to wrap the row in another list, or pass a one-row DataFrame with the training column names.
Third, leaving text columns in the feature table. The symptom is ValueError: could not convert string to float, because the model only accepts numbers. The fix is to encode categories first, with get_dummies as the demo does, or OneHotEncoder inside a pipeline.
Fourth, trusting accuracy on lopsided data. The symptom is a model that scores 95 percent while missing every churner, because the 95 percent who stay carry the average. The fix is to read the classification report and the confusion matrix, and check recall for the rare class before quoting any single number.
Frequently Asked Questions
Do I need a GPU to use scikit-learn? No. Scikit-learn runs on an ordinary CPU and is designed for tabular data, not for the matrix workloads that need a GPU. The churn demo trains in under a second.
How is scikit-learn different from PyTorch or TensorFlow? Scikit-learn covers classical models on tables: logistic regression, trees, forests, clustering. PyTorch and TensorFlow cover deep learning on text, images, and audio, where the model learns its own features.
How much data do I need before a model means anything? More than twenty rows. A handful of rows can prove the code runs, but a score on five test rows says almost nothing about new customers. Collect hundreds of rows first.
Can a scikit-learn model go into production? Yes, for the right job. A fitted pipeline can be saved with joblib and loaded by a small service that takes a customer row and returns a prediction. Keep the training code and the serving code using the same pipeline.
What to remember
- Scikit-learn expects a table: rows are samples, columns are features, and even one prediction needs a 2-D row.
- Split first, then scale, so the test set stays unseen.
- Encode categories into numbers before training, or the model will refuse the text.
- Read the confusion matrix, not just the accuracy.
- A perfect score on five test rows proves the wiring, not the model.
Where this leaves you
You now have a churn classifier that trains on real rows, reports its score honestly, and fails loudly when handed a single customer the wrong way. That is the whole skill: prepare a table, split it fairly, pick a simple model, and read the report instead of the headline number. The next step is your own data, a spreadsheet you already have, with one column you want to predict. Load it, split it, train a logistic regression, and check the confusion matrix before you believe anything. If the matrix is clean on a decent test set, you have a model worth showing someone.
Further reading
- Scikit-learn, Getting started, https://scikit-learn.org/stable/getting_started.html
- Scikit-learn, User guide: supervised learning, https://scikit-learn.org/stable/supervised_learning.html
- Scikit-learn, LogisticRegression documentation, https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html
- Pandas Explained: Tables in Python, Without the Spreadsheet, https://practicaldevblog.blogspot.com/2026/11/pandas-explained-tables-in-python.html
- PyTorch Explained: Machine Learning You Can Watch Learn, https://practicaldevblog.blogspot.com/2026/11/pytorch-explained-machine-learning-you.html
- NumPy: Fast Arrays in Python Without the Loops, https://practicaldevblog.blogspot.com/2026/11/numpy-fast-arrays-in-python-without.html
- Matplotlib: Charts in Python Without Opening a Spreadsheet, https://practicaldevblog.blogspot.com/2026/11/matplotlib-charts-in-python-without.html
- Python List Comprehensions Explained With Real Examples, https://practicaldevblog.blogspot.com/2026/10/python-list-comprehensions-explained.html
Waqas Shahid is a software engineer from Karachi with more than 12 years of experience, including 6+ years in engineering leadership. He writes The Practical Developer.

