All articles →

100 Exercises / Probability Statistics / 100 Exercise Points in Probability & Statistical Marketing Applications

Practical Customer Analysis in Manufacturing Using Python | 10 Exercises on RFM, Defection, CLV, and Uplift

Analyze B2B customers with RFM, cohorts, churn, CLV, recommendations, and held-out uplift evaluation in ten practical Python exercises.

Shifting Existing Customers from ‘Sales’ to ‘Relationships’: 10 Key Customer Strategies for Industrial Parts Manufacturers

This article uses the two-year order history and promotional experiments of the fictional industrial parts manufacturer ‘Suiri Seiki’ as a subject to treat Customer prioritization, understanding retention rates, verifying the effectiveness of initiatives, forecasting future value, and cross-selling as a single decision-making process. Through No.051 to No.060, you will see how to move from sales management that merely looks at aggregates to customer strategies where each customer can choose “what to do next.”

Note This material adapts notebooks used in corporate training by Surikobo or its representative, Wayama, and is published with the participating companies’ permission. All datasets are fictional and do not represent actual companies, factories, or results.

Introduction: Practical Challenges in Manufacturing Covered in This Article

Marketing in manufacturing is not just about advertising. It is also important to maintain long-term relationships with agents, equipment manufacturers, and maintenance departments, and to propose repair items and related materials at the appropriate time. However, if you approach ‘visiting because sales are high,’ ‘noticing loss after losing orders,’ or ‘counting only campaign responders as successful,’ you cannot effectively allocate sales effort and discount resources.

Here, order histories are reinterpreted by customer, acquisition timing, and order units, and using descriptive statistics, probabilistic models, machine learning, and randomized controlled trials to create shareable decision-making materials for sales, marketing, and production planning.

Common situations on site

  • Core systems have order history, but customer priorities depend on the experience of the person in charge
  • While tracking new customer numbers, they do not look at retention rates by month of acquisition.
  • Post-exhibition emails and technical consultation sessions are distributed simultaneously to all customers
  • Unable to distinguish between customers whose orders have stopped and those whose purchase cycles are only long.
  • You know sales by product, but don’t know what to buy simultaneously or what product to propose next.
  • Even if the purchase rate after the policy is high, it cannot be ruled out that the original customers were the buyers.

Why is this issue so difficult to judge?

Corporate customers have uneven purchase intervals, with varying sizes and equipment renewal cycles for each customer. Therefore, the average number of purchases alone can be a mix of “dormancy” and “normal long intervals.” Also, when selecting the target of a campaign and measuring its effectiveness using the same data, it is easy to mistakenly interpret the effect of selecting customers with high purchase intent as the effectiveness of the campaign.

What is needed is to separate the units of analysis according to the purpose. At the customer level, use RFM, churn, and CLV; on the acquisition month, use cohort; on the order basis, use basket; and at the initiative level, use A/B testing and Uplift. Each metric is not a “higher is better” evaluation, but is used to determine To which customers, at which touchpoints, and to what extent to spend.

Exercise Overview

No.ThemeKey Decisions
051RFM AnalysisPriority for sales follow-up
052Cohort AnalysisImprovement of acquisition strategies and onboarding
053A/B TestingWill we roll out initiatives company-wide?
054Customer churn analysisWho should we respond to dormant signs?
055Pareto/NBDCapturing the difference in purchase frequency between customers using probabilistic means
056BG/NBDEstimating survival probabilities including purchase stops
057CLVSet investment limits for each client
058Market Basket AnalysisDiscover cross-selling combinations
059Recommendation SystemCreate the next product candidates by customer
060Uplift ModelingChoose customers whose actions change through your actions

Preparing the Python environment

numpy, pandas, scipy, scikit-learn, and matplotlib are used. The random number generator is initialized with a fixed seed so that no matter how many times it runs, the same fictitious data and results are obtained.

Run the cells in order in a notebook. Each [IN: n] is paired with its [OUT: n] result. These outputs were checked with Python 3.14.4, NumPy 2.5.1, and pandas 3.0.3. Library versions can affect final digits and display formatting.

Environment and library setup ([IN: 1])
[IN: 1]
import itertools

import japanize_matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy import stats
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import RocCurveDisplay, roc_auc_score
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from IPython.display import display

pd.set_option("display.max_columns", 20)
pd.set_option("display.float_format", lambda x: f"{x :,.3f}")

SEED = 202507
rng = np.random.default_rng(SEED)
ANALYSIS_END = pd.Timestamp("2025-12-31")
print("Analysis Reference Date:", ANALYSIS_END.date(), " / seed:", SEED)
[OUT: 1]
Analysis Reference Date: 2025-12-31  / seed: 202507

Creation of Fictional Data

Generate customer masters for 600 companies, order headers for January 2024 to December 2025, and order slips. Purchase frequency, unit price, and dormancy vary by customer segment, and certain product categories are often selected simultaneously within an order. This is fictitious data intended to explain the analysis procedure and is not a benchmark to guarantee model performance.

Synthetic-data setup code ([IN: 2])
[IN: 2]
n_customers = 600
segments = np.array(
    [
        "Equipment Manufacturers",
        "agency",
        "Maintenance department",
        "Research and Development",
    ]
)
segment = rng.choice(segments, n_customers, p=[0.30, 0.25, 0.30, 0.15])
cohort_month = rng.integers(0, 12, n_customers)
customers = pd.DataFrame(
    {
        "customer_id": [f"C{i :04d}" for i in range(1, n_customers + 1)],
        "segment": segment,
        "cohort": pd.DatetimeIndex(
            [
                pd.Timestamp("2024-01-01") + pd.DateOffset(months=int(m))
                for m in cohort_month
            ]
        ),
    }
)
customers["cohort"] = customers["cohort"].dt.to_period("M").dt.to_timestamp()

rate_map = {
    "Equipment Manufacturers": 0.75,
    "agency": 1.05,
    "Maintenance department": 0.52,
    "Research and Development": 0.32,
}
amount_map = {
    "Equipment Manufacturers": 320_000,
    "agency": 210_000,
    "Maintenance department": 145_000,
    "Research and Development": 110_000,
}
product_names = np.array(
    ["bearing", "Seal", "lubricant", "Sensors", "control component", "Maintenance Kit"]
)
base_product_p = np.array([0.23, 0.18, 0.14, 0.17, 0.14, 0.14])

