Skip to content
Data & Technology

10 Steps to Building a Credit Card Propensity Model Using Transformers in Python

A step-by-step guide to preparing banking data, building a tabular Transformer, benchmarking against gradient boosting, and driving controlled campaign decisions.

Share this article

LinkedInXWhatsApp
On this page

Key takeaways

  1. Define the campaign decision and 30-day response target before choosing a model.

  2. Use pre-offer snapshot features; this example does not model transaction sequences.

  3. Enforce time-aware evaluation and prevent leakage from future outcomes or preprocessing.

  4. Compare the Transformer with a strong gradient-boosted tree baseline.

  5. Evaluate ranking, probability quality and precision at actual campaign capacity.

  6. Separate propensity from creditworthiness, eligibility and incremental marketing impact.

A marketing question that becomes a machine learning problem

In this article, we will walk through how a data scientist on a retail bank's analytics team can solve a customer propensity problem using a tabular Transformer.

Consider a common scenario: The bank has hundreds of thousands of existing customers, but the marketing budget only permits contacting a fraction of them about a new credit card. Sending offers to everyone would waste money and could frustrate customers. Choosing customers by a few simple rules might be better than random selection, but those rules can overlook useful combinations of customer behaviour and existing relationships.

The business question is straightforward: which eligible customers should the bank prioritise for its next campaign? A propensity model helps by estimating the probability that a customer will accept an offer within a defined period. We can rank customers using those estimates and examine whether the ranking would improve the use of a limited campaign budget.

We need to be precise about the prediction. Offer propensity is not creditworthiness, an approval decision or proof that an offer caused a customer to respond. A customer predicted to have a 30% response probability is not necessarily a customer who should receive credit, and a high predicted response does not establish that marketing contact would change their behaviour. Those distinctions will matter throughout the tutorial.

Our goal is to build a functioning tabular Transformer, compare it with a strong conventional baseline and understand how the result could inform a responsible business workflow. The examples use synthetic customer data. They teach a method, not actual banking behaviour.

Prerequisites: Basic Python, pandas, supervised learning and some familiarity with neural networks. You can run the accompanying script on a CPU. Install dependencies with pip install -r requirements.txt and execute python code/train_propensity.py --output outputs. The code in the accompanying script is the executable reference implementation for the steps below.

Architecture from historical customer offers through chronological splitting, feature preprocessing, gradient-boosting baseline and tabular Transformer, evaluation and marketing ranking.

Figure 1

Figure 1. From historical offers and pre-offer customer features to a model comparison, ranked customers and a controlled marketing decision. The Transformer path is shown alongside a gradient-boosting baseline.

Step 1. Define the decision, target and observation point

Before writing model code, decide exactly what one training record means. Here, one row represents a historical offer to an eligible customer. The target accepted_offer equals 1 if that offer was accepted within 30 days and 0 otherwise. Features must describe the customer before the offer decision, not after it.

That last requirement is easy to underestimate. An email click recorded after the offer may predict acceptance remarkably well, but it is unavailable when deciding whom to contact. Including it would create data leakage and give the model an unfair view of the future. Similarly, a label for an offer sent yesterday cannot yet be treated as a completed 30-day non-response. In real data, define a prediction timestamp, enforce feature cutoffs and wait until the outcome window has matured.

The model will rank eligible customers for marketing. Eligibility, consent, suppression lists and credit approval remain separate processes.

Step 2. Understand the features and whether they are sequential

Our first model uses tabular customer snapshots, not a sequence of transactions. Each record contains six numerical features and two categorical features. The values summarise what is known at the offer timestamp.

FeatureTypeInterpretation
tenure_monthsNumericalLength of customer relationship
annual_incomeNumericalRecorded annual income
avg_balanceNumericalAverage account balance over an approved pre-offer window
monthly_transactionsNumericalTransaction count over a pre-offer month
digital_loginsNumericalDigital engagement over a pre-offer month
existing_productsNumericalNumber of products held
employment_typeCategoricalEmployment category
customer_segmentCategoricalExisting marketing segment

In the synthetic generator, these values are sampled directly rather than calculated from actual dated transactions. In a real bank, avg_balance, monthly_transactions and digital_logins would need explicit lookback definitions, for example the 30 days before each offer. The same calculation must be reproduced at training and scoring time.

We are not feeding monthly sequences into this Transformer. Its tokens represent features, such as balance and employment type, rather than months or individual transactions. A temporal Transformer would instead receive ordered observations, perhaps six monthly vectors of spending, payments and complaints, and would need temporal information such as time embeddings. That is a separate modelling problem and a natural follow-on tutorial.

We exclude age from model inputs, even though the synthetic source data includes it. This is an illustrative feature-governance decision, not a claim that dropping age eliminates fairness risks. Other variables can act as proxies, and real feature selection requires a documented legal and fairness review.

