Foundations

A First End-to-End Model on Tabular Data, Step by Step

Build a complete churn model in Python, from inspecting a table through leak-free preprocessing, cross-validation and one final test.

Key takeaways

  • Look at shape, missing values, the target rate and a few group summaries before fitting anything.
  • Set the test set aside early and leave it alone until your choices are final.
  • Put imputation, scaling and encoding inside a pipeline so they are fitted on training folds only.
  • Always run a baseline and at least one simple model before reaching for something complex.
  • Pick a decision threshold from development data and the real cost of each action.

To build a first model on a table, work in this order: inspect the data, set aside a test set, put preprocessing and model into one pipeline, compare it with a baseline using cross-validation, choose settings, and score the test set once. This walkthrough does each step in Python with pandas and scikit-learn.

The data is synthetic, so you can run everything without downloading a file. It imitates a subscription business that wants to know which customers will cancel. Tabular data means rows of examples and columns of features.

The route from table to test score

Each step feeds the next, and the test rows stay untouched until the end.

From raw table to one honest test score
1 Inspect Shape, gaps, target rate, group summaries. 2 Hold out Lock away a test set. 3 Pipeline Impute, scale, encode, then model. 4 Cross-validate Compare with a baseline on development data. 5 Set threshold Match action costs using out-of-fold scores. 6 Test once Report, check slices, save. Inspect Shape, gaps, target rate, group summaries. 1 Hold out Lock away a test set. 2 Pipeline Impute, scale, encode, then model. 3 Cross-validate Compare with a baseline on development data. 4 Set threshold Match action costs using out-of-fold scores. 5 Test once Report, check slices, save. 6

Step 1: Create and inspect the table

The generator below makes 4,000 customers. Churn becomes less likely with longer membership and more likely with support tickets, higher fees and the basic plan. About 10 percent of fees are then removed to imitate missing data.

import numpy as np
import pandas as pd

rng = np.random.default_rng(0)
n = 4000
df = pd.DataFrame({
    "months": rng.integers(1, 61, n).astype(float),
    "tickets": rng.poisson(1.0, n).astype(float),
    "monthly_fee": rng.normal(50, 12, n),
    "plan": rng.choice(["basic", "plus", "pro"], n),
})
logit = (-1.0 - 0.04 * df.months + 0.6 * df.tickets
         + 0.03 * (df.monthly_fee - 50) + 0.8 * (df.plan == "basic"))
df["churned"] = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
df.loc[rng.random(n) < 0.1, "monthly_fee"] = np.nan

print(df.shape)                      # (4000, 5)
print(df.isna().mean().round(3))     # share missing per column
print(df.churned.mean().round(3))    # target rate
print(df.groupby("plan").churned.mean().round(3))

In one run, about 23 percent of customers churned, about 10 percent of fees were missing, and basic customers churned at roughly 32 percent against 19 for the others. Your digits may differ slightly with other library versions.

With real data, ask more: when was each column filled in? Would you know it on the day you predict? A column such as "cancellation reason" would give the answer away. See target leakage.

Step 2: Hold out a test set

from sklearn.model_selection import train_test_split

X, y = df.drop(columns="churned"), df["churned"]
X_dev, X_test, y_dev, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=0)

X_dev has 3,200 rows and X_test has 800. Stratifying keeps the churn rate similar in both. The development set is everything you are allowed to learn from and experiment with.

A random split suits this invented data. For real churn, where you predict next month from the past, a split by date is usually more honest.

Step 3: Describe the preprocessing

from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

numeric = ["months", "tickets", "monthly_fee"]
prep = ColumnTransformer([
    ("num", make_pipeline(
        SimpleImputer(strategy="median", add_indicator=True),
        StandardScaler()), numeric),
    ("cat", OneHotEncoder(handle_unknown="ignore"), ["plan"]),
])

Imputation fills gaps, here with the median, and the added indicator column records that a value was missing. Scaling puts numbers on comparable ranges. One-hot encoding turns the plan name into one 0 or 1 column per plan, and an unknown plan becomes all zeros instead of crashing.

Nothing has been computed yet. These steps will learn their medians and means each time the pipeline is fitted, using only the rows given to it. That is the reason for pipelines.

Step 4: Compare with cross-validation

Cross-validation splits the development set into five parts, trains on four, scores on the fifth, and rotates.

from sklearn.dummy import DummyClassifier
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_validate

models = {
    "baseline": make_pipeline(prep, DummyClassifier(strategy="prior")),
    "logistic": make_pipeline(prep, LogisticRegression()),
    "boosting": make_pipeline(
        prep, HistGradientBoostingClassifier(random_state=0)),
}
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
for name, m in models.items():
    s = cross_validate(m, X_dev, y_dev, cv=cv,
                       scoring=["neg_log_loss", "roc_auc"])
    print(name, round(-s["test_neg_log_loss"].mean(), 3),
          round(s["test_roc_auc"].mean(), 3))