orders_data, lines_data = [], []
order_no = 1
for row in customers.itertuples(index=False):
    latent = rng.gamma(shape=1.8, scale=0.7)
    dropout_month = rng.choice(np.arange(8, 30), p=np.repeat(1 / 22, 22))
    for month in pd.date_range(row.cohort, ANALYSIS_END, freq="MS"):
        age = (month.year - row.cohort.year) * 12 + month.month - row.cohort.month
        if age >= dropout_month:
            break
        n_orders = rng.poisson(rate_map[row.segment] * latent)
        for _ in range(n_orders):
            order_id = f"O{order_no :06d}"
            date = month + pd.Timedelta(days=int(rng.integers(0, 27)))
            amount = max(25_000, rng.lognormal(np.log(amount_map[row.segment]), 0.45))
            orders_data.append(
                (
                    order_id,
                    row.customer_id,
                    date,
                    amount,
                    amount * rng.uniform(0.24, 0.38),
                )
            )
            n_items = int(rng.integers(1, 4))
            items = list(
                rng.choice(product_names, size=n_items, replace=False, p=base_product_p)
            )
            if "bearing" in items and "lubricant" not in items and rng.random() < 0.42:
                items.append("lubricant")
            if (
                "Sensors" in items
                and "control component" not in items
                and rng.random() < 0.38
            ):
                items.append("control component")
            weights = rng.dirichlet(np.ones(len(items)))
            for item, weight in zip(items, weights):
                lines_data.append(
                    (order_id, row.customer_id, date, item, amount * weight)
                )
            order_no += 1

orders = pd.DataFrame(
    orders_data,
    columns=["order_id", "customer_id", "order_date", "sales", "gross_profit"],
)
order_lines = pd.DataFrame(
    lines_data,
    columns=["order_id", "customer_id", "order_date", "product", "line_sales"],
)
customers = customers.merge(
    orders.groupby("customer_id")["order_date"].min().rename("first_order"),
    on="customer_id",
    how="left",
)

print(
    f"number_of_customers: {len (customers ):,}society / Order quantity: {len (orders ):,}records / detailed quantity: {len (order_lines ):,}rows"
)
display(orders.head())
display(order_lines.head())
[OUT: 2]
number_of_customers: 600society / Order quantity: 8,390records / detailed quantity: 18,847rows
order_id customer_id order_date sales gross_profit
0 O000001 C0001 2024-12-20 186,215.307 48,156.255
1 O000002 C0001 2024-12-22 271,079.760 100,379.747
2 O000003 C0001 2025-01-19 397,117.855 104,551.397
3 O000004 C0001 2025-02-24 288,861.018 88,361.531
4 O000005 C0001 2025-02-12 140,191.611 41,564.577
order_id customer_id order_date product line_sales
0 O000001 C0001 2024-12-20 Sensors 186,215.307
1 O000002 C0001 2024-12-22 Seal 271,079.760
2 O000003 C0001 2025-01-19 lubricant 72,430.084
3 O000003 C0001 2025-01-19 bearing 224,157.931
4 O000003 C0001 2025-01-19 Seal 100,529.840

No.051: RFM Analysis — Visualizing Sales Follow-up Priorities

Practical Purpose

RFMs organize customers by the number of days from last purchase (Recency), Number of Purchases (Frequency), and Purchase Amount (Monetary). In manufacturing, practical applications include not only identifying key customers but also early identifying large customers whose orders have recently stopped.

Method and Assumptions

Let t0t_0 be the analysis date, tijt_{ij} customer ii’s order dates, and yijy_{ij} the order amounts. Then Ri=t0−max⁡jtijR_i=t_0-\max_j t_{ij}, Fi=∑j1F_i=\sum_j 1, and Mi=∑jyijM_i=\sum_j y_{ij}. Convert each measure to quintile scores, with smaller recency receiving a higher score. Score only customers with purchase history. This example breaks ties by row order; use fixed cutoffs if equal values should receive equal scores.

Check with Python

[IN: 3]
rfm = (
    orders.groupby("customer_id")
    .agg(
        recency=("order_date", lambda s: (ANALYSIS_END - s.max()).days),
        frequency=("order_id", "nunique"),
        monetary=("sales", "sum"),
    )
    .reset_index()
)
rfm["R"] = pd.qcut(
    rfm["recency"].rank(method="first"), 5, labels=[5, 4, 3, 2, 1]
).astype(int)
rfm["F"] = pd.qcut(
    rfm["frequency"].rank(method="first"), 5, labels=[1, 2, 3, 4, 5]
).astype(int)
rfm["M"] = pd.qcut(
    rfm["monetary"].rank(method="first"), 5, labels=[1, 2, 3, 4, 5]
).astype(int)
rfm["rfm_score"] = rfm[["R", "F", "M"]].sum(axis=1)
rfm["action"] = np.select(
    [(rfm["R"] >= 4) & (rfm["F"] >= 4), (rfm["R"] <= 2) & (rfm["M"] >= 4)],
    [
        "Relationship Maintenance and Additional Proposals",
        "Priority confirmation for dormancy prevention",
    ],
    default="Standard Follow",
)

display(rfm.sort_values("rfm_score", ascending=False).head(8))
summary_rfm = rfm.groupby("action").agg(
    number_of_customers=("customer_id", "size"),
    average_last_purchase_days=("recency", "mean"),
    total_sales=("monetary", "sum"),
)
display(summary_rfm)

fig, ax = plt.subplots(figsize=(8, 5))
for label, group in rfm.groupby("action"):
    ax.scatter(
        group["recency"],
        group["monetary"] / 1e6,
        s=18 + group["frequency"] * 1.5,
        alpha=0.55,
        label=label,
    )
