All articles →

100 Exercises / Bayesian statistics / Bayesian Statistics 100 Exercises for Data Analysis

Introduction to Bayesian Regression in Manufacturing | Predicting Order Amount, Order Probability, and Number of Inquiries Using Python

Use PyMC to model order value, win probability, and inquiry counts. Examine coefficient uncertainty, predictive intervals, and model diagnostics.

Overview

In sales and technical support for manufacturing, it is necessary to estimate “next month’s order amount,” “order probability per project,” and “number of inquiries” based on limited results. In this article, we use a fictional industrial equipment manufacturer as a subject and implement Bayesian linear regression, Bayesian logistic regression, and Bayesian Poisson regression as a single decision-making process. Not only point forecasts but also coefficients and forecast uncertainties are visualized, linking to budget, personnel, and project priorities.

This article adapts a training notebook used by Surikobo or its representative, Hiroshi Wayama, with permission from the client company. All data listed is fictional and has no relation whatsoever to real companies, factories, or figures.

Introduction: Practical Challenges in Manufacturing Covered in This Article

Industrial equipment has high project prices and long negotiation periods, so plans based on average values have a greater impact if they fail. Here, we forecast order amounts based on monthly sales promotions and activities, determine follow-up rankings based on the probability of receiving estimate projects, and plan technical inquiry staff based on the number of units in operation.

Common situations on site

  • There are only a few dozen cases, and the normal regression coefficient fluctuates significantly.
  • I want to know the relationship between sales strategies and order amounts, but there is also significant seasonal variation
  • We want to properly treat cases as “orders/cancellations” and inquiries as “counts”
  • While management meetings require a single number per person, the site needs safety margins

Why is this issue so difficult to judge?

The type of the target variable varies depending on continuous, binary, and counting values, and estimation errors cannot be ignored with small datasets. Bayesian regression combines prior knowledge with observational data, treating unknown parameters as posterior distributions. Therefore, it can be explained using probabilities directly related to decision-making, such as “the probability that the coefficient is positive” or “the probability that the order amount falls below the planned value.”

Overview of the exercises

No.ThemeKey Decisions
061–066Bayesian linear regressionUnderstanding order value factors, budget planning, and forecasting range
067–068Bayesian logistic regressionOrder Probability and Follow-up Priority for Quotation Projects
069–070Bayesian Poisson regressionNumber of inquiries, number of respondents, and margin for upside

Preparing the Python environment

Fix random number seeds so that the same fictional data can be reproduced in the same environment. Give random_seed to PyMC’s MCMC as well. Graphs are drawn using only matplotlib.

Run these cells in Jupyter Notebook in numerical order, starting with [IN: 1]. Each [OUT: n] belongs to the input with the same number. Run the collapsed setup cells too. To reproduce random draws, restart the kernel and run all cells from the top; rerunning only a random-sampling cell advances the generator. Library versions can affect numerical precision and plot rendering.

The teaching examples use two MCMC chains to limit runtime. For operational decisions, run at least four chains and check R-hat, effective sample sizes, divergences, and trace plots for each model.

Libraries and display settings
[IN: 1]
import warnings

import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import pytensor

# Run without a C++ compiler; sampling may take longer.
pytensor.config.cxx = ""

import pymc as pm
import arviz as az

SEED = 20260712
rng = np.random.default_rng(SEED)
pd.set_option("display.float_format", lambda x: f"{x:,.3f}")

print("numpy      :", np.__version__)
print("pandas     :", pd.__version__)
print("matplotlib :", matplotlib.__version__)
print("PyMC       :", pm.__version__)

from IPython.display import display
[OUT: 1]
numpy      : 2.5.1
pandas     : 3.0.3
matplotlib : 3.11.0
PyMC       : 5.26.1

Creating synthetic data

We create three types of business data for the same manufacturer. Linear regression covers monthly order amounts (million yen), logistic regression covers whether quoted projects have been received, and Poisson regression tracks the number of weekly inquiries. This is not based on actual individual company data.