Step 3. Generate historical campaign data

The companion Python script generates 12,000 synthetic historical offer records using NumPy and pandas. It creates the customer features, assigns an offer_date, constructs an illustrative response probability and samples a binary acceptance outcome.

Code
from code.train_propensity import generate

df = generate(n=12_000, seed=42)
print(df.head())
print('Historical response rate:', df['accepted_offer'].mean())

The simulated response probability is influenced by income, balance, digital engagement, product holdings, segment and age. This is an invented data-generating mechanism, not a statement about the determinants of credit card uptake in a real population. We deliberately leave age out of the model inputs, which also means the model cannot perfectly recover the synthetic mechanism.

Real campaign data would require much more care: repeated customer offers, campaign differences, changing product terms, missing values, consent records, historical targeting decisions and potentially inconsistent outcome capture. The synthetic dataset lets us isolate the mechanics without pretending those issues disappear.

Step 4. Create a time-aware training, validation and test split

The next campaign happens in the future, so a chronological evaluation is generally more informative than randomly mixing earlier and later offers. We sort by offer_date, train on the oldest 70%, validate on the next 15% and reserve the newest 15% as an untouched test set.

Code
n_train = int(len(df) * .70)
n_valid = int(len(df) * .15)
train = df.iloc[:n_train].copy()
valid = df.iloc[n_train:n_train+n_valid].copy()
test = df.iloc[n_train+n_valid:].copy()

In production, add a maturity gap where necessary so the last training labels are fully observed before the validation period begins. Also examine whether repeated customers or overlapping feature windows create dependencies across splits. A time split is helpful, but it does not by itself solve every form of leakage.

Step 5. Prepare numerical values and categorical embeddings

Neural networks need numerical inputs. We standardise numerical features using a scaler fitted on the training period only. For categories, we create integer codes and reserve 0 for an unseen category. Each categorical feature then receives its own learned embedding table inside the Transformer.

Code
from sklearn.preprocessing import StandardScaler, OrdinalEncoder

numeric = ['tenure_months','annual_income','avg_balance',
           'monthly_transactions','digital_logins','existing_products']
categorical = ['employment_type','customer_segment']

scaler = StandardScaler()
X_train_num = scaler.fit_transform(train[numeric]).astype('float32')
X_valid_num = scaler.transform(valid[numeric]).astype('float32')

encoder = OrdinalEncoder(handle_unknown='use_encoded_value', unknown_value=-1)
X_train_cat = encoder.fit_transform(train[categorical]).astype('int64') + 1
X_valid_cat = encoder.transform(valid[categorical]).astype('int64') + 1

We fit preprocessing only on training data. If the scaler or category vocabulary were fitted using the test period, information from the future would influence the model development workflow. The executable script also transforms the test set and calculates the embedding sizes from the training vocabulary.

Step 6. Train a strong baseline before using attention

A Transformer should earn its place. For ordinary tabular data, gradient-boosted trees are often competitive and can be simpler to train and operate. Our baseline uses scikit-learn's HistGradientBoostingClassifier, with one-hot encoding for categories and the original numerical values.

Code
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.pipeline import Pipeline

features = numeric + categorical
baseline = Pipeline([
    ('preprocessor', ColumnTransformer([
        ('numeric', 'passthrough', numeric),
        ('categorical', OneHotEncoder(handle_unknown='ignore',
                                      sparse_output=False), categorical),
    ])),
    ('model', HistGradientBoostingClassifier(
        max_iter=200, learning_rate=.05, max_leaf_nodes=15, random_state=42)),
])
baseline.fit(train[features], train['accepted_offer'])
baseline_prob = baseline.predict_proba(test[features])[:, 1]

The baseline and Transformer must be evaluated on the same held-out records and against the same business objective. Otherwise, an apparent improvement may come from differences in data or evaluation rather than architecture.

Step 7. Understand and build the tabular Transformer

Transformers are associated with language because they can learn relationships among tokens in a sequence. In this tutorial, a token is a feature representation. Each numerical feature is mapped into a learned vector using feature-specific weights and biases. Each categorical feature is represented by a learned embedding. A classification token is added, and a Transformer encoder combines information across the feature tokens.

The attention operation is:

Attention⁡(Q,K,V)=softmax⁡(QK⊤dk)V. \operatorname{Attention}(Q,K,V)=\operatorname{softmax}\left(\frac{QK^\top}{\sqrt{d_k}}\right)V.

Queries and keys determine how information is weighted; values supply the information being combined. Multiple attention heads allow different learned interactions. In this application, that could include relationships between account activity and product holdings, although attention weights should not be treated as a validated explanation of individual predictions.