ax.set_title("Customer portfolio by RFM")
ax.set_xlabel("Number of days since last purchase (the shorter, the more recent)")
ax.set_ylabel("Cumulative Sales (million yen)")
ax.grid(True, alpha=0.3)
ax.legend()
plt.tight_layout()
plt.show()
[OUT: 3]
customer_id recency frequency monetary R F M rfm_score action
293 C0306 7 41 10,270,366.277 5 5 5 15 Relationship Maintenance and Additional Proposals
272 C0285 11 65 14,943,315.819 5 5 5 15 Relationship Maintenance and Additional Proposals
389 C0402 6 76 16,230,293.881 5 5 5 15 Relationship Maintenance and Additional Proposals
371 C0384 5 24 6,035,812.080 5 5 5 15 Relationship Maintenance and Additional Proposals
369 C0382 13 29 6,060,873.171 5 5 5 15 Relationship Maintenance and Additional Proposals
86 C0089 7 69 17,859,396.094 5 5 5 15 Relationship Maintenance and Additional Proposals
349 C0362 6 37 8,211,112.453 5 5 5 15 Relationship Maintenance and Additional Proposals
330 C0343 11 51 12,737,485.237 5 5 5 15 Relationship Maintenance and Additional Proposals
number_of_customers average_last_purchase_days total_sales
action
Priority confirmation for dormancy prevention 52 258.173 330,612,493.247
Relationship Maintenance and Additional Proposals 141 18.702 945,970,658.570
Standard Follow 393 185.257 776,520,534.649

No.051: RFM Analysis — Visualizing Sales Follow-up Priorities: result chart

Interpreting the Results

In the upper right corner, you’ll see customers who have had significant past sales but haven’t bought recently. This group should prioritize confirming reasons for order suspensions, such as equipment stoppages, changes in responsibility, or competitive switches, rather than uniform discounts. On the other hand, customers who are frequently on the left side are subject to relationship maintenance measures such as stockout prevention and annual contracts. Since RFM alone cannot determine causality or future value, it is combined with subsequent analyses.

No.052: Cohort Analysis — Comparing Post-Acquisition Retention on the Same Time Axis

Practical Purpose

Even if monthly sales are growing, the increase in new acquisition may be masking the loss of existing customers. By reviewing the retention rate by the first order month, you can evaluate the “quality of long-term transactions” of acquisition strategies such as exhibitions, agent introductions, and web inquiries.

Method and Assumptions

Let cic_i be customer ii’s first purchase month and tt a purchase month; elapsed months are a=t−cia=t-c_i. The monthly purchase rate is Retentionc,a=Nc,a/Nc,0\mathrm{Retention}_{c,a}=N_{c,a}/N_{c,0}. An observed month with no buyers is zero; a month beyond observation end is missing. This measures purchasing in that month, not a survival rate that rules out returning after inactivity.

Check with Python

[IN: 4]
cohort_base = orders.assign(
    order_month=orders["order_date"].dt.to_period("M").dt.to_timestamp()
)
first_month = cohort_base.groupby("customer_id")["order_month"].min().rename("cohort")
cohort_base = cohort_base.join(first_month, on="customer_id")
cohort_base["age"] = (
    (cohort_base["order_month"].dt.year - cohort_base["cohort"].dt.year) * 12
    + cohort_base["order_month"].dt.month
    - cohort_base["cohort"].dt.month
)
cohort_counts = (
    cohort_base.groupby(["cohort", "age"])["customer_id"].nunique().unstack()
)
# Zero purchases in an observed month differ from an unobserved future month.
max_age = (ANALYSIS_END.to_period("M") - cohort_counts.index.min().to_period("M")).n
cohort_counts = cohort_counts.reindex(columns=range(max_age + 1)).fillna(0)
for cohort in cohort_counts.index:
    observed_age = (ANALYSIS_END.to_period("M") - cohort.to_period("M")).n
    cohort_counts.loc[cohort, cohort_counts.columns > observed_age] = np.nan
retention = cohort_counts.div(cohort_counts[0], axis=0)
display((retention.iloc[:, :13] * 100).round(1))

fig, ax = plt.subplots(figsize=(9, 5))
for cohort, row in retention.iloc[:, :13].iterrows():
    ax.plot(
        row.index,
        row.values * 100,
        marker="o",
        alpha=0.55,
        label=cohort.strftime("%Y-%m"),
    )
ax.set_title("Customer retention rate by first order month")
ax.set_xlabel("Elapsed months since initial order received")
ax.set_ylabel("Purchase rate for the month (%)")
ax.grid(True, alpha=0.3)
ax.legend(ncol=3, fontsize=8)
plt.tight_layout()
plt.show()
[OUT: 4]
age 0 1 2 3 4 5 6 7 8 9 10 11 12
cohort
2024-01-01 100.000 61.500 57.700 57.700 61.500 69.200 84.600 61.500 53.800 76.900 46.200 61.500 46.200
2024-02-01 100.000 68.300 65.900 61.000 48.800 51.200 51.200 61.000 65.900 56.100 53.700 46.300 43.900
2024-03-01 100.000 60.000 63.300 53.300 70.000 66.700 46.700 46.700 46.700 40.000 33.300 33.300 40.000
2024-04-01 100.000 60.000 54.300 57.100 60.000 45.700 51.400 48.600 48.600 48.600 54.300 37.100 37.100
2024-05-01 100.000 41.500 45.300 52.800 62.300 58.500 52.800 56.600 64.200 49.100 41.500 45.300 32.100
2024-06-01 100.000 62.500 45.000 42.500 57.500 47.500 55.000 57.500 35.000 27.500 50.000 47.500 45.000
2024-07-01 100.000 53.700 53.700 51.900 51.900 48.100 42.600 48.100 50.000 53.700 29.600 33.300 42.600
2024-08-01 100.000 54.400 47.400 50.900 61.400 59.600 45.600 50.900 47.400 50.900 42.100 35.100 29.800
2024-09-01 100.000 42.900 59.200 57.100 59.200 59.200 40.800 53.100 59.200 44.900 46.900 42.900 49.000
2024-10-01 100.000 47.900 45.800 45.800 50.000 56.200 45.800 52.100 54.200 47.900 37.500 35.400 37.500
2024-11-01 100.000 51.100 48.900 57.800 48.900 57.800 51.100 48.900 51.100 53.300 48.900 46.700 40.000
2024-12-01 100.000 52.300 38.600 45.500 43.200 50.000 50.000 40.900 50.000 54.500 40.900 45.500 40.900
2025-01-01 100.000 41.700 33.300 37.500 33.300 29.200 45.800 16.700 33.300 20.800 45.800 37.500 NaN
2025-02-01 100.000 61.500 38.500 15.400 53.800 38.500 46.200 30.800 7.700 23.100 38.500 NaN NaN
2025-03-01 100.000 25.000 100.000 25.000 0.000 50.000 0.000 25.000 25.000 50.000 NaN NaN NaN
2025-04-01 100.000 14.300 14.300 42.900 14.300 14.300 14.300 14.300 14.300 NaN NaN NaN NaN
2025-05-01 100.000 50.000 25.000 75.000 50.000 0.000 25.000 25.000 NaN NaN NaN NaN NaN
2025-06-01 100.000 0.000 0.000 0.000 0.000 0.000 0.000 NaN NaN NaN NaN NaN NaN
2025-07-01 100.000 33.300 0.000 0.000 0.000 33.300 NaN NaN NaN NaN NaN NaN NaN
2025-08-01 100.000 0.000 50.000 50.000 50.000 NaN NaN NaN NaN NaN NaN NaN NaN
2025-09-01 100.000 100.000 0.000 0.000 NaN NaN NaN NaN NaN NaN NaN NaN NaN
2025-10-01 100.000 0.000 0.000 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2025-11-01 100.000 0.000 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2025-12-01 100.000 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN

