Sub topic 2
Turning Behaviour into Features and Content
Assume you know campaign concepts, tabular data, and basic statistics. Python and pandas are helpful but not required to follow the working model.
Turning behaviour into features
A feature is a measurable input used to describe a customer. Raw events, such as orders and visits, become useful when aggregated over a defined time window.
RFM is a common feature set:
- Recency: days since the last purchase. Lower values usually indicate stronger recent engagement.
- Frequency: number of purchases in the window.
- Monetary value: total spending in the window.
Clean the data first. Apply consent and identity rules, remove duplicates, choose a consistent observation window, and check missing values. Scale features before distance-based clustering because spending may otherwise dominate purchase counts.
Creating segments with clustering
Clustering groups customers by similarity without requiring labels. K-means assigns each customer to the nearest of a chosen number of cluster centres.
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
customers = pd.DataFrame({
"customer_id": [1, 2, 3, 4, 5, 6],
"recency_days": [3, 5, 40, 60, 2, 90],
"frequency": [12, 9, 3, 2, 15, 1],
"monetary": [540.0, 410.0, 120.0, 80.0, 700.0, 25.0],
})
features = customers[["recency_days", "frequency", "monetary"]]
scaled = StandardScaler().fit_transform(features)
model = KMeans(n_clusters=2, n_init=10, random_state=42)
customers["segment"] = model.fit_predict(scaled)
print(customers.groupby("segment")[[
"recency_days", "frequency", "monetary"
]].mean())Name clusters from their averages, such as “high-value active” or “lapsed low-value.” Cluster numbers have no business meaning.
Predictive segments: propensity and churn
A predictive segment estimates a future outcome. A propensity score estimates the likelihood of an action, such as purchase. A churn model estimates the likelihood that a customer will stop engaging. Validate predictions on later data, and do not treat a score as a fact. Choose thresholds using campaign capacity, cost, and the harm of incorrect targeting.
Dynamic content and safe fallbacks
Templates select content at delivery time. Every variable needs a safe default, and every conditional needs a valid alternative.
from jinja2 import Template
template = Template(
"Hi {{ first_name | default('there', true) }}, "
"{% if segment == 'lapsed' %}we saved your basket."
"{% else %}see what is new this week.{% endif %}"
)
print(template.render(first_name=None, segment="lapsed"))Modular content and safe fallbacks
Store messages as approved modules rather than generating an entire message for each person. Define fallback content for missing names, unknown segments, unavailable products, and revoked consent.
Exercise
Why should RFM features be scaled before k-means clustering?
Show answer
Scaling prevents a large-valued feature, such as monetary value, from dominating distance calculations.