Setup code for the synthetic data
[IN: 2]
# Monthly Sales Data (36 months)
n_month = 36
sales = pd.DataFrame(
    {
        "month": pd.date_range("2023-01-01", periods=n_month, freq="MS"),
        "promotion_million": rng.uniform(1.5, 7.0, n_month),
        "sales_visits": rng.integers(35, 91, n_month),
    }
)
sales["orders_million"] = (
    18
    + 4.2 * sales["promotion_million"]
    + 0.32 * sales["sales_visits"]
    + rng.normal(0, 6.0, n_month)
)

# Quotation Project Data (160 items)
n_deal = 160
deals = pd.DataFrame(
    {
        "value_million": rng.lognormal(np.log(8), 0.55, n_deal),
        "demo_done": rng.binomial(1, 0.58, n_deal),
        "lead_days": rng.integers(5, 61, n_deal),
    }
)
z = (
    -0.7
    - 0.055 * (deals["value_million"] - 8)
    + 1.25 * deals["demo_done"]
    - 0.025 * (deals["lead_days"] - 25)
)
deals["won"] = rng.binomial(1, 1 / (1 + np.exp(-z)))

# Weekly Inquiry Data (80 weeks)
n_week = 80
support = pd.DataFrame(
    {
        "week": np.arange(1, n_week + 1),
        "installed_100": rng.uniform(5, 22, n_week),
        "release_week": rng.binomial(1, 0.18, n_week),
    }
)
lam = np.exp(0.35 + 0.075 * support["installed_100"] + 0.48 * support["release_week"])
support["inquiries"] = rng.poisson(lam)

display(sales.head(3))
display(deals.head(3))
display(support.head(3))
[OUT: 2]
month promotion_million sales_visits orders_million
0 2023-01-01 5.309 83 64.583
1 2023-02-01 4.153 85 62.291
2 2023-03-01 6.281 62 58.671
value_million demo_done lead_days won
0 15.960 1 34 1
1 14.069 1 52 0
2 7.036 1 16 1
week installed_100 release_week inquiries
0 1 16.799 0 9
1 2 12.655 0 4
2 3 6.783 1 9

No.061: Understanding the Bayesian Linear Regression Concept

Practical meaning

If you can explain the order amount as promotional expenses and number of visits, you can convert next month’s initiative proposals into sales plans. However, it is important not to treat estimates as definite values, and to leave uncertainty based on the amount of data used.

Model and assumptions

yiy_i the order amount per month ii, and using standardized promotional expenses and the number of visits as xi1,xi2x_{i1},x_{i2},

yi∼N(μi,σ2),μi=α+β1xi1+β2xi2\begin{aligned} y_i &\sim \mathcal{N}(\mu_i,\sigma^2), \\ \mu_i &=\alpha+\beta_1x_{i1}+\beta_2x_{i2} \end{aligned}

That’s how it is placed. While frequentist regression focuses on point estimation of coefficients, Bayesian regression seeks p(α,β,σ∣y,X)p(\alpha,\boldsymbol{\beta},\sigma\mid y,X).

Check with Python

[IN: 3]
fig, ax = plt.subplots(figsize=(7, 4))
sc = ax.scatter(
    sales["promotion_million"],
    sales["orders_million"],
    c=sales["sales_visits"],
    cmap="viridis",
    s=55,
)
fig.colorbar(sc, ax=ax, label="Sales visits")
ax.set_title("Monthly orders and promotion spending")
ax.set_xlabel("Promotion spending (million JPY)")
ax.set_ylabel("Orders (million JPY)")
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
[OUT: 3]

Plot: No.061: Understanding the Bayesian Linear Regression Concept

Interpreting the results

Months with higher promotional expenses tend to have higher order amounts, but even within the same promotional budget, the number of visits and unexpected fluctuations can vary. This range is carried over into coefficient estimation and future projection called Bayesian regression. It is also important to note that correlation alone cannot be definitively identified as causal effect.

No.062: Setting a prior distribution for Regression Coefficients

Practical meaning