No.052: Cohort Analysis — Comparing Post-Acquisition Retention on the Same Time Axis: result chart

Interpreting the Results

A significant drop from 100% in the first month to the following month is natural for B2B products that do not purchase monthly. The important thing is to compare cohorts within the same elapsed months. For example, if the acquisition month in the sixth month is weak in retention, further check acquisition channels, first-time purchase products, and whether there is technical follow-up during that period. Listing the cumulative repurchase rate together helps avoid misunderstandings about products with long purchasing cycles.

No.053: A/B Test — Measuring the Pure Effectiveness of Technical Consultation Meetings

Practical Purpose

Looking only at the purchase rates of campaign participants, the influence of choosing customers who were originally highly interested is mixed. A/B tests that randomly divide candidates into intervention and control groups can be used for investment decisions before technical consultations or company-wide email campaigns.

Method and Assumptions

Estimate p^1−p^0\hat p_1-\hat p_0, using the unpooled standard error for a 95% confidence interval and a Wald test of H0:p1=p0H_0:p_1=p_0. Express differences in percentage points. The chart’s error bar is a 95% normal interval for the treated group’s rate; the printed interval is for the rate difference. This separate experiment randomly assigns consultation invitations to 1,200 firms; it measures the effect of sending invitations, not attendance itself.

Check with Python

[IN: 5]
ab_rng = np.random.default_rng(SEED + 1)
n_ab = 1200
ab = pd.DataFrame({"treatment": ab_rng.binomial(1, 0.5, n_ab)})
ab["purchase"] = ab_rng.binomial(1, 0.105 + 0.038 * ab["treatment"])
rates = ab.groupby("treatment")["purchase"].agg(["mean", "sum", "count"])
p0, p1 = rates.loc[0, "mean"], rates.loc[1, "mean"]
diff = p1 - p0
se = np.sqrt(
    p0 * (1 - p0) / rates.loc[0, "count"] + p1 * (1 - p1) / rates.loc[1, "count"]
)
ci = (diff - 1.96 * se, diff + 1.96 * se)
z = diff / se
p_value = 2 * stats.norm.sf(abs(z))
display(rates.rename(index={0: "control group", 1: "intervention group"}))
print(
    f"Purchase rate difference: {100 *diff :.1f} pp / 95% CI: [{100 *ci [0 ]:.1f}, {100 *ci [1 ]:.1f}] pp / p-value: {p_value :.4f}"
)

fig, ax = plt.subplots(figsize=(7, 4))
ax.bar(
    ["control group", "Technical Consultation Group"],
    [p0 * 100, p1 * 100],
    color=["#7f8c8d", "#2874a6"],
)
ax.errorbar(
    1,
    p1 * 100,
    yerr=1.96 * np.sqrt(p1 * (1 - p1) / rates.loc[1, "count"]) * 100,
    color="black",
    capsize=5,
)
ax.set_title("A/B test purchase rates")
ax.set_xlabel("Assigned group")
ax.set_ylabel("Purchase rate (%)")
ax.grid(True, axis="y", alpha=0.3)
plt.tight_layout()
plt.show()
[OUT: 5]
mean sum count
treatment
control group 0.121 71 586
intervention group 0.168 103 614
Purchase rate difference: 4.7 pp / 95% CI: [0.7, 8.6] pp / p-value: 0.0212

No.053: A/B Test — Measuring the Pure Effectiveness of Technical Consultation Meetings: result chart

Interpreting the Results

A positive point estimate alone does not establish an increase. If its confidence interval includes zero, the sample remains compatible with no effect at that confidence level. Compare incremental gross profit, consultation costs, and sample size before extending the trial. Decide the stopping rule in advance rather than stopping when an interim result becomes favorable.

No.054: Customer Churn Analysis — Turning Signs of Order Stoppages into Prioritization

Practical Purpose

Churn analysis helps prioritize customers for follow-up. Define inactivity in relation to the purchase cycle; here churn means no order in the 120 days after the cutoff date.

Method and Assumptions

Build recency, frequency, mean order value, and the number of months with purchases from history through August 2025. Predict no purchase in the next 120 days. Fit scaling on training customers only, train logistic regression, and evaluate ROC-AUC. This evaluates different customers at the same cutoff; use additional cutoff dates to assess future deployment.

Check with Python

[IN: 6]
cutoff = pd.Timestamp("2025-08-31")
hist = orders[orders["order_date"] <= cutoff]
future = orders[
    (orders["order_date"] > cutoff)
    & (orders["order_date"] <= cutoff + pd.Timedelta(days=120))
]
churn = (
    hist.groupby("customer_id")
    .agg(
        recency=("order_date", lambda s: (cutoff - s.max()).days),
        frequency=("order_id", "nunique"),
        avg_sales=("sales", "mean"),
        active_months=("order_date", lambda s: s.dt.to_period("M").nunique()),
    )
    .reset_index()
)
churn["churn"] = (~churn["customer_id"].isin(future["customer_id"])).astype(int)
features = ["recency", "frequency", "avg_sales", "active_months"]
X_train, X_test, y_train, y_test = train_test_split(
    churn[features],
    churn["churn"],
    test_size=0.3,
    random_state=SEED,
    stratify=churn["churn"],
)
churn_model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=2000)).fit(
    X_train, y_train
)
pred = churn_model.predict_proba(X_test)[:, 1]
print(
    f"Desertion rate: {churn ['churn'].mean ():.1%} / TestROC-AUC: {roc_auc_score (y_test ,pred ):.3f}"
)
coef = pd.Series(
    churn_model.named_steps["logisticregression"].coef_[0],
    index=features,
    name="Standardized coefficient",
)
display(coef.to_frame())