The model in code/train_propensity.py is a compact FT-Transformer-inspired implementation, not an exact reproduction of the research architecture. It uses six numerical feature tokens, two categorical feature tokens, one classification token, two encoder layers and a binary classification head. Because columns have fixed identities, feature-specific projections and embeddings provide identity information; there is no chronological order to encode.

Code
from code.train_propensity import TabularTransformer

model = TabularTransformer(
    n_numeric=len(numeric),
    category_sizes=[len(c) + 1 for c in encoder.categories_],
    d_model=32,
    n_heads=4,
    n_layers=2,
)

The complete model class is in the accompanying runnable script. It is preferable to keep one tested source of truth for the implementation rather than maintain slightly different copies of the same neural network in the article and download.

Step 8. Train, validate and produce probabilities

We use binary cross-entropy with logits, the AdamW optimiser, mini-batches and early stopping on validation loss. The model produces a logit for each customer; applying a sigmoid converts that logit into a value between zero and one. The runnable script contains the full training loop, checkpoint restoration and test inference.

Code
# Run the full, tested workflow from the package root:
# python code/train_propensity.py --output outputs

A value of 0.18 is a model estimate of response probability under conditions comparable to the training data. It is not guaranteed to be a calibrated 18% chance. We therefore examine probability quality rather than assuming the neural network's outputs are automatically reliable.

For a real application, repeat training with multiple random seeds, tune only on validation data, document the selected configuration and preserve the model and preprocessing artefacts together. The demonstration script is intentionally smaller than a production training pipeline.

Step 9. Evaluate the model at the marketing decision point

If only a minority of customers respond, classification accuracy can be misleading. A model that predicts non-response for everyone could appear accurate while being useless for selecting whom to contact. We therefore compare ROC-AUC, average precision, Brier score and precision at campaign capacity.

ROC-AUC assesses ranking across thresholds; average precision summarises precision-recall behaviour; Brier score measures squared probability error. For the marketing team, precision among the top-ranked customers is particularly tangible: if the campaign can contact 500 people, what share of the top 500 historical test records accepted their offers?

Code
from sklearn.metrics import roc_auc_score, average_precision_score, brier_score_loss
import numpy as np

def precision_at_k(y, probabilities, k):
    selected = np.argsort(probabilities)[-k:]
    return np.asarray(y)[selected].mean()

# The executable script reports these metrics for both models.

Lift at capacity compares top-group response with the overall historical response rate. A lift of 2 means the selected group responded at twice the overall rate in the test data. It does not prove that sending the offer caused twice as many responses. Check calibration, uncertainty, stability over time and performance across relevant customer groups before trusting a campaign policy.

The tutorial does not claim that the Transformer wins. The synthetic response mechanism is relatively simple, and a tree model may match or outperform it. Choosing a more complex model is justified only if the evidence demonstrates meaningful additional value.

Step 10. Convert propensity into a controlled campaign decision

The modelling output becomes useful when it supports a real operational decision. In a bank, the scoring pipeline would create a fresh snapshot of eligible customers, apply the same preprocessing, produce probabilities and rank customers subject to contact limits and approved policies. The campaign process would separately enforce consent, marketing preferences, suppressions, suitability and any applicable eligibility rules.

Our script exports a ranked historical test sample as historical_test_ranking.csv for demonstration. It is not a live contact file: the synthetic records have no customer identifiers and already represent past offers. A production export would require a new scoring population and an approved integration with the bank's campaign platform.

Even a well-ranked propensity model may not maximise incremental value. Historical offer recipients were probably selected by earlier marketing policies, so the training sample can suffer selection bias. A customer likely to accept an offer is not necessarily a customer whose decision is changed by receiving it. To estimate incremental campaign impact, the bank may need a randomised holdout, uplift modelling or another defensible causal evaluation design.

The model also needs an operating owner, monitoring for drift and calibration, documented limitations, privacy and fairness review, and a mechanism for withdrawing or retraining it. Business value should be evaluated using incremental outcomes, campaign cost, customer experience and the quality of acquired relationships, not AUC alone.

What we learned

We started with a marketing capacity problem and translated it into a specific prediction task. We defined the outcome window and feature timestamp, prepared customer snapshots, trained a gradient-boosted baseline and a tabular Transformer, and examined the metrics that matter when contact capacity is limited. We also separated prediction from credit approval and from the causal effect of marketing.

The central lesson is not that a Transformer is necessarily the best model for customer data. It is that a practitioner should understand what the tokens represent, compare architectures fairly and connect the model's output to a decision the organisation can operate and evaluate responsibly.

A Transformer is a modelling option. A reliable, measurable marketing decision is the business outcome.

All examples and outcomes in this article are synthetic. The code is educational and has not been validated for regulated banking deployment.