We suppress unrealistic coefficients such as “orders increase by hundreds of millions yen per 1 million yen of promotional expenses” based on small datasets, and clearly indicate past experiences and operational limits in the model.

Model and assumptions

After standardizing the explanatory variables, set α∼N(50,302)\alpha\sim\mathcal{N}(50,30^2) for intercepts, βj∼N(0,152)\beta_j\sim\mathcal{N}(0,15^2) for coefficients, and σ∼HalfNormal(15)\sigma\sim\mathrm{HalfNormal}(15) for errors. This is a weakly informative prior distribution that does not determine the positive or negative coefficients. Through prior predictive checks, we check whether we generate a large amount of unnatural order amounts.

Check with Python

[IN: 4]
features = ["promotion_million", "sales_visits"]
X_mean, X_sd = sales[features].mean(), sales[features].std()
X = ((sales[features] - X_mean) / X_sd).to_numpy()
y = sales["orders_million"].to_numpy()

prior_rng = np.random.default_rng(SEED + 1)
alpha_prior = prior_rng.normal(50, 30, 4000)
beta_prior = prior_rng.normal(0, 15, (4000, 2))
sigma_prior = np.abs(prior_rng.normal(0, 15, 4000))
mu_typical = alpha_prior  # Standardized explanatory variable 0 (average month)
y_prior = prior_rng.normal(mu_typical, sigma_prior)
print(pd.Series(y_prior).quantile([0.025, 0.5, 0.975]).rename("prior orders"))
[OUT: 4]
0.025   -15.451
0.500    50.607
0.975   113.715
Name: prior orders, dtype: float64

Interpreting the results

Even at average activity levels, the prior predictive 2.5th percentile is about −15.5 million JPY. Negative order values are impossible, so this normal model is a teaching simplification. Before using it in practice, consider tighter priors, a model for log order value, or a positive-valued likelihood.

No.063: Implementing Bayesian Linear Regression in PyMC

Practical meaning

Turn assumptions into reproducible code and transform model updates from dependent spreadsheets into periodically executable analytical processes.

Model and assumptions

Probability and prior distribution are declared in PyMC, and NUTS samples from posterior distributions. r_hat indicates the convergence of multiple chains, and ess_bulk indicates the effective sample size.

Check with Python

[IN: 5]
with pm.Model() as linear_model:
    alpha = pm.Normal("alpha", mu=50, sigma=30)
    beta = pm.Normal("beta", mu=0, sigma=15, shape=2)
    sigma = pm.HalfNormal("sigma", sigma=15)
    mu = alpha + pm.math.dot(X, beta)
    pm.Normal("orders", mu=mu, sigma=sigma, observed=y)
    linear_idata = pm.sample(
        700,
        tune=700,
        chains=2,
        cores=1,
        random_seed=SEED,
        target_accept=0.9,
        progressbar=False,
    )

linear_summary = az.summary(
    linear_idata, var_names=["alpha", "beta", "sigma"], hdi_prob=0.95, round_to=3
)
display(linear_summary)
[OUT: 5]
mean sd hdi_2.5% hdi_97.5% mcse_mean mcse_sd ess_bulk ess_tail r_hat
alpha 57.116 1.005 54.979 58.955 0.029 0.027 1,248.678 1,024.931 1.000
beta[0] 8.216 0.980 6.286 10.115 0.028 0.029 1,268.013 816.110 1.001
beta[1] 4.974 1.018 3.251 7.253 0.028 0.029 1,313.229 815.351 1.000
sigma 5.904 0.765 4.544 7.504 0.026 0.023 917.321 778.611 1.002

Interpreting the results

If the r_hat is generally 1.01 or below and the effective sample size is not extremely small, you can first confirm the numerical convergence. However, convergence does not prove model validity. Residuals, outliers, time dependence, and the data generation process are checked separately.

No.064: Checking the posterior distribution of the regression coefficient

Practical meaning

Instead of choosing between ‘effective’ or ‘not effective,’ you can share how confident you are about the magnitude and direction of the effect.

Model and assumptions