fig, ax = plt.subplots(figsize=(6, 5))
RocCurveDisplay.from_predictions(y_test, pred, ax=ax, name="defection model")
ax.set_title("Customer churn ROC curve")
ax.set_xlabel("false positive rate")
ax.set_ylabel("True positive rate")
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
[OUT: 6]
Desertion rate: 44.5% / TestROC-AUC: 0.821
Standardized coefficient
recency 2.023
frequency 0.224
avg_sales -0.015
active_months -0.114

No.054: Customer Churn Analysis — Turning Signs of Order Stoppages into Prioritization: result chart

Interpreting the Results

ROC-AUC measures how often a randomly selected churned customer receives a higher score than a non-churned customer. In this example, recency has a positive standardized coefficient and active months a negative one; check the displayed estimates rather than assuming every frequency measure has the same sign. High predicted churn does not establish that outreach will work. Choose contact thresholds using expected gross profit, available sales time, and false-alarm costs.

No.055: Pareto/NBD — Capturing Variation in Purchase Frequency Using Probability Distributions

Practical Purpose

It is common for a small number of customers to purchase multiple times while many customers purchase a small number of times, even in B2B. If you create a budget based only on average frequencies, you may mistakenly spread the influence of high-frequency customers to all customers. Pareto/NBD separates purchase generation and churn, and is a framework that considers future purchases across the entire customer base.

Method and Assumptions

Pareto/NBD models purchases while active as a Poisson process with customer-specific rate λ\lambda, with Gamma-distributed rate heterogeneity. Dropout times are exponential, dropout rates vary according to a Gamma distribution, and the two rates are independent. Here we only fit a negative-binomial count approximation by moments. It mixes exposure and dropout differences and is not a full Pareto/NBD fit.

Check with Python

[IN: 7]
purchase_counts = (
    orders.groupby("customer_id")["order_id"]
    .nunique()
    .reindex(customers["customer_id"], fill_value=0)
)
mean_x, var_x = purchase_counts.mean(), purchase_counts.var()
if var_x <= mean_x:
    raise ValueError("The moment fit requires variance greater than the mean.")
shape_r = mean_x**2 / (var_x - mean_x)
prob_p = shape_r / (shape_r + mean_x)
x = np.arange(0, int(purchase_counts.quantile(0.98)) + 1)
observed = purchase_counts.value_counts(normalize=True).reindex(x, fill_value=0)
fitted = stats.nbinom.pmf(x, shape_r, prob_p)
print(
    f"average: {mean_x :.2f}Return / disperse: {var_x :.2f} / GammaShape equivalent: {shape_r :.2f}"
)
display(
    pd.DataFrame(
        {
            "Number of purchases": x[:10],
            "Measured Composition Ratio": observed.values[:10],
            "NBDEstimated composition ratio": fitted[:10],
        }
    )
)

fig, ax = plt.subplots(figsize=(8, 5))
ax.bar(x, observed.values, alpha=0.55, label="Measured")
ax.plot(x, fitted, color="#c0392b", marker="o", label="Negative binomial distribution")
ax.set_title("Customer purchase counts and NBD approximation")
ax.set_xlabel("Purchase count over two years")
ax.set_ylabel("Customer Composition Ratio")
ax.grid(True, axis="y", alpha=0.3)
ax.legend()
plt.tight_layout()
plt.show()
[OUT: 7]
average: 13.98Return / disperse: 179.02 / GammaShape equivalent: 1.18
Number of purchases Measured Composition Ratio NBDEstimated composition ratio
0 0 0.023 0.049
1 1 0.048 0.053
2 2 0.050 0.054
3 3 0.057 0.052
4 4 0.067 0.051
5 5 0.050 0.048
6 6 0.047 0.046
7 7 0.042 0.044
8 8 0.043 0.041
9 9 0.040 0.039

No.055: Pareto/NBD — Capturing Variation in Purchase Frequency Using Probability Distributions: result chart

Interpreting the Results

Variance above the mean indicates that a single Poisson distribution does not capture count variation. Acquisition and dropout dates also differ, so not all overdispersion represents purchase-rate heterogeneity. A Pareto/NBD forecast must account for each customer’s exposure and be validated against holdout purchases.

No.056: BG/NBD — Estimating the survival probability of customers who haven’t bought recently

Practical Purpose

Even with the same ‘no purchase in 6 months,’ the meaning differs between customers who used to buy monthly and those who only once a year. BG/NBD combines purchase frequency, last purchase point, and observation period, representing the probability that the product is still tradable.

Method and Assumptions

BG/NBD assumes independent Gamma-distributed purchase rates and Beta-distributed dropout probabilities after repeat purchases. Let xx be repeat purchases, txt_x the time from first to last purchase, and TT the time from first purchase to observation end. For x>0x>0, the conditional active probability is given below.

P(alive)=[1+ab+x−1(α+Tα+tx)r+x]−1P(\mathrm{alive})=\left[1+\frac{a}{b+x-1}\left(\frac{\alpha+T}{\alpha+t_x}\right)^{r+x}\right]^{-1}

Parameters are illustrative, not fitted, and time is measured in months. Under this standard BG/NBD expression, customers with no repeat purchase (x=0x=0) receive active probability one. This modeling convention does not guarantee continued business. See the authors’ derivation. Fit parameters and evaluate holdout purchases before operational use.

Check with Python

[IN: 8]
bg = (
    orders.groupby("customer_id")
    .agg(
        first=("order_date", "min"),
        last=("order_date", "max"),
        n=("order_id", "nunique"),
    )
    .reset_index()
)
bg["x"] = (bg["n"] - 1).clip(lower=0)
bg["t_x"] = (bg["last"] - bg["first"]).dt.days / 30.44
bg["T"] = (ANALYSIS_END - bg["first"]).dt.days / 30.44
r, alpha, a, b = 0.9, 5.0, 1.4, 3.8
ratio = (alpha + bg["T"]) / (alpha + bg["t_x"])
bg["p_alive"] = np.where(
    bg["x"] > 0, 1 / (1 + a / (b + bg["x"] - 1) * ratio ** (r + bg["x"])), 1.0
)
display(bg.sort_values("p_alive").head(10)[["customer_id", "x", "t_x", "T", "p_alive"]])

