Using Transformers to Predict Customer Churn from Sequential Data
A practical Python tutorial on real-world behavioural features, temporal embeddings, churn modelling and enterprise retention architecture.
On this page
Key takeaways
Define the decision before the model. Prediction timestamp, observation window, churn definition and intended intervention must align.
Build trustworthy customer-month features. Event-time cutoffs, availability and missingness matter as much as model choice.
Understand the input tensor. Each of six monthly tokens contains five behavioural features; projection and position embeddings make them suitable for attention.
Use an encoder for this classification task. All observed months are available at prediction time; a generative decoder is unnecessary.
Compare against strong baselines. A synthetic improvement is not evidence of superiority in a live business environment.
Connect predictions to accountable action. Eligibility, consent, campaign execution, monitoring and experiments determine real-world value.
Introduction
Customer churn prediction is a familiar supervised-learning problem: given what an organisation knows about a customer at a particular date, estimate whether that customer will discontinue a service over a defined future period. In telecommunications, the outcome might be voluntary cancellation within the next 30 days. The result can help a retention team decide where to investigate and whom to contact, subject to business rules and customer preferences.
A conventional model often uses a snapshot: customer tenure, current plan, average monthly usage, number of complaints and outstanding payments. Those features can work well, especially with gradient-boosted trees. But two customers with the same six-month average usage can have opposite trajectories. One may be gradually disengaging while the other is becoming more active. The average alone conceals that difference.
We can engineer trend features for a conventional model, or we can preserve the six monthly observations and let a sequential model learn patterns across them. This tutorial follows the second approach using an encoder-only Transformer. It explains the underlying feature engineering and tensor transformations, implements the model in PyTorch, compares it with gradient boosting, and shows where the model fits in a real retention operation.
The example uses synthetic data. Its purpose is to demonstrate a reproducible workflow, not to claim that Transformers are universally superior or that the generated patterns represent actual telecom subscribers.
1. Define the decision, prediction date and label
Suppose a telecom provider wants to prioritise active customers for a monthly retention review. The model is scored on the first day of each month using the six completed months immediately before that date. Its label is 1 when a customer voluntarily cancels within the following 30 days and 0 otherwise. Customers who are not active at the prediction date should not enter the population being scored.
| Design choice | Tutorial definition |
|---|---|
| Prediction timestamp | Beginning of a calendar month |
| Observation window | Six preceding completed months |
| Prediction horizon | Following 30 days |
| Outcome | Voluntary churn: 1 or 0 |
| Intended use | Prioritise eligible customers for retention review |
This definition must be agreed with the business. Involuntary disconnection, prepaid inactivity and contract cancellation may need different labels. It is also essential to distinguish when an event happened from when the organisation first knew about it. A complaint recorded after the prediction timestamp cannot be retroactively included in that historical prediction, even if its effective date refers to an earlier period.
2. Identify the real-world features and their source systems
Telecom data is distributed across CRM, billing, usage, service-management and network platforms. A model's reliability begins with consistent customer identity, feature definitions and point-in-time availability, not with the choice of neural network.
| Source | Typical records | Candidate feature |
|---|---|---|
| CRM | Activation date, plan, contract | Tenure and plan category |
| Usage systems | Daily data and voice events | Monthly GB and voice minutes |
| Billing | Invoice due date and payment date | Late-payment days |
| Customer service | Complaint creation and resolution | Complaints opened per month |
| Network operations | Customer-impacting incidents | Monthly incident count |
| Digital channels | App and portal events | Engagement counts and changes |
Our runnable example uses five monthly numerical features: data_usage_gb, voice_minutes, late_payment_days, complaints and network_incidents. It also uses tenure as a static feature measured at the prediction timestamp. We deliberately omit more sensitive or operationally ambiguous fields rather than implying that every available variable should be used.
In practice, feature definitions need more care than their names suggest. Does a complaint count include reopened tickets? Are late-payment days calculated from the contractual due date or a grace period? Does a network incident affect the subscriber or merely a nearby network element? Each definition needs an accountable owner and a reproducible computation.
3. Build a customer-month feature table
Raw systems produce events at different frequencies. We need to align them into one row per customer per completed month. The following example shows the principle for daily data usage; similar transformations would be required for billing, complaints and incidents.
import pandas as pd
usage["event_date"] = pd.to_datetime(usage["event_date"])
usage["month"] = usage["event_date"].dt.to_period("M").dt.to_timestamp()
monthly_usage = (
usage.groupby(["customer_id", "month"])
.agg(data_usage_gb=("data_gb", "sum"))
.reset_index()
)
The example assumes usage is an already loaded source table. In production, a point-in-time pipeline should apply the relevant event and availability cutoffs before aggregation. It should also differentiate a genuine zero from a missing source record and handle corrections that arrive after a scoring date.
An illustrative customer history might look like this:
| Month | Data GB | Voice minutes | Late days | Complaints | Incidents |
|---|---|---|---|---|---|
| January | 82 | 320 | 0 | 0 | 1 |
| February | 76 | 305 | 0 | 0 | 1 |
| March | 68 | 280 | 0 | 1 | 2 |
| April | 58 | 240 | 3 | 1 | 2 |
| May | 49 | 205 | 5 | 2 | 3 |
| June | 42 | 180 | 8 | 2 | 4 |
Figure 1. Two illustrative customers have the same average usage but opposite trajectories. A snapshot average hides the direction of change.
4. Turn monthly observations into sequences
Each month becomes a five-dimensional vector. Six months produce a matrix for one customer:
For 12,000 customer histories, the input tensor has shape (12000, 6, 5): customers, months and features. Unlike the tabular Transformer in our credit card propensity tutorial, each token here represents a month, not a separate column.
import numpy as np
feature_columns = [
"data_usage_gb", "voice_minutes", "late_payment_days",
"complaints", "network_incidents"
]
def build_sequences(monthly_features):
sequences, customer_ids = [], []
for customer_id, group in monthly_features.groupby("customer_id"):
group = group.sort_values("month")
if len(group) != 6:
continue
sequences.append(group[feature_columns].to_numpy(dtype=np.float32))
customer_ids.append(customer_id)
return np.stack(sequences), np.asarray(customer_ids)
This small function illustrates tensor construction, not the entire production pipeline. It assumes six valid, preselected months per customer. In real use, construct sequences for each customer and prediction date, verify month continuity, handle missing periods explicitly, and avoid overlapping observations crossing training and test boundaries without a deliberate evaluation design.
Figure 2. A six-month by five-feature matrix for one illustrative customer. The displayed values retain their original units; colour intensity is normalised separately by feature.
5. Prepare numerical, categorical and static features
Monthly data usage, voice minutes and incident counts have different scales. We standardise numerical features using statistics fitted on the training period only. Validation, test and future inference must reuse those exact parameters.
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler().fit(X_train.reshape(-1, 5))
def scale_sequences(X):
return scaler.transform(X.reshape(-1, 5)).reshape(X.shape).astype("float32")
X_train_scaled = scale_sequences(X_train)
X_valid_scaled = scale_sequences(X_valid)
X_test_scaled = scale_sequences(X_test)
These arrays are created in the full runnable script supplied with this article. The script also scales tenure separately. If a production dataset contains categorical monthly features such as plan type, they can be encoded using a training-fitted vocabulary and a learned embedding table. The categorical embedding can then be concatenated with, or projected alongside, the numerical monthly representation. Missingness should be represented explicitly where relevant; replacing every missing value with zero can silently alter its meaning.
The tutorial keeps categorical features out of the runnable model to make the temporal mechanism easier to inspect. That is a scoped educational choice, not a recommendation to omit them from real churn modelling.
6. Understand temporal embeddings and the Transformer input
The raw monthly vector has five values. A learned linear projection maps it into a model dimension, such as 32:
Six projected months become a (batch_size, 6, 32) tensor. The projection learns combinations of the behavioural measurements. We then add a learned positional vector to each monthly token:
Position information matters because a standard self-attention encoder has no inherent sense of which month came first. For irregular event histories, time gaps or elapsed-time features may be needed in addition to ordinal positions.
The encoder uses scaled dot-product attention:
This allows the representation of one observed month to incorporate information from other observed months. It does not prove that any particular attention weight is a faithful explanation of the churn prediction. We use bidirectional attention because all six input months are already known at the prediction timestamp. This is not future leakage; using post-timestamp events would be.
7. Choose and implement the architecture
We use an encoder-only Transformer because the task requires one classification score from a completed history. We are not generating future observations autoregressively, so an autoregressive decoder is unnecessary. We also do not need the additional complexity of a multi-horizon forecasting architecture for this introductory example. A separate Foundations article will compare major Transformer families in depth.
Figure 3. Monthly features are projected into tokens, positional information is added, an encoder processes the observed history, and the pooled representation is combined with tenure to predict churn.
The runnable implementation is in code/train_churn.py. Its essential model definition is:
class ChurnTransformer(nn.Module):
def __init__(self, n_features=5, seq_len=6, d_model=32, heads=4, layers=2):
super().__init__()
self.project = nn.Linear(n_features, d_model)
self.position = nn.Embedding(seq_len, d_model)
layer = nn.TransformerEncoderLayer(
d_model=d_model, nhead=heads,
dim_feedforward=d_model * 2,
dropout=0.1, batch_first=True
)
self.encoder = nn.TransformerEncoder(layer, num_layers=layers)
self.classifier = nn.Sequential(
nn.LayerNorm(d_model + 1),
nn.Linear(d_model + 1, 32), nn.ReLU(), nn.Linear(32, 1)
)
def forward(self, sequence, tenure):
positions = torch.arange(sequence.shape[1], device=sequence.device)
tokens = self.project(sequence) + self.position(positions).unsqueeze(0)
pooled = self.encoder(tokens).mean(dim=1)
return self.classifier(torch.cat([pooled, tenure], dim=1)).squeeze(-1)
The code is deliberately compact: two encoder layers, four attention heads, mean pooling and a static-tenure branch. It returns one logit per customer; applying sigmoid produces a score between zero and one. Other pooling methods or static-feature fusion designs may perform differently and should be evaluated rather than assumed superior.
8. Train the model and compare it with gradient boosting
A strong baseline is essential. We create conventional features from the same six months: mean value, latest value and first-to-last change for each behaviour, plus tenure. A gradient-boosted tree can learn from those engineered trends without self-attention.
The full script trains a HistGradientBoostingClassifier, then a PyTorch Transformer using BCEWithLogitsLoss, AdamW and validation-loss early stopping. It constructs all arrays, fits preprocessing on training data only, retains the best validation checkpoint and scores the untouched test partition.
Run the example from the package root:
pip install -r code/requirements.txt
python code/train_churn.py --customers 12000 --epochs 20 \
--output validation/my-run-results.json
The synthetic data generator creates one customer history per row and assigns illustrative prediction dates before chronological sorting. It does not simulate genuine calendar-driven drift; therefore, the time-ordered split demonstrates workflow mechanics but cannot establish robustness to real market or behavioural changes. In an actual project, historical customer snapshots and outcome windows must be constructed from event-time and availability-time records, with matured labels and suitable temporal holdouts.
9. Evaluate the model against the retention decision
Accuracy alone can mislead when churn is uncommon. We evaluate ROC-AUC, average precision, Brier score and precision and recall among the top-ranked customers the retention team could contact. Brier score is lower-is-better and should be complemented by calibration analysis when predicted probabilities are used operationally.
The following results come from an executed run on 12,000 synthetic histories, using a 70%/15%/15% ordered split. The test set contained 1,800 records; the contact capacity was set to its top 10%, or 180 customers. Results are saved in validation/full-run-results.json.
| Metric | Gradient boosting | Sequential Transformer |
|---|---|---|
| ROC-AUC | 0.708 | 0.726 |
| Average precision | 0.344 | 0.352 |
| Brier score (lower is better) | 0.129 | 0.126 |
| Precision at top 10% | 45.6% | 47.8% |
| Recall at top 10% | 27.1% | 28.4% |
The Transformer performed slightly better in this synthetic run. That is not a general performance claim. We have not demonstrated stability across multiple seeds, actual time periods or real customers, and the synthetic outcome mechanism is intentionally simplified. A production comparison should use stronger engineered-feature baselines, repeated evaluation periods, calibration checks and subgroup analysis.
A crucial business distinction remains: churn propensity is not retention uplift. A customer likely to leave is not necessarily someone whose behaviour will change because of an offer. Controlled experiments or causal approaches are needed to estimate the incremental effect of interventions.
10. Fit the model into a real retention operation
A notebook does not deliver a retention programme. A telecom company needs a repeatable architecture that connects operational data to a governed feature pipeline, model development, scheduled scoring, retention decisioning and measured outcomes.
Figure 4. Separate data and feature preparation, model training and validation, production scoring, business decisioning and measurement. Predictions support retention decisions; they do not automatically authorise customer contact.
Operational systems provide CRM, billing, usage, complaints and network events. Data engineering aligns identities and event timestamps, constructs consistent customer-month features and monitors data quality. The model development process versions feature definitions, preprocessing parameters, trained models and validation results. An approved production job then scores the current active population using only the information available at the scoring cutoff.
The retention decisioning layer applies communication permissions, eligibility rules, contact frequency limits, operational capacity and approved intervention policies. The campaign system records who was selected, who was actually contacted and what happened afterwards. Monitoring should cover both model behaviour and business outcomes, including drift, calibration, operational failures, customer experience and intervention economics.
Business issues that deserve particular attention include whether a score arrives early enough to be actionable, whether the target population reflects the customers the business can actually contact, whether features are legally and operationally appropriate, and whether the intervention creates incremental value. The organisation also needs named owners for feature quality, model performance, campaign policy, incident response and decisions to retrain or retire the model.
For many organisations, the most consequential design decision is not the number of attention heads. It is whether the predictions can be used responsibly within the constraints of the actual customer relationship and operational process.
Conclusion
Sequential Transformers provide a way to learn from the order of customer behaviour rather than relying entirely on static summaries. We began with operational telecom records, formed six-month customer histories, projected monthly feature vectors into embeddings, added positional information and trained an encoder-only Transformer to predict churn over the next 30 days.
The executed synthetic example demonstrates a working implementation and an honest comparison with gradient boosting. It does not establish that a Transformer is always better, nor that predicting churn is the same as preventing it. The enterprise architecture matters because a model only becomes valuable when reliable features, accountable decisions, lawful customer contact and measurable interventions work together.
The goal is not to deploy a Transformer. It is to help an organisation make better, timely and responsible retention decisions.
Editorial note: All customer histories, chart values and outcomes are synthetic or illustrative. The accompanying Python script has been executed end to end on synthetic data. No real customer information is included. This is an engineering intake package, not authorisation to publish or deploy a model.