Calculate the 2.5th and 97.5th percentiles of each standardized coefficient’s posterior samples to obtain a 95% equal-tailed credible interval. This differs from the highest-density interval (HDI) in the ArviZ summary. Also report the probability that each coefficient is positive.

Check with Python

[IN: 6]
beta_draws = linear_idata.posterior["beta"].stack(sample=("chain", "draw")).values
coef_result = pd.DataFrame(
    {
        "feature": features,
        "posterior_mean": beta_draws.mean(axis=1),
        "eti_2.5%": np.quantile(beta_draws, 0.025, axis=1),
        "eti_97.5%": np.quantile(beta_draws, 0.975, axis=1),
        "P(beta>0)": (beta_draws > 0).mean(axis=1),
    }
)
display(coef_result)
[OUT: 6]
feature posterior_mean eti_2.5% eti_97.5% P(beta>0)
0 promotion_million 8.216 6.188 10.107 1.000
1 sales_visits 4.974 2.954 7.050 1.000

Interpreting the results

Variables with a higher probability of being positive and whose intervals are far from zero can be observed more stably positive correlations. Since it’s a standardized coefficient, you can compare activity by one standard deviation. On the other hand, when promotional expenses and the number of visits are decided simultaneously, experimentation and coordination are necessary to achieve causal effects on the initiative.

No.065: Visualizing the Bayesian Regression Credible interval

Practical meaning

By showing not only core forecasts for each budget proposal but also the average response credible interval, management and the field can share risk levels.

Model and assumptions

Fix the average number of visits and adjust the promotional budget. For each post-coefficient sample, calculate the expected order amount and plot the 2.5, 50, and 97.5 percentiles. This is the uncertainty of the average response and does not include random errors in individual months.

Check with Python

[IN: 7]
promo_grid = np.linspace(1.5, 7.0, 80)
X_grid = np.column_stack(
    [
        (promo_grid - X_mean["promotion_million"]) / X_sd["promotion_million"],
        np.zeros_like(promo_grid),
    ]
)
alpha_draws = linear_idata.posterior["alpha"].stack(sample=("chain", "draw")).values
mu_grid = alpha_draws[:, None] + beta_draws.T @ X_grid.T
lo, med, hi = np.quantile(mu_grid, [0.025, 0.5, 0.975], axis=0)

fig, ax = plt.subplots(figsize=(7, 4))
ax.scatter(sales["promotion_million"], y, alpha=0.55, label="Observed")
ax.plot(promo_grid, med, color="C1", label="Posterior median")
ax.fill_between(
    promo_grid, lo, hi, color="C1", alpha=0.25, label="95% credible interval"
)
ax.set_title("Expected monthly orders at average sales visits")
ax.set_xlabel("Promotion spending (million JPY)")
ax.set_ylabel("Expected orders (million JPY)")
ax.grid(True, alpha=0.3)
ax.legend()
plt.tight_layout()
plt.show()
[OUT: 7]

Plot: No.065: Visualizing the Bayesian Regression Credible interval

Interpreting the results

The band represents the uncertainty of coefficient estimation. The more extrapolate the area with fewer observations, the wider the section generally becomes. A credible interval is a ‘posterior probability interval where the expected value is included under this model and data,’ and it is interpreted differently from the confidence interval in frequentism.

No.066: Predicting Order Value Using Bayesian Regression

Practical meaning

The next month’s plan is not set as a single value; instead, it shows downward, median, and upward trends, creating scenarios for cash flow and production capacity.

Model and assumptions

Next month, we will spend 5 million yen on sales promotion and have 70 visits. A posterior distribution is created by adding the uncertainty of expected values to the observational error of σ\sigma. The forecast range is broader than the credible interval and includes variation in individual months.

Check with Python