fig, ax = plt.subplots(figsize=(8, 5))
scatter = ax.scatter(
    (ANALYSIS_END - bg["last"]).dt.days,
    bg["p_alive"],
    c=bg["x"],
    cmap="viridis",
    alpha=0.65,
)
ax.set_title("Recency and BG/NBD active probability")
ax.set_xlabel("Number of days from last purchase")
ax.set_ylabel("Estimated probability of being active")
ax.grid(True, alpha=0.3)
fig.colorbar(scatter, ax=ax, label="Number of repeat purchases x")
plt.tight_layout()
plt.show()
[OUT: 8]
customer_id x t_x T p_alive
202 C0211 21 6.636 21.288 0.000
526 C0541 56 11.531 17.674 0.000
500 C0515 40 14.290 23.489 0.000
140 C0144 21 8.607 21.912 0.000
435 C0449 61 16.623 22.963 0.000
552 C0567 42 15.473 23.916 0.000
238 C0251 27 12.615 23.817 0.000
254 C0267 19 7.786 18.988 0.000
432 C0446 13 6.899 22.668 0.000
109 C0113 26 9.625 17.937 0.000

No.056: BG/NBD — Estimating the survival probability of customers who haven't bought recently: result chart

Interpreting the Results

Even if the number of days since the last purchase is the same, survival probabilities vary depending on the number of repeat purchases and the observation period. In sales lists, you can add this probability to dormant RFM candidates and prioritize customers with high historical value but a sharp drop in survival probability. For businesses or subscriptions where contract termination is explicitly stated, assumptions may not match, so comparisons are made with rule-based or alternative lifetime models.

No.057: CLV — Considering the Upper Limit of Customer Investment from Future Gross Margin

Practical Purpose

Even if sales are the same, differences in gross profit margin, retention rate, and response costs will result in different customer value. CLV (Customer Lifetime Value) is an indicator used to align investment amounts such as visits, technical support, and discounts with future gross profit.

Method and Assumptions

Write expected gross-profit present value as CLVi=∑h=1HE[Nih]mˉi/(1+d)h−Ci\mathrm{CLV}_i=\sum_{h=1}^{H}E[N_{ih}]\bar m_i/(1+d)^h-C_i, where NihN_{ih} is order count, mˉi\bar m_i mean order gross profit, dd the periodic discount rate, and CiC_i service cost. The code approximates annual orders by historical rate times current active probability, discounts year-end profit at 5%, sets service cost to zero, and omits future dropout. This is neither an exact BG/NBD forecast nor full lifetime CLV.

Check with Python

[IN: 9]
value = orders.groupby("customer_id").agg(
    total_gp=("gross_profit", "sum"),
    avg_gp=("gross_profit", "mean"),
    orders=("order_id", "nunique"),
    first=("order_date", "min"),
)
value["observed_years"] = ((ANALYSIS_END - value["first"]).dt.days / 365.25).clip(
    lower=0.25
)
value["annual_rate"] = value["orders"] / value["observed_years"]
value = value.join(bg.set_index("customer_id")["p_alive"])
value["expected_orders_12m"] = value["annual_rate"] * value["p_alive"]
value["clv_12m"] = value["expected_orders_12m"] * value["avg_gp"] / 1.05
display(
    value.sort_values("clv_12m", ascending=False).head(10)[
        ["p_alive", "annual_rate", "avg_gp", "expected_orders_12m", "clv_12m"]
    ]
)

fig, ax = plt.subplots(figsize=(8, 5))
ax.scatter(value["total_gp"] / 1e6, value["clv_12m"] / 1e6, alpha=0.5)
ax.set_title("Historical gross profit and next-year CLV approximation")
ax.set_xlabel("Past Cumulative Gross Profit (million yen)")
ax.set_ylabel("Expected 12-month gross profit (million yen)")
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
[OUT: 9]
p_alive annual_rate avg_gp expected_orders_12m clv_12m
customer_id
C0538 0.965 43.114 117,235.205 41.601 4,644,882.215
C0294 0.927 47.445 107,058.922 43.971 4,483,329.450
C0011 0.970 60.167 75,974.428 58.385 4,224,567.377
C0551 0.936 31.085 117,128.103 29.083 3,244,211.275
C0402 0.968 45.656 65,883.266 44.205 2,773,670.272
C0129 0.890 26.298 122,618.560 23.402 2,732,854.653
C0047 0.953 38.574 77,386.062 36.748 2,708,357.054
C0063 0.962 29.765 99,210.867 28.633 2,705,449.818
C0089 0.966 36.106 80,998.743 34.887 2,691,239.692
C0183 0.822 41.266 82,795.765 33.904 2,673,455.311

No.057: CLV — Considering the Upper Limit of Customer Investment from Future Gross Margin: result chart

Interpreting the Results

Even if past gross profit is high, if survival probability is low, future CLV will be low. Conversely, even if your trading history is short, if you have high frequency and high gross margin, you can be a target for development. CLV is not a score that cuts off customers, but information that designs service levels and acquisition cost caps. In production, we reflect product-specific gross profit, returns, sales hours, contract renewals, and forecast uncertainties, sharing them across ranges rather than single values.

No.058: Market Basket Analysis — Finding Proposal Combinations from Simultaneous Purchases

Practical Purpose

By understanding which parts will be purchased together within an order, you can use it to propose accessories during quotes, design maintenance kits, and improve the routing of your e-commerce screen. Since simple simultaneous transactions alone can rank high for popular products, we see connections beyond just chance with lift.

Method and Assumptions

For products A,BA,B, support is P(A∩B)P(A\cap B), confidence is P(B∣A)P(B\mid A), and lift is P(A∩B)/[P(A)P(B)]P(A\cap B)/[P(A)P(B)]. Lift above one indicates more co-purchasing than independence predicts, but does not establish statistical significance, causality, or incremental purchases from recommendations.

Check with Python

