All articles →

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

Bayesian Estimation of Manufacturing Defect Rate | Applying Credible intervals, Exceeding Standards Probability, and Next Lot Forecast with Python

Compare two production lines using posterior estimates, credible intervals, improvement probabilities, predictive counts, and model checks.

A single reported defect rate is insufficient for shipment and process-improvement decisions. Exercises No.041–050 compare current Line A and candidate Line B using posterior estimates, improvement probabilities, next-lot predictions, and model checks.

The questions addressed include the current defect rate, whether it could exceed control standards, whether line B is truly improving, and how many defects are expected in the next lot. External data is not used; instead, fictional data generated by fixed seeds is used.

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

At one factory, non-standard critical dimensions are defined as “defects” and are conducting spot checks on a separate line. The management guideline is a defect rate of 2%. However, if the number of tests is only a few hundred, the error rate can fluctuate even by chance. Judging solely by “1.7% is no problem” or “2.2% is why stop” leads to both overreaction and missed detection.

In this article, we set the defect probability as an unknown parameter pp and calculate the posterior distribution from the prior distribution and test results. On top of that, we cover everything from process status explanation, line comparison, next lot prediction, model verification, to report creation.

Common situations on site

  • The daily report only lists ‘number of tests, number of defects, and defect rate,’ and does not indicate uncertainty.
  • Interpreting the difference in rates before and after improvement as the effect of improvement
  • You cannot discuss probability exceeding management standards alone
  • Estimates based on historical data are often confused with variations in future lots.
  • Report only results without checking for discrepancies between model predictions and actual measurements.

Why is this issue so difficult to judge?

If the number of defects xx is the binomial distribution x∼Binomial(n,p)x\sim\mathrm{Binomial}(n,p) among nn, even with the same true defect rate, the xx changes with each inspection. Also, the uncertainty of the estimated pp and the variation in chance occurring in the next lot are two different things. Bayesian statistics represent the former as posterior distributions, and the combined result as the posterior predictive distribution.

Overview of the exercises

No.ThemeQuestions Answered in Practice
041Posterior averageWhat is the representative defect rate?
042Posterior medianWhat is the value that halves the posterior probability?
043MAP EstimatesWhat is the defect rate with the highest density?
044credible intervalWhere is the most plausible range for defect rates?
045Probability of exceeding thresholdWhat is the probability that the defect rate exceeds the 2% management standard?
046Difference between ratesWhat is the probability and extent of improvement for line B over A?
047Posterior predictive distributionHow to predict the number of defects in the next lot
048Predictive intervalWhat is the realistic range for defective numbers in the next lot?
049Forecast CheckAre there any major discrepancies between the model and actual measurements?
050ReportHow to communicate results to decision-makers

Preparing the Python environment

Only NumPy, pandas, SciPy, and matplotlib are used. Create a random number generator and fix the seed so that the result is the same when you run it again.

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.

Libraries and display settings
[IN: 1]
import sys
import numpy as np
import pandas as pd
import scipy
from scipy.stats import beta, betabinom
import matplotlib
import matplotlib.pyplot as plt
from IPython.display import display, Markdown

SEED = 20250715
rng = np.random.default_rng(SEED)
plt.rcParams["figure.figsize"] = (8, 4.5)
plt.rcParams["axes.unicode_minus"] = False
plot_label = {
    "A(Current)": "Line A (current)",
    "B(Improvement candidate)": "Line B (candidate)",
}

print(f"Python     : {sys.version.split()[0]}")
print(f"NumPy      : {np.__version__}")
print(f"pandas     : {pd.__version__}")
print(f"SciPy      : {scipy.__version__}")
print(f"matplotlib : {matplotlib.__version__}")
[OUT: 1]
Python     : 3.14.4
NumPy      : 2.5.1
pandas     : 3.0.3
SciPy      : 1.18.0
matplotlib : 3.11.0

Creating synthetic data

For each line, let’s say you remove 20 items per day for 25 days. As training data, fixed daily inspection and defect counts are generated in Python. Line A is a candidate based on current conditions, and Line B is a candidate with revised equipment conditions. The data here is a hypothetical value for explanatory purposes.