[IN: 8]
next_x = np.array(
    [
        (5.0 - X_mean["promotion_million"]) / X_sd["promotion_million"],
        (70 - X_mean["sales_visits"]) / X_sd["sales_visits"],
    ]
)
sigma_draws = linear_idata.posterior["sigma"].stack(sample=("chain", "draw")).values
next_mu = alpha_draws + beta_draws.T @ next_x
pred_rng = np.random.default_rng(SEED + 2)
next_orders = pred_rng.normal(next_mu, sigma_draws)
q = np.quantile(next_orders, [0.025, 0.5, 0.975])
decision = pd.Series(
    {
        "2.5%": q[0],
        "median": q[1],
        "97.5%": q[2],
        "P(orders < 50)": (next_orders < 50).mean(),
    }
)
display(decision.to_frame("next-month prediction"))
[OUT: 8]
next-month prediction
2.5% 49.198
median 61.317
97.5% 72.412
P(orders < 50) 0.034

Interpreting the results

The median can be used as the baseline plan, and the 2.5% point as a severe downward case. Also, the “probability of falling under 50 million yen” is directly linked to the activation conditions of inventory and financial plans. In decision-making, not only forecast accuracy but also the difference between excess inventory and out-of-stock losses is clearly stated.

No.067: Understanding Bayesian Logistic Regression

Practical meaning

If you use binary results like orders and lost orders as they are in linear regression, the prediction can be less than 0 or even over 1. With logistic regression, you can evaluate the deal as a probability.

Model and assumptions

For opportunity ii, let yi∈{0,1}y_i\in\{0,1\} indicate whether the order is won. The model is

yi∼Bernoulli(pi),logit(pi)=α+xi⊤β\begin{aligned} y_i &\sim\mathrm{Bernoulli}(p_i), \\ \mathrm{logit}(p_i)&=\alpha+\boldsymbol{x}_i^\top\boldsymbol{\beta} \end{aligned}

Let’s say so. The exp⁡(β)\exp(\beta) of the coefficient exponentially is the odds ratio when the explanatory variable increases by one unit under other constant conditions.

Check with Python

[IN: 9]
win_by_demo = deals.groupby("demo_done")["won"].agg(["count", "mean"])
win_by_demo.index = ["No demo", "Demo completed"]
display(win_by_demo.rename(columns={"mean": "observed_win_rate"}))
[OUT: 9]
count observed_win_rate
No demo 66 0.318
Demo completed 94 0.479

Interpreting the results

The observed order rate for demo projects serves as a comparative point, but it does not adjust for differences in project amounts or lead days composition. Regression models handle multiple conditions simultaneously to obtain the order probability distribution for each project. It should be noted that it is not possible to definitively determine the causal effect of the demo from observational data.

No.068: Estimating Purchase Probability Using Bayesian Logistic Regression

Practical meaning

Here, we interpret B2B “purchase” as receiving quotation projects. Not only do we arrange projects in order of probability, but we also calculate the expected order amount by multiplying the project amounts and allocating limited sales work.

Model and assumptions

Standardize deal amounts and lead days, and invest in demo implementation at 0/1. Using the Weakly Informative prior distribution N(0,1.52)\mathcal{N}(0,1.5^2), the probability of winning a deal is calculated for each posterior sample.

Check with Python

[IN: 10]
logit_cols = ["value_million", "demo_done", "lead_days"]
logit_mean = deals[["value_million", "lead_days"]].mean()
logit_sd = deals[["value_million", "lead_days"]].std()
X_logit = np.column_stack(
    [
        (deals["value_million"] - logit_mean["value_million"])
        / logit_sd["value_million"],
        deals["demo_done"],
        (deals["lead_days"] - logit_mean["lead_days"]) / logit_sd["lead_days"],
    ]
)

with pm.Model() as logit_model:
    a = pm.Normal("a", 0, 1.5)
    b = pm.Normal("b", 0, 1.5, shape=3)
    p = pm.Deterministic("p", pm.math.sigmoid(a + pm.math.dot(X_logit, b)))
    pm.Bernoulli("won", p=p, observed=deals["won"].to_numpy())
    logit_idata = pm.sample(
        700,
        tune=700,
        chains=2,
        cores=1,
        random_seed=SEED + 3,
        target_accept=0.9,
        progressbar=False,
    )