[IN: 10]
basket = pd.crosstab(order_lines["order_id"], order_lines["product"]).gt(0)
rules = []
for a, b in itertools.permutations(basket.columns, 2):
    support_a = basket[a].mean()
    support_b = basket[b].mean()
    support_ab = (basket[a] & basket[b]).mean()
    confidence = support_ab / support_a
    lift = confidence / support_b
    rules.append((a, b, support_ab, confidence, lift))
rules = pd.DataFrame(
    rules, columns=["antecedent", "consequent", "support", "confidence", "lift"]
)
top_rules = (
    rules.query("support >= 0.03")
    .sort_values(["lift", "support"], ascending=False)
    .head(10)
)
display(top_rules)

fig, ax = plt.subplots(figsize=(8, 5))
plot_rules = top_rules.sort_values("lift")
labels = plot_rules["antecedent"] + " → " + plot_rules["consequent"]
ax.barh(labels, plot_rules["lift"], color="#2e86c1")
ax.axvline(1.0, color="black", linestyle="--", linewidth=1)
ax.set_title("Lift of co-purchase rules")
ax.set_xlabel("Lift (1 = independent purchases)")
ax.set_ylabel("Related Rules")
ax.grid(True, axis="x", alpha=0.3)
plt.tight_layout()
plt.show()
[OUT: 10]
antecedent consequent support confidence lift
13 Sensors control component 0.179 0.520 1.318
22 control component Sensors 0.179 0.454 1.318
19 bearing lubricant 0.243 0.560 1.313
28 lubricant bearing 0.243 0.571 1.313
12 Sensors bearing 0.127 0.368 0.845
17 bearing Sensors 0.127 0.291 0.845
8 Seal control component 0.118 0.332 0.842
21 control component Seal 0.118 0.300 0.842
7 Seal bearing 0.130 0.364 0.838
16 bearing Seal 0.130 0.299 0.838

No.058: Market Basket Analysis — Finding Proposal Combinations from Simultaneous Purchases: result chart

Interpreting the Results

High-lift rules such as “bearing → lubricants” and “sensors → control components” serve as hypotheses for estimate checks and set proposals. Confidence has a direction, and its value differs between A to B and B to A. To avoid accidental low support or falsification due to product line, season, or distributor inventory, we check reproducibility by period and measure incremental gross profit through small-scale proposal experiments.

No.059: Recommendation System — Creating the Next Product Candidate by Customer

Practical Purpose

Basket analysis shows the overall mix, while recommendations change candidates based on the customer’s purchase history. In sales support, using it as a “second-best product candidate” where the person in charge can check the reason for the proposal is easier to implement than automatic submission.

Method and Assumptions

Build a customer-by-product count matrix XX and calculate cosine similarity between product columns: sjk=xj⊤xk/(∥xj∥∥xk∥)s_{jk}=x_j^\top x_k/(\lVert x_j\rVert\lVert x_k\rVert). Sum similarities weighted by log⁡(1+purchase count)\log(1+\text{purchase count}) and rank only unpurchased products. Return fewer than three recommendations when fewer than three products remain eligible.

Check with Python

[IN: 11]
customer_item = pd.crosstab(order_lines["customer_id"], order_lines["product"])
similarity = pd.DataFrame(
    cosine_similarity(customer_item.T),
    index=customer_item.columns,
    columns=customer_item.columns,
)
similarity = similarity.mask(np.eye(len(similarity), dtype=bool), 0.0)


def recommend(customer_id, n=3):
    history = customer_item.loc[customer_id]
    scores = similarity.dot(np.log1p(history))
    return scores.loc[history.eq(0)].nlargest(n)