[IN: 2]
days = pd.date_range("2025-06-02", periods=25, freq="B")
records = []
for line, true_rate in {"A(Current)": 0.024, "B(Improvement candidate)": 0.014}.items():
    defects = rng.binomial(20, true_rate, size=len(days))
    for day, x in zip(days, defects):
        records.append({"date": day, "line": line, "inspected": 20, "defects": int(x)})

inspection = pd.DataFrame(records)
summary = inspection.groupby("line", as_index=False).agg(
    inspected=("inspected", "sum"), defects=("defects", "sum")
)
summary["observed_rate"] = summary["defects"] / summary["inspected"]
display(inspection.head(8))
display(summary.style.format({"observed_rate": "{:.2%}"}))
[OUT: 2]
date line inspected defects
0 2025-06-02 A(Current) 20 0
1 2025-06-03 A(Current) 20 0
2 2025-06-04 A(Current) 20 0
3 2025-06-05 A(Current) 20 0
4 2025-06-06 A(Current) 20 2
5 2025-06-09 A(Current) 20 1
6 2025-06-10 A(Current) 20 0
7 2025-06-11 A(Current) 20 0
  line inspected defects observed_rate
0 A(Current) 500 10 2.00%
1 B(Improvement candidate) 500 8 1.60%
[IN: 3]
daily = inspection.pivot(index="date", columns="line", values="defects")
ax = daily.rename(columns=plot_label).plot(marker="o", linewidth=1.2)
ax.set_title("Daily defects in 20 inspected units")
ax.set_xlabel("Inspection date")
ax.set_ylabel("Number of defects")
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
[OUT: 3]

Plot: Creating synthetic data

Common Model Settings

Use a beta prior p∼Beta(2,98)p\sim\mathrm{Beta}(2,98) with mean 2%. Its parameter sum of 100 controls its weight in the posterior mean; it does not represent a literal inspection record. With xx defects among nn items, conjugacy gives

p∣x,n∼Beta(α+x,  β+n−x)p\mid x,n\sim\mathrm{Beta}(\alpha+x,\;\beta+n-x)

In practice, we agree on prior distribution with quality assurance and production technology, and also conduct sensitivity analysis using multiple prior distributions.

[IN: 4]
prior_a, prior_b = 2, 98
post = summary.copy()
post["alpha"] = prior_a + post["defects"]
post["beta"] = prior_b + post["inspected"] - post["defects"]
post = post.set_index("line")
display(post)
[OUT: 4]
inspected defects observed_rate alpha beta
line
A(Current) 500 10 0.020 12 588
B(Improvement candidate) 500 8 0.016 10 590

No.041: Calculating Posterior Averages

Practical meaning

The posterior mean is a Bayesian estimate when the square error is considered a loss. It is useful when a single representative value is needed for daily reports or KPIs, but it is also necessary to list the distribution range. In the Beta distribution, it is E[p∣x]=α′/(α′+β′)E[p\mid x]=\alpha'/(\alpha'+\beta').

Model and assumptions

Add the observed defect and non-defect counts to the prior parameters, then calculate the beta posterior mean for each line. Compare it with the observed rate to see the influence of the prior.

Check with Python

[IN: 5]
post["posterior_mean"] = post["alpha"] / (post["alpha"] + post["beta"])
display(post[["observed_rate", "posterior_mean"]].style.format("{:.3%}"))
[OUT: 5]
  observed_rate posterior_mean
line    
A(Current) 2.000% 2.000%
B(Improvement candidate) 1.600% 1.667%

Interpreting the results

Posterior averages are positioned between the observed rate and the prior mean. The smaller the sample size, the greater the influence of prior information, which helps suppress overreaction to random swings. However, shipment approval is not determined solely by the average; instead, the sections and probabilities for No.044 and 045 are checked.

No.042: Calculating the Posterior Median

Practical meaning