p_draws = logit_idata.posterior["p"].stack(sample=("chain", "draw")).values
deals_result = deals.copy()
deals_result["win_prob"] = p_draws.mean(axis=1)
deals_result["expected_orders_million"] = (
    deals_result["value_million"] * deals_result["win_prob"]
)
display(
    deals_result.nlargest(8, "expected_orders_million")[
        [
            "value_million",
            "demo_done",
            "lead_days",
            "win_prob",
            "expected_orders_million",
        ]
    ]
)
[OUT: 10]
value_million demo_done lead_days win_prob expected_orders_million
143 42.899 1 5 0.554 23.760
156 49.475 1 35 0.394 19.492
93 21.275 1 18 0.538 11.448
144 18.953 1 25 0.503 9.537
149 17.189 1 22 0.525 9.029
11 16.943 1 27 0.496 8.410
41 16.084 1 25 0.510 8.208
76 15.074 1 22 0.531 7.999

Interpreting the results

Expected order value combines win probability and deal size, but also consider margin, follow-up effort, and delivery constraints. This table fits historical deals used for training; it is not an evaluation on unseen opportunities. Standardize new cases using training-set statistics and validate predictions on a later period.

No.069: Understanding Bayesian Poisson Regression

Practical meaning

It handles non-negative integers such as inquiries, failures, and defects. As the number of operating units increases, the number of projects also rises, so simple averages alone can lead to errors in staffing planning.

Model and assumptions

Using the number of ii cases per week as yiy_i,

yi∼Poisson(λi),log⁡λi=α+xi⊤βy_i\sim\mathrm{Poisson}(\lambda_i),\qquad \log\lambda_i=\alpha+\boldsymbol{x}_i^\top\boldsymbol{\beta}

Let’s say so. exp⁡(β)\exp(\beta) is the expected multiplier for an increase of one unit in the explanatory variable. Since the Poisson distribution has equal variance to the mean, if overdispersion is strong, negative binomial regression is considered.

Check with Python

[IN: 11]
count_check = support["inquiries"].agg(["mean", "var", "min", "max"])
display(count_check.to_frame("inquiries"))

fig, ax = plt.subplots(figsize=(7, 3.8))
ax.scatter(
    support["installed_100"],
    support["inquiries"],
    c=support["release_week"],
    cmap="coolwarm",
    alpha=0.75,
)
ax.set_title("Weekly inquiries and installed base")
ax.set_xlabel("Installed units (hundreds)")
ax.set_ylabel("Inquiries per week")
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
[OUT: 11]
inquiries
mean 4.050
var 7.263
min 0.000
max 15.000

Plot: No.069: Understanding Bayesian Poisson Regression

Interpreting the results

Expected inquiry counts vary with installed units and release status. Therefore, variance above the mean across all weeks does not by itself violate a Poisson regression assumption. Check residuals and posterior predictive distributions conditional on these predictors for remaining overdispersion.

No.070: Estimating the Number of Inquiries Using Bayesian Poisson Regression

Practical meaning

Predict the upward swing in inquiries during the new release week using probability distributions, and plan first responders, escalation slots, and outsourcing slots.

Model and assumptions

Standardize the number of units operating and include the logarithmic link along with the release week flag. Not only the expected number of cases for the next week, but also a posterior distribution including Poisson accidental fluctuations is created, and the probability of processing capacity exceedance is calculated.

Check with Python

[IN: 12]
inst_mean, inst_sd = support["installed_100"].mean(), support["installed_100"].std()
X_count = np.column_stack(
    [(support["installed_100"] - inst_mean) / inst_sd, support["release_week"]]
)
with pm.Model() as count_model:
    ca = pm.Normal("ca", 0, 1.5)
    cb = pm.Normal("cb", 0, 1.0, shape=2)
    rate = pm.Deterministic("rate", pm.math.exp(ca + pm.math.dot(X_count, cb)))
    pm.Poisson("inquiries", mu=rate, observed=support["inquiries"].to_numpy())
    count_idata = pm.sample(
        700,
        tune=700,
        chains=2,
        cores=1,
        random_seed=SEED + 4,
        target_accept=0.9,
        progressbar=False,
    )