Model Log loss (lower is better) ROC AUC
Baseline about 0.54 0.50
Logistic regression about 0.46 about 0.76
Boosted trees, defaults about 0.52 about 0.70

Log loss scores the probabilities. ROC AUC is the chance that a random churner is scored above a random non-churner.

Step 5: Interpret before tuning

The simple model wins. That is expected here, because the data was generated from a formula that is linear on the log-odds scale, which is exactly what logistic regression assumes. Default boosted trees have far more freedom and fit some of the noise in only a few thousand rows.

On your own data the order may reverse. Boosted trees often do well on tables with interactions and thresholds. You could tune them with a smaller learning rate, shallower trees or early stopping, using a search over settings on the development set. The lesson is to compare, and not to assume that the more elaborate method is better.

Look inside the winner

A linear model can be read, within limits. After fitting on the development set, list the feature names from the preprocessing step beside the coefficients.

fitted = models["logistic"].fit(X_dev, y_dev)
names = fitted[:-1].get_feature_names_out()
for name, w in zip(names, fitted[-1].coef_[0]):
    print(name, round(w, 2))

Expect a negative weight on months and positive weights on tickets, fee and the basic plan, matching the formula that made the data. Because numeric columns were standardized, each of their weights is the change in log-odds for a one standard deviation increase. The missing-fee indicator should be near zero, since fees were removed completely at random.

On real data you do not know the true formula. A surprising sign or an enormous weight is a prompt to investigate: correlated columns, a coding error or leakage. Even sensible weights describe associations in this dataset. They do not show that reducing a customer's ticket count would keep that customer.

Step 6: Choose a threshold

A probability becomes an action through a threshold. Get out-of-fold predictions, so each row is scored by a model that did not train on it.

from sklearn.model_selection import cross_val_predict

q = cross_val_predict(models["logistic"], X_dev, y_dev, cv=cv,
                      method="predict_proba")[:, 1]
for t in (0.2, 0.3, 0.5):
    flag = q >= t
    precision = y_dev[flag].mean()
    recall = y_dev[flag].sum() / y_dev.sum()
    print(t, flag.sum(), round(precision, 2), round(recall, 2))
Threshold Customers flagged Precision Recall
0.2 about 1,470 about 0.38 about 0.74
0.3 about 910 about 0.46 about 0.56
0.5 about 300 about 0.63 about 0.26

Precision is the share of flagged customers who churn. Recall is the share of churners you flagged. If a retention offer is cheap, a low threshold makes sense. If each contact is costly, raise it.

Step 7: Test once

from sklearn.metrics import log_loss, roc_auc_score

final = models["logistic"].fit(X_dev, y_dev)
p = final.predict_proba(X_test)[:, 1]
print(log_loss(y_test, p), roc_auc_score(y_test, p))

The run gave log loss about 0.47 and AUC about 0.74, close to the cross-validation estimates. With only 800 test rows, differences of a few hundredths in AUC are well within noise. If the test result had been much worse, you would look for leakage or a split problem, and any further tuning would need fresh test data to be reported honestly.

Step 8: Check slices and save

Compare the average predicted probability with the observed churn rate for each plan, and look at the metric per plan. Small groups give noisy numbers, so read them with care. Then save the whole fitted pipeline, together with library versions and the data description.

Python's joblib and pickle formats can execute code when loaded, so load only files you trust. Saving scikit-learn models covers the alternatives.

Common mistakes in a first project

Mistake Why it hurts Fix
Filling gaps before splitting Test rows influence the medians Impute inside the pipeline
Tuning until the test score looks good The test set stops being independent Tune with cross-validation only
Keeping an ID column as a feature The model may memorize rows or ordering Drop identifiers
Reporting accuracy alone A 23 percent target rate lets "nobody churns" score 77 percent Report log loss, AUC, precision and recall
Editing a notebook out of order Results cannot be reproduced Restart and run top to bottom

Run the whole script from a fresh session before you share a number. Hidden state in a notebook, such as a variable left over from a deleted cell, is a frequent reason a result cannot be repeated. Moving the finished steps into a plain script or module also makes it easier for someone else to review them.

Where to go next

Replace the synthetic table with a dataset you are licensed to use, and repeat every step. Expect messier columns, subtler leakage and a disappointing first score. Then plot a learning curve and read your errors to decide whether to gather data, build features or change models. This exercise is teaching material; a model that affects real people needs far more validation and review.

Written for 4MachineLearning with AI writing tools and not reviewed line by line by a person. Check anything you rely on against a textbook or primary source. Report an error.

Keep reading

All 42 articles in Foundations →

Latest news on this topic