The posterior median mm meets P(p≤m∣x)=0.5P(p\le m\mid x)=0.5. In a distorted distribution, unlike the mean, the representative value is represented by the absolute error loss. It is worth comparing with indicators that tend to distort near zero, such as low defect rates.

Model and assumptions

Calculate the 50th percentile of each posterior. Compare it with the mean to see how a longer right tail affects the choice of a representative value.

Check with Python

[IN: 6]
post["posterior_median"] = [beta.median(r.alpha, r.beta) for r in post.itertuples()]
display(post[["posterior_mean", "posterior_median"]].style.format("{:.3%}"))
[OUT: 6]
  posterior_mean posterior_median
line    
A(Current) 2.000% 1.947%
B(Improvement candidate) 1.667% 1.613%

Interpreting the results

Although the difference between the average and median is small, it is not identical. When the rate is low and the number of defects is small, the right end of the distribution may be longer, and the average may be slightly above the median. Clearly state the definition of representative values in the report.

No.043: Calculating MAP Estimates

Practical meaning

MAP (maximum a posteriori) is the value where posterior density is maximized. When the Beta distribution is α′,β′>1\alpha',\beta'>1, it is (α′−1)/(α′+β′−2)(\alpha'-1)/(\alpha'+\beta'-2). It shows the most “likely point,” but the probability of a continuous point itself is zero and is not a substitute for the interval.

Model and assumptions

Both posterior shape parameters exceed 1, so the interior beta mode formula applies. Compare the MAP estimate with the mean and median, while reporting an interval separately.

Check with Python

[IN: 7]
post["map"] = (post["alpha"] - 1) / (post["alpha"] + post["beta"] - 2)
display(post[["posterior_mean", "posterior_median", "map"]].style.format("{:.3%}"))
[OUT: 7]
  posterior_mean posterior_median map
line      
A(Current) 2.000% 1.947% 1.839%
B(Improvement candidate) 1.667% 1.613% 1.505%

Interpreting the results

The closeness of the mean, median, and MAP indicates that the estimate is not extremely skewed. However, in decision-making, estimates should be chosen based on the loss function used, and “MAP is not always correct.”

No.044: Calculating the Credible interval

Practical meaning

The 95% equal-tailed credible interval is constructed at the lower 2.5% point and the upper 97.5% point of the posterior distribution. The Bayesian credible interval can be interpreted as a 95% posterior probability that pp falls within this range, based on the model and data.

Model and assumptions

Calculate the 2.5th and 97.5th percentiles for each line. Plot this equal-tailed interval with the posterior mean and the 2% control threshold.

Check with Python

[IN: 8]
post["ci_low"] = [beta.ppf(0.025, r.alpha, r.beta) for r in post.itertuples()]
post["ci_high"] = [beta.ppf(0.975, r.alpha, r.beta) for r in post.itertuples()]
display(post[["posterior_mean", "ci_low", "ci_high"]].style.format("{:.3%}"))

plot_df = post.reset_index()
err = np.vstack(
    [plot_df.posterior_mean - plot_df.ci_low, plot_df.ci_high - plot_df.posterior_mean]
)
fig, ax = plt.subplots()
ax.errorbar(
    plot_df["line"].map(plot_label),
    plot_df.posterior_mean,
    yerr=err,
    fmt="o",
    capsize=6,
    color="tab:blue",
)
ax.axhline(0.02, color="tab:red", linestyle="--", label="Control threshold: 2%")
ax.set_title("Posterior mean and 95% credible interval")
ax.set_xlabel("Production line")
ax.set_ylabel("Defect probability")
ax.grid(True, alpha=0.3)
ax.legend()
plt.tight_layout()
plt.show()
[OUT: 8]
  posterior_mean ci_low ci_high
line      
A(Current) 2.000% 1.039% 3.262%
B(Improvement candidate) 1.667% 0.803% 2.833%

Plot: No.044: Calculating the Credible interval

Interpreting the results

Overlapping marginal intervals do not establish that two rates are equal. Here both intervals cross 2%. Even though B’s posterior mean is below 2%, its true rate may exceed the target. Compare the potential value of further inspection with its cost.

No.045: Calculating the probability that parameters exceed a constant value

Practical meaning

If we set the management standard to plimit=2%p_{limit}=2\%, the probability of exceeding is P(p>plimit∣x)=1−FBeta(plimit)P(p>p_{limit}\mid x)=1-F_{Beta}(p_{limit}). You can present the probability of ‘exceeding the standard or not’ to the quality meeting. Actual shutdown standards are designed in conjunction with losses, regulations, and customer requirements.

Model and assumptions

Use beta.sf to calculate the posterior area above 2%. This is the probability that the true defect rate exceeds the threshold, conditional on the data, model, and prior.

Check with Python

[IN: 9]
limit = 0.02
post["prob_over_2pct"] = [beta.sf(limit, r.alpha, r.beta) for r in post.itertuples()]
display(post[["posterior_mean", "prob_over_2pct"]].style.format("{:.2%}"))

xgrid = np.linspace(0, 0.07, 600)
fig, ax = plt.subplots()
for line, row in post.iterrows():
    density = beta.pdf(xgrid, row.alpha, row.beta)
    ax.plot(xgrid, density, label=plot_label[line])
    ax.fill_between(xgrid, density, where=xgrid > limit, alpha=0.18)
ax.axvline(limit, color="black", linestyle="--", label="Threshold: 2%")
ax.set_title("Posterior distributions and threshold exceedance")
ax.set_xlabel("Defect probability")
ax.set_ylabel("Posterior density")
ax.grid(True, alpha=0.3)
ax.legend()
plt.tight_layout()
plt.show()
[OUT: 9]
  posterior_mean prob_over_2pct
line    
A(Current) 2.00% 46.28%
B(Improvement candidate) 1.67% 24.15%

Plot: No.045: Calculating the probability that parameters exceed a constant value

Interpreting the results

The excess probability is the posterior area to the right of the baseline. This can be linked to rules like “80% or higher, process check,” or “95% or more, pause,” but thresholds quantify the costs of false stops and outflows.

No.046: Calculating the posterior distribution of the difference between two probabilities

Practical meaning

Samples pA,pBp_A,p_B from independent posterior distributions and calculates the Δ=pA−pB\Delta=p_A-p_B of improvement. P(Δ>0)P(\Delta>0) is the probability that B has a lower defect rate than A, and P(Δ>0.005)P(\Delta>0.005) is the probability of improving by 0.5 points or more.

Model and assumptions

Draw 200,000 pairs of rates from the independent posteriors and subtract B from A. Calculate the probabilities of a positive difference and a difference above 0.005, plus its 2.5th and 97.5th percentiles. Express rate differences in percentage points.

Check with Python

[IN: 10]
draws = 200_000
pa = rng.beta(post.loc["A(Current)", "alpha"], post.loc["A(Current)", "beta"], draws)
pb = rng.beta(
    post.loc["B(Improvement candidate)", "alpha"],
    post.loc["B(Improvement candidate)", "beta"],
    draws,
)
delta = pa - pb
comparison = pd.Series(
    {
        "mean_improvement": delta.mean(),
        "prob_B_better": np.mean(delta > 0),
        "prob_improvement_over_0.5pt": np.mean(delta > 0.005),
        "ci_low": np.quantile(delta, 0.025),
        "ci_high": np.quantile(delta, 0.975),
    }
)
formatted_comparison = comparison.to_frame("value").astype(object)
for name in comparison.index:
    value = comparison[name]
    formatted_comparison.loc[name, "value"] = (
        f"{value:.2%}" if name.startswith("prob_") else f"{value * 100:.2f} pp"
    )
display(formatted_comparison)

fig, ax = plt.subplots()
ax.hist(delta, bins=80, density=True, alpha=0.75, color="tab:green")
ax.axvline(0, color="black", linestyle="--", label="No difference")
ax.axvline(0.005, color="tab:red", linestyle=":", label="0.5 pt improvement")
ax.set_title("Posterior distribution of improvement (pA - pB)")
ax.set_xlabel("Reduction in defect probability")
ax.set_ylabel("Density")
ax.grid(True, alpha=0.3)
ax.legend()
plt.tight_layout()
plt.show()
[OUT: 10]
value
mean_improvement 0.34 pp
prob_B_better 67.09%
prob_improvement_over_0.5pt 41.07%
ci_low -1.18 pp
ci_high 1.88 pp

Plot: No.046: Calculating the posterior distribution of the difference between two probabilities

Interpreting the results

Not only is the observation rate of B low, but it can also be shown separately as the probability that B is superior and the probability that the improvement exceeds practical significance. Even if statistical advantage is high, if the improvement is small, the modification costs may not be recovered.

No.047: Creating Posterior Predictive Distributions

Practical meaning

The number of defects YY in the next mm items follows the beta-binomial posterior predictive distribution, Y∣x∼BetaBinomial(m,α′,β′)Y\mid x\sim\mathrm{BetaBinomial}(m,\alpha\prime,\beta\prime). Here each line’s next lot contains 200 items.

Model and assumptions

Calculate beta-binomial probabilities for counts from 0 to 200 using the updated beta parameters. The plot shows counts from 0 to 17 for readability.

Check with Python

[IN: 11]
future_n = 200
k = np.arange(future_n + 1)
predictive = {}
for line, row in post.iterrows():
    predictive[line] = betabinom.pmf(k, future_n, row.alpha, row.beta)

fig, ax = plt.subplots()
for line, pmf in predictive.items():
    ax.plot(k[:18], pmf[:18], marker="o", label=plot_label[line])
ax.set_title("Posterior predictive distribution for next 200 units")
ax.set_xlabel("Number of defects in next lot")
ax.set_ylabel("Predictive probability")
ax.grid(True, alpha=0.3)
ax.legend()
plt.tight_layout()
plt.show()
[OUT: 11]

Plot: No.047: Creating Posterior Predictive Distributions

Interpreting the results

The predicted distribution directly represents how many defects may occur in the next lot. For tasks planned by “quantity,” such as reserved space, re-inspection man-hours, and replacement inventory, the posterior predictive distribution is more suitable than the credible interval of the parameter.

No.048: Calculating Forecast Intervals

Practical meaning

The 95% prediction range is the range where defects in the next lot are expected to occur. This is not a credible interval for the defect rate parameter, but also includes binomial fluctuations observed in the future, so it is relatively broad.

Model and assumptions

Find the 2.5th and 97.5th predictive quantiles for the next 200 units, together with the probability of at least five defects. Because counts are discrete, interval coverage need not equal exactly 95%.

Check with Python

[IN: 12]
pred_rows = []
for line, row in post.iterrows():
    dist = betabinom(future_n, row.alpha, row.beta)
    pred_rows.append(
        {
            "line": line,
            "expected_defects": dist.mean(),
            "prediction_low": int(dist.ppf(0.025)),
            "prediction_high": int(dist.ppf(0.975)),
            "prob_5_or_more": dist.sf(4),
        }
    )
pred_summary = pd.DataFrame(pred_rows).set_index("line")
display(
    pred_summary.style.format(
        {"expected_defects": "{:.2f}", "prob_5_or_more": "{:.1%}"}
    )
)
[OUT: 12]
  expected_defects prediction_low prediction_high prob_5_or_more
line        
A(Current) 4.00 0 9 37.0%
B(Improvement candidate) 3.33 0 8 25.8%

Interpreting the results

By looking not only at the expected number of defects but also at the upper predicted points, you can design with more margins in personnel and re-inspection capacity. Simply saying, ‘Average 3 pieces, so only prepare 3 units’ cannot handle the upside fluctuations that normally occur.

No.049: Comparing Observations and Posterior Predictive Distributions

Practical meaning

Use posterior predictive checks to ask whether the model reproduces observed features. Here the statistic is the number of zero-defect days among 25 days of 20 inspections. An extreme observed value suggests checking day-to-day variation or other omitted structure.

Model and assumptions

Draw one defect rate for each replicated dataset and share it across 25 simulated days. Compare the number of zero-defect days with the observations. Cap the doubled smaller tail probability at 1 for this discrete diagnostic.

Check with Python

[IN: 13]
n_rep = 50_000
ppc_rows = []
fig, axes = plt.subplots(1, 2, figsize=(11, 4.2))
for ax, (line, row) in zip(axes, post.iterrows()):
    p_rep = rng.beta(row.alpha, row.beta, size=(n_rep, 1))
    replicated = rng.binomial(20, p_rep, size=(n_rep, 25))
    rep_zero_days = (replicated == 0).sum(axis=1)
    observed = daily[line].to_numpy()
    obs_zero_days = int((observed == 0).sum())
    ppc_rows.append(
        {
            "line": line,
            "observed_zero_days": obs_zero_days,
            "predictive_mean_zero_days": rep_zero_days.mean(),
            "two_sided_tail_area": min(
                1.0,
                2
                * min(
                    np.mean(rep_zero_days <= obs_zero_days),
                    np.mean(rep_zero_days >= obs_zero_days),
                ),
            ),
        }
    )
    ax.hist(rep_zero_days, bins=np.arange(-0.5, 26.5), alpha=0.75)
    ax.axvline(obs_zero_days, color="tab:red", linestyle="--", label="Observed")
    ax.set_title(f"PPC: {plot_label[line]}")
    ax.set_xlabel("Zero-defect days out of 25")
    ax.set_ylabel("Simulation frequency")
    ax.grid(True, alpha=0.3)
    ax.legend()
plt.tight_layout()
plt.show()
ppc = pd.DataFrame(ppc_rows).set_index("line")
display(
    ppc.style.format(
        {"predictive_mean_zero_days": "{:.1f}", "two_sided_tail_area": "{:.3f}"}
    )
)
[OUT: 13]

Plot: No.049: Comparing Observations and Posterior Predictive Distributions

  observed_zero_days predictive_mean_zero_days two_sided_tail_area
line      
A(Current) 16 16.8 0.897
B(Improvement candidate) 17 18.0 0.829

Interpreting the results

Check whether the red line is at the extreme end of the predicted distribution. This check does not prove the model is correct. If there is inconsistency, do not stick to a simple binomial model, but consider daily and equipment hierarchical structures and overdispersion.

No.050: Compiling Bayesian Estimation Results as a Report

Practical meaning

In the decision maker report, the method name indicates “conclusion, uncertainty, recommended action, assumptions” first. Below, we automatically generate a routine summary from the calculated values. A design that allows pre-rounding data for audit purposes is also desirable.

Model and assumptions

Combine the computed estimates, credible intervals, threshold probabilities, and predictions in one report. Round only for presentation and use unrounded samples for improvement probabilities.

Check with Python

[IN: 14]
report = pd.DataFrame(
    {
        "indicator": [
            "Posterior mean defect rate",
            "95% credible interval",
            "P(defect rate > 2%)",
            "Expected defects in next 200 items",
            "95% predictive interval for next 200 items",
        ],
        "A(Current)": [
            f"{post.loc['A(Current)','posterior_mean']:.2%}",
            f"{post.loc['A(Current)','ci_low']:.2%}–{post.loc['A(Current)','ci_high']:.2%}",
            f"{post.loc['A(Current)','prob_over_2pct']:.1%}",
            f"{pred_summary.loc['A(Current)','expected_defects']:.1f} defects",
            f"{pred_summary.loc['A(Current)','prediction_low']}–{pred_summary.loc['A(Current)','prediction_high']} defects",
        ],
        "B(Improvement candidate)": [
            f"{post.loc['B(Improvement candidate)','posterior_mean']:.2%}",
            f"{post.loc['B(Improvement candidate)','ci_low']:.2%}–{post.loc['B(Improvement candidate)','ci_high']:.2%}",
            f"{post.loc['B(Improvement candidate)','prob_over_2pct']:.1%}",
            f"{pred_summary.loc['B(Improvement candidate)','expected_defects']:.1f} defects",
            f"{pred_summary.loc['B(Improvement candidate)','prediction_low']}–{pred_summary.loc['B(Improvement candidate)','prediction_high']} defects",
        ],
    }
).set_index("indicator")
display(report)

recommendation = f"""### Summary for Quality Meetings (Fictitious Data)

- The posterior probability that B has a lower defect rate than A is **{np.mean(delta > 0):.1%}**.
- The probability that the improvement exceeds 0.5 percentage points is **{np.mean(delta > 0.005):.1%}**.
- Uncertainty remains. Before switching, run an additional comparison with the same product and inspection conditions.
- Set the adoption criteria before this comparison, using the costs of escaped defects and production stoppages.
"""
display(Markdown(recommendation))
[OUT: 14]
A(Current) B(Improvement candidate)
indicator
Posterior mean defect rate 2.00% 1.67%
95% credible interval 1.04%–3.26% 0.80%–2.83%
P(defect rate > 2%) 46.3% 24.2%
Expected defects in next 200 items 4.0 defects 3.3 defects
95% predictive interval for next 200 items 0–9 defects 0–8 defects

Summary for Quality Meetings (Fictitious Data)

  • The posterior probability that B has a lower defect rate than A is 67.1%.
  • The probability that the improvement exceeds 0.5 percentage points is 41.1%.
  • Uncertainty remains. Before switching, run an additional comparison with the same product and inspection conditions.
  • Set the adoption criteria before this comparison, using the costs of escaped defects and production stoppages.

Interpreting the results

A good report not only lists point estimation but also probability, intervals, operational thresholds, and next actions in the same table. Furthermore, this conclusion assumes binomial models, prior distribution, inspection independence, and inspection accuracy, and requires verification before applying them to actual processes.

Practical implications

  1. Representative values, intervals, and excess probabilities have different roles: KPIs should focus on posterior means, explanations should focus on credible intervals, and behavioral criteria should focus on threshold exceeding probabilities.
  2. Distinguishing the probability of a difference from its magnitude: The probability that Line B is superior alone does not determine the economic rationality of capital investment. Define the minimum practical difference.
  3. Use predictive distributions for future planning: Instead of parameter estimation, we design re-inspection personnel, inventory, and delivery risks based on the number of defective items in the next lot.
  4. Predictive checks are the entry point to operations.: If daily variations cannot be reproduced, explanatory variables and hierarchical structures such as variety, equipment, material lots, and work teams are examined.
  5. Converting probability into action requires costs: Decision-making rules only become after defining losses from outflows, stoppages, reinspections, switchings, and delivery delays.

Putting the analysis into practice

  • Standardize defect definitions, inspection units, populations, and measurement systems.
  • Define the target periods and similar processes for past data, and record the basis for prior distribution.
  • Confirm the independence of inspections, product composition, and heterogeneity by equipment, work teams, and material lots
  • Conduct sensitivity analysis with altered prior distribution and external verification over time series
  • Decide what to do if the probability of exceeding the standard is greater than what is the risk, including losses and those responsible.
  • Incorporate data updates, recalculations, approvals, version management, and audit logs into your workflow
  • If errors by inspectors or measuring instruments cannot be ignored, they are included in the observation model.

Conclusion

In No.041–050, we used a Beta-Binomial model to implement representative defect rates, credible intervals, probability of exceeding the standard, line differences, next lot prediction, forecast checks, and reporting. The value of Bayesian estimates is not in asserting that the defect rate is 1.8%, but in being able to make a common language about “how uncertain and which actions are reasonable.”

This example is a simplified starting point. In practice, by incorporating hierarchical factors such as day, equipment, variable, and material lots, time changes, inspection errors, and decision-making costs, we develop a system that can withstand on-site judgments.

Consultations for Corporations

At Surikobo, we support everything from Bayesian model design targeting manufacturing quality data, PoC, integration with existing KPIs, on-site training, to implementing regular reports and dashboards. You can consult with us from stages such as small data volumes, large differences between processes, or wanting to make threshold judgments explainable.

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