ca_d = count_idata.posterior["ca"].stack(sample=("chain", "draw")).values
cb_d = count_idata.posterior["cb"].stack(sample=("chain", "draw")).values
next_count_x = np.array([(20 - inst_mean) / inst_sd, 1])
next_rate = np.exp(ca_d + cb_d.T @ next_count_x)
count_rng = np.random.default_rng(SEED + 5)
next_count = count_rng.poisson(next_rate)
capacity = 8
count_plan = pd.Series(
    {
        "expected inquiries": next_count.mean(),
        "median": np.median(next_count),
        "95% prediction lower": np.quantile(next_count, 0.025),
        "95% prediction upper": np.quantile(next_count, 0.975),
        f"P(inquiries > {capacity})": (next_count > capacity).mean(),
    }
)
display(count_plan.to_frame("release-week plan"))

fig, ax = plt.subplots(figsize=(7, 3.8))
bins = np.arange(next_count.min(), next_count.max() + 2) - 0.5
ax.hist(next_count, bins=bins, density=True, alpha=0.75, color="C2")
ax.axvline(capacity, color="C3", linestyle="--", label=f"Capacity = {capacity}")
ax.set_title("Posterior predictive inquiries: next release week")
ax.set_xlabel("Inquiries per week")
ax.set_ylabel("Probability")
ax.grid(True, alpha=0.3)
ax.legend()
plt.tight_layout()
plt.show()
[OUT: 12]
release-week plan
expected inquiries 9.399
median 9.000
95% prediction lower 4.000
95% prediction upper 16.000
P(inquiries > 8) 0.586

Plot: No.070: Estimating the Number of Inquiries Using Bayesian Poisson Regression

Interpreting the results

The 95% prediction range is a realistic range of respondents, and the probability of exceeding eight cases is a key factor in securing support personnel. The threshold is set based on “one loss exceeding the limit” and “the cost of one surplus personnel.” Not only the number of transactions, but also processing times by difficulty will be modeled in the next stage.

Practical implications

  1. Depending on the type of the objective variable, you need to select normal for continuous values, Bernoulli for binary values, and Poisson likelihood for number of cases.
  2. Rather than point prediction, the probability of downside, the probability of overcapability, and the probability that a coefficient is positive are more helpful for decision-making.
  3. Prior distribution does not hide arbitrariness; it visualizes assumptions before viewing the data and serves as a subject for stakeholders to review.
  4. Predictive correlation and causal effect are separate. To understand the effectiveness of a policy, experimental design and confounding adjustment are necessary.

Putting the analysis into practice

  • unified definition: Fix KPI definitions such as order dates, lost orders, and inquiry entries
  • Information available at prediction time: Use only explanatory variables that were available at the time of prediction to prevent information leaks.
  • verification: Check errors, interval coverage, and probability corrections with time series holdouts
  • Diagnosis: Examines MCMC convergence, posterior predictive distributions, outliers, overdispersions, and correlations among explanatory variables.
  • Utilization: Break down thresholds, retraining frequency, approvers, and model stop conditions into business procedures
  • Governance: The model assists the person in charge and does not automatically determine ratings or credit approvals.

Conclusion

No.061–070 connect Bayesian regression from a “technique for estimating coefficients” to a “mechanism for allocating business resources including uncertainty.” Although order amount, order probability, and number of inquiries differ in data type, they can be organized under a common framework of prior distribution, likelihood, posterior distribution, and posterior predictive distributioning. In practice, the key to success is not only model accuracy but also designing who changes what in response to predictions.

Consultations for Corporations

At Surikobo, we support data analysis training for manufacturing companies, Bayesian modeling, demand and order forecasting, decision rule design, and everything from PoC to operational implementation. We also offer consultations on designing objective variables, likelihoods, and prior distributions suitable for your company’s data, as well as mapping them into dashboards that can be explained by the field.

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