product_variety = customer_item.gt(0).sum(axis=1)
candidate_customers = product_variety[product_variety.between(1, 3)].index
target_customer = candidate_customers[len(candidate_customers) // 2]
history = customer_item.loc[target_customer]
result = pd.DataFrame(
    {"Number of purchases": history[history > 0], "Classification": "Purchased"}
)
recs = recommend(target_customer)
print("Target Customers:", target_customer)
display(result)
display(recs.rename("Recommendation Score").to_frame())

fig, ax = plt.subplots(figsize=(7, 5))
im = ax.imshow(similarity, cmap="Blues", vmin=0, vmax=1)
ax.set_xticks(range(len(similarity)), similarity.columns, rotation=45, ha="right")
ax.set_yticks(range(len(similarity)), similarity.index)
ax.set_title("Cosine similarity between products")
ax.set_xlabel("Product Categories")
ax.set_ylabel("Product Categories")
ax.grid(False)
fig.colorbar(im, ax=ax, label="similarity")
plt.tight_layout()
plt.show()
[OUT: 11]
Target Customers: C0354
Number of purchases Classification
product
Maintenance Kit 1 Purchased
Sensors 1 Purchased
bearing 1 Purchased
Recommendation Score
product
lubricant 1.959
control component 1.948
Seal 1.924

No.059: Recommendation System — Creating the Next Product Candidate by Customer: result chart

Interpreting the Results

Recommendations identify unpurchased categories associated with the customer’s purchase history. Check compatibility, installed equipment, distributor agreements, and stock before proposing them. Record why staff accept or reject suggestions, then assess incremental gross profit, opportunities created, and inappropriate recommendations.

No.060: Uplift Modeling — Finding Customers Who Change Their Behavior Through Initiatives

Practical Purpose

Even if you focus your efforts on customers with a high purchase probability, those customers may have bought without any initiative. Uplift Modeling estimates the difference in response between intervention and non-intervention for each customer, allocating limited sales hours to the segment where actions change through engagement.

Method and Assumptions

Define conditional average treatment effect as τ(X)=P(Y=1∣T=1,X)−P(Y=1∣T=0,X)\tau(X)=P(Y=1\mid T=1,X)-P(Y=1\mid T=0,X). Split randomized data into training and evaluation customers. A T-learner fits separate logistic regressions to treated and control training customers. Rank held-out customers by predicted uplift and evaluate purchase-rate differences within groups. Individual causal effects remain unobserved.

Check with Python

[IN: 12]
up_rng = np.random.default_rng(SEED + 2)
n_up = 5000
uplift_data = pd.DataFrame(
    {
        "recency": up_rng.gamma(2.2, 55, n_up),
        "frequency": up_rng.poisson(5, n_up),
        "margin": up_rng.lognormal(np.log(60_000), 0.55, n_up),
        "treatment": up_rng.binomial(1, 0.5, n_up),
    }
)
base_logit = -2.4 - 0.006 * uplift_data["recency"] + 0.10 * uplift_data["frequency"]
true_uplift_logit = 0.9 * (
    (uplift_data["recency"] > 45) & (uplift_data["recency"] < 170)
) - 0.35 * (uplift_data["frequency"] >= 8)
p = 1 / (1 + np.exp(-(base_logit + uplift_data["treatment"] * true_uplift_logit)))
uplift_data["purchase"] = up_rng.binomial(1, p)
features_up = ["recency", "frequency", "margin"]

# Fit on one random subset and assess uplift on held-out customers.
up_train, up_test = train_test_split(
    uplift_data, test_size=0.4, random_state=SEED, stratify=uplift_data["treatment"]
)
up_test = up_test.copy()
model_t = make_pipeline(StandardScaler(), LogisticRegression(max_iter=2000))
model_c = make_pipeline(StandardScaler(), LogisticRegression(max_iter=2000))
for treatment, model in [(1, model_t), (0, model_c)]:
    group = up_train.loc[up_train["treatment"].eq(treatment)]
    model.fit(group[features_up], group["purchase"])
up_test["uplift_score"] = (
    model_t.predict_proba(up_test[features_up])[:, 1]
    - model_c.predict_proba(up_test[features_up])[:, 1]
)
up_test["decile"] = pd.qcut(
    up_test["uplift_score"].rank(method="first"), 10, labels=False
)
evaluation = up_test.groupby(["decile", "treatment"])["purchase"].mean().unstack()
evaluation["observed_uplift"] = evaluation[1] - evaluation[0]
evaluation = evaluation.sort_index(ascending=False)
display(
    evaluation.rename(
        columns={
            0: "Control group purchase rate",
            1: "Intervention Group Purchase Rate",
            "observed_uplift": "MeasuredUplift",
        }
    )
)

fig, ax = plt.subplots(figsize=(8, 5))
ax.bar(
    range(1, 11),
    evaluation["observed_uplift"] * 100,
    color=np.where(evaluation["observed_uplift"] >= 0, "#2874a6", "#c0392b"),
)
ax.axhline(0, color="black", linewidth=1)
ax.set_title("Held-out purchase-rate differences by predicted uplift decile")
ax.set_xlabel("Predicted uplift group (1 = highest score)")
ax.set_ylabel(
    "intervention group-Difference in purchase rate between control groups (points)"
)
ax.grid(True, axis="y", alpha=0.3)
plt.tight_layout()
plt.show()
[OUT: 12]
treatment Control group purchase rate Intervention Group Purchase Rate MeasuredUplift
decile
9 0.051 0.089 0.039
8 0.110 0.128 0.019
7 0.031 0.165 0.134
6 0.052 0.165 0.114
5 0.104 0.135 0.030
4 0.088 0.133 0.044
3 0.066 0.096 0.030
2 0.019 0.141 0.123
1 0.020 0.099 0.079
0 0.009 0.044 0.035

No.060: Uplift Modeling — Finding Customers Who Change Their Behavior Through Initiatives: result chart

Interpreting the Results

Check whether high-score groups have larger purchase-rate differences on held-out data. Sampling error means a negative estimate alone does not establish harm. Linear models may miss the simulated effect concentrated in a middle recency range. Use replication, confidence intervals, Qini curves, incremental profit, and contact costs when choosing targets.

Using the Results in Practice

Use RFM and cohorts to describe current customer relationships, then purchase and churn models to estimate future activity. CLV helps set a service budget, while basket analysis and recommendations suggest products. A/B tests and held-out uplift evaluation assess whether outreach changes purchasing.

In manufacturing, not only forecasting accuracy but also connection with supply capacity is crucial. Even if you offer specific products all at once to high-uplift customers, insufficient inventory or production capacity can harm customer experience and profits. It is necessary to design KPIs that allow confirmation of the number of target initiatives, expected demand, gross profit, and supply constraints in the same meeting.

Operational Requirements

  1. Consistent IDs and timestamps: Align customer integrated IDs and the timing of orders, returns, quotations, and contact histories
  2. Definition agreement: Unified purchasing, churn, gross profit, policy expenses, and customer units across sales, accounting, and IT
  3. Verification Design: Use only information prior to the forecast period to secure retention periods and randomized control groups
  4. Implementation of Business Constraints: Reflect equipment compatibility, inventory, number of cases you can handle, and agency contracts in your recommendations and selection
  5. Decision KPIs: In addition to AUC and accuracy, we track incremental gross profit, negotiation rate, inappropriate proposal rate, and supply fulfillment rate.
  6. Improvement from small-scale operations: Conduct tests in a way that allows the person in charge to verify the reasons, and carry the results back to the next learning session

A model is not made once and is not finished. When purchasing cycles, product mix, pricing, and sales operations change, features and thresholds also change. It is important to design monthly data quality monitoring and quarterly effectiveness verification as your responsibilities.

Conclusion

From No.051 to No.060, we used fictitious data from industrial parts manufacturers to reinterpret customers not only by “past sales” but also from the perspectives of retention, turnover, survival probability, future gross profit, mergers, and behavioral changes due to policies.

  • RFM cohorts use a common language to address current situations and changes in customer relationships
  • Pareto/NBD, BG/NBD, and Churn Analysis probabilistically treats differences in purchase frequency and dormancy
  • CLV links future operating and service investments to gross profit.
  • Basket analysis and recommendations create proposal candidates and complete them based on operational constraints and the judgment of the person in charge.
  • A/B testing and uplift modeling evaluate “customers who have changed through initiatives” rather than “responsive customers.”

The ultimate goal is not to introduce advanced models, but to build a decision-making cycle about who to propose what to and how to learn from the results.

Consulting Services

At Surikobo, we handle everything from problem organization to supporting the design of customer data platforms in manufacturing, building churn, CLV, and demand forecasting models, experimental design of sales strategies, and decision support that connects recommendation results with production and inventory constraints. You can consult with us from the stage where you have an order history but don’t translate into measures or want to embed analysis results in the sales field.

📩 Contact Us: www.surikobo.co.jp/contact
Please feel free to consult us first.