All articles →

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

Practice Quality Control in Manufacturing with Python | Defect Rate, Cp/Cpk, and 10 Control Charts Exerciseed

Use Python to estimate defect rates, assess Cp/Cpk, build control charts, and simulate quality losses with ten manufacturing exercises.

Turning Quality Data into “Judgment”: 10 Exercises on Manufacturing Probability and Statistics

This article uses fictional quality data from three production lines to calculate defect rates, process capability, control charts, hypothesis tests, failure rates, and next-month quality losses in Python. Each result helps identify which line to investigate, whether to reduce variation or correct centering, and how to plan inspection and quality-loss budgets.

The 100 exercises cover quality control, maintenance, demand, inventory, production planning, customer analytics, machine learning, decision science, simulation, and manufacturing DI. These first ten establish the quality-control foundations, using reproducible Python calculations that production, quality assurance, and management can review together.

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.

1. Introduction: Practical Challenges in Manufacturing Covered in This Article

In a fictional precision parts factory, three lines produce the same part. The critical dimension standard is 49.5〜50.5 mm, measuring 50 pieces per lot and inspecting 200 pieces per lot for visual inspection. Recently, customers have asked us to explain, “Is the defect rate stable?” “Is there a difference between lines?” and “How much loss could be next month?”

A low average defect rate can hide sudden problems, and a high Cp does not prevent defects if the process mean is off-center. Examine the current level, variation, changes over time, estimation uncertainty, and economic impact together.

2. Common Situations on Site

  • Only the monthly defect rate is reported, and it’s unclear when or where the situation worsened.
  • Cp and Cpk are confused, overlooking the state of ‘having equipment capacity but misaligned core’
  • Treating control limits and specification limits as the same
  • Identify the difference in a small sample as a process difference as it is.
  • Thresholds for anomaly detection and sampling inspection conditions are not linked to customer risk.
  • Planning is based solely on point estimates, without reflecting estimation errors or fluctuations in the next month in the budget.

3. Why is this issue difficult to judge?

Quality indicators have different roles. specification limit refers to the acceptable range required by customers and designers, while control limit refers to the range of fluctuations that typically occur during the stabilization process. Also, defect rates are estimates from finite samples and are not the true defect rates themselves. Therefore, it is necessary not only to choose between “exceeding the standard or not exceeding” but also to clearly state the data generation process, sample size, chronological order, and false positive costs.

4. Exercise Overview

No.ThemeKey Decisions
001Defect Rate EstimationPriority of improvement targets
002Process Capability Index cpThe Need to Reduce Variation
003Process Capability Index CpkDistinguishing between centering and equipment improvement
004control chartIdentification of Normal Fluctuations and Special Causes
005anomaly detectionNarrowing down the lot size to be investigated
006sampling inspectionDesigning inspection costs and leakage risks
007Quality Evaluation Using Confidence IntervalsExplanation including uncertainty in the estimate
008Process Comparison TestStatistical Confirmation of Line Difference
009Failure rate estimationMaintenance and Spare Parts Plan
010Quality SimulationProbabilistic budgeting of losses for the following month

5. Preparing the Python environment

Handle data with numpy and pandas, use scipy for statistics and matplotlib for visualization. Because it fixes random number seeds, the same result can be reproduced every time you run. To avoid font differences in execution environments, the notation within the graph is unified to English.

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]
%matplotlib inline
import sys
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from scipy import stats
from IPython.display import display

SEED = 20260711
rng = np.random.default_rng(SEED)
pd.set_option("display.precision", 4)

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

6. Creation of Fictional Data

For 120 lots (3 lines × 40 lots), we generate dimensional measurements, visual inspections, equipment operating hours, and the number of failures. For each line, the average, standard deviation, basic defect probability, and failure rate are slightly adjusted, and dimensional shifts due to special causes are added to some lots. This is a hypothetical setting to check the behavior of the analysis method.

variableMeaning
dimension_mmActual measurements of important dimensions (50 pieces per lot)
inspected / defectsNumber of Visual Inspections / Number of Defects
exposure_hours / failuresEquipment Operating Hours / Number of Failures
LSL, USLDimensions Standard Lower and Upper Limits
Synthetic-data setup code ([IN: 2])
[IN: 2]
LSL, TARGET, USL = 49.5, 50.0, 50.5
n_lots, sample_per_lot, inspected_per_lot = 120, 50, 200
lines = np.tile(["A", "B", "C"], n_lots // 3)
dates = pd.date_range("2026-01-05", periods=n_lots, freq="D")

line_mean = {"A": 50.00, "B": 50.12, "C": 49.94}
line_sigma = {"A": 0.12, "B": 0.16, "C": 0.10}
base_defect_p = {"A": 0.007, "B": 0.015, "C": 0.009}
failure_rate = {"A": 1 / 1400, "B": 1 / 650, "C": 1 / 2200}
special_shift = {41: 0.32, 76: -0.28, 102: 0.35}  # Lot position starting from 0

lot_rows, measurement_rows = [], []
for i, (date, line) in enumerate(zip(dates, lines)):
    mu = line_mean[line] + special_shift.get(i, 0.0)
    values = rng.normal(mu, line_sigma[line], sample_per_lot)
    p = min(
        base_defect_p[line]
        + 0.035 * abs(mu - TARGET)
        + (0.03 if i in special_shift else 0),
        0.20,
    )
    defects = rng.binomial(inspected_per_lot, p)
    exposure = int(rng.integers(650, 951))
    failures = rng.poisson(exposure * failure_rate[line])
    lot_id = f"L{i + 1:03d}"
    lot_rows.append(
        (
            lot_id,
            date,
            line,
            inspected_per_lot,
            defects,
            exposure,
            failures,
            values.mean(),
            values.std(ddof=1),
        )
    )
    measurement_rows.extend((lot_id, date, line, x) for x in values)

lot_df = pd.DataFrame(
    lot_rows,
    columns=[
        "lot_id",
        "date",
        "line",
        "inspected",
        "defects",
        "exposure_hours",
        "failures",
        "dimension_mean",
        "dimension_std",
    ],
)
measurements = pd.DataFrame(
    measurement_rows, columns=["lot_id", "date", "line", "dimension_mm"]
)
lot_df["defect_rate"] = lot_df["defects"] / lot_df["inspected"]

print(
    f"lot_size: {len(lot_df):,} / Dimensional measurement quantity: {len(measurements):,}"
)
display(lot_df.head())
[OUT: 2]
lot_size: 120 / Dimensional measurement quantity: 6,000
lot_id date line inspected defects exposure_hours failures dimension_mean dimension_std defect_rate
0 L001 2026-01-05 A 200 1 887 1 49.9851 0.1170 0.005
1 L002 2026-01-06 B 200 6 874 1 50.1248 0.1722 0.030
2 L003 2026-01-07 C 200 2 798 1 49.9519 0.1064 0.010
3 L004 2026-01-08 A 200 4 779 1 49.9892 0.1213 0.020
4 L005 2026-01-09 B 200 1 720 2 50.1023 0.1498 0.005

7. No.001: Defect Rate Estimation

Practical Purpose

The defect rate is the entry point for quality cost, shipment evaluation, and selection of improvement themes. However, if you simply average the defect rates by line, the number of inspections may be incorrect if the number of inspections differs. The basic calculation is based on “total defects ÷ total number of inspections.”

Method and Assumptions

Assuming independent inspections with the same defect probability pp, the defect count among nn inspected units follows X∼Binomial(n,p)X\sim\mathrm{Binomial}(n,p). Its maximum-likelihood estimate is

p^=Xn\hat{p}=\frac{X}{n}

First, we estimate points by line and examine the number of contributing defects to identify factors worsening the overall KPI.

Check with Python

[IN: 3]
defect_summary = lot_df.groupby("line").agg(
    lots=("lot_id", "count"), inspected=("inspected", "sum"), defects=("defects", "sum")
)
defect_summary["defect_rate_pct"] = (
    100 * defect_summary["defects"] / defect_summary["inspected"]
)
defect_summary["defect_share_pct"] = (
    100 * defect_summary["defects"] / defect_summary["defects"].sum()
)
display(defect_summary)

ax = defect_summary["defect_rate_pct"].plot(
    kind="bar", color=["#4C78A8", "#F58518", "#54A24B"], legend=False
)
ax.set_title("Estimated Defect Rate by Line")
ax.set_xlabel("Line")
ax.set_ylabel("Defect rate (%)")
ax.grid(axis="y", alpha=0.3)
plt.tight_layout()
plt.show()
[OUT: 3]
lots inspected defects defect_rate_pct defect_share_pct
line
A 40 8000 61 0.7625 18.8272
B 40 8000 171 2.1375 52.7778
C 40 8000 92 1.1500 28.3951

7. No.001: Defect Rate Estimation: result chart

Interpreting the Results

Line B contributes significantly to both defect rates and defect numbers, making it the top candidate for improvement. However, point estimation alone cannot distinguish between accidental fluctuations. Combine the confidence interval No.007 and the test of No.008 to verify the certainty of the difference.

8. No.002: Process Capability Index Cp

Practical Purpose

Cp indicates whether the process can be processed with sufficiently small variation relative to the standard width. These are the criteria for making decisions on investments that reduce variation, such as equipment upgrades, jig improvements, and standardization of conditions.

Method and Assumptions

When the process is stable and the dimensions generally follow a normal distribution,

Cp=USL−LSL6sC_p=\frac{USL-LSL}{6s}

6s6s spans three standard deviations on either side of the mean. Cp measures capability based on variation without accounting for centering. Here we exclude the three known special-cause lots and use the standard deviation of the remaining measurements under the simulated assumption of a constant mean and variance within each line. With real between-lot variation, distinguish Cp/Cpk based on within-subgroup variation from Pp/Ppk based on overall variation.

Check with Python

[IN: 4]
special_lots = {"L042", "L077", "L103"}
baseline = measurements.loc[~measurements["lot_id"].isin(special_lots)].copy()
capability = baseline.groupby("line")["dimension_mm"].agg(mean="mean", std="std")
capability["Cp"] = (USL - LSL) / (6 * capability["std"])
display(capability)

ax = capability["Cp"].plot(kind="bar", color="#4C78A8", legend=False)
ax.axhline(1.33, color="#E45756", linestyle="--", label="Reference 1.33")
ax.set_title("Potential Process Capability (Cp)")
ax.set_xlabel("Line")
ax.set_ylabel("Cp")
ax.grid(axis="y", alpha=0.3)
ax.legend()
plt.tight_layout()
plt.show()
[OUT: 4]
mean std Cp
line
A 50.0002 0.1182 1.4100
B 50.1127 0.1612 1.0341
C 49.9389 0.0986 1.6895

8. No.002: Process Capability Index Cp: result chart

Interpreting the Results

Line B has a larger standard deviation than other lines, indicating a lower potential process capability. The commonly used 1.33 is only a reference line, and the adoption criteria are set according to product risks and customer requirements. The next challenge is that CP alone cannot assess center deviation.

9. No.003: Process Capability Index Cpk

Practical Purpose

Cpk expresses how much margin there is to the specification limit on the closer side of the process average, in addition to variation. If the Cp is good but the Cpk is low, you can prioritize suspicion of center misalignment due to set values, correction values, and tool wear rather than the equipment capacity itself.

Method and Assumptions

Cpk=min⁡(USL−xˉ3s,xˉ−LSL3s)C_{pk}=\min\left(\frac{USL-\bar{x}}{3s},\frac{\bar{x}-LSL}{3s}\right)

The gap between Cp and Cpk indicates how far the process mean is from the specification midpoint. Both require a stable process; investigate special causes before selecting the reference period.

Check with Python

[IN: 5]
capability["Cpu"] = (USL - capability["mean"]) / (3 * capability["std"])
capability["Cpl"] = (capability["mean"] - LSL) / (3 * capability["std"])
capability["Cpk"] = capability[["Cpu", "Cpl"]].min(axis=1)
capability["Cp_minus_Cpk"] = capability["Cp"] - capability["Cpk"]
display(capability[["mean", "std", "Cp", "Cpk", "Cp_minus_Cpk"]])

ax = capability[["Cp", "Cpk"]].plot(kind="bar", color=["#4C78A8", "#F58518"])
ax.set_title("Cp and Cpk by Line")
ax.set_xlabel("Line")
ax.set_ylabel("Capability index")
ax.grid(axis="y", alpha=0.3)
plt.tight_layout()
plt.show()
[OUT: 5]
mean std Cp Cpk Cp_minus_Cpk
line
A 50.0002 0.1182 1.4100 1.4094 0.0006
B 50.1127 0.1612 1.0341 0.8010 0.2331
C 49.9389 0.0986 1.6895 1.4830 0.2065

9. No.003: Process Capability Index Cpk: result chart

Interpreting the Results

At line B, the Cpk is even lower than Cp, with both deviation and upward center deviation. Line C also has its center shifting downward, so reporting only Cp underestimates the risk. In the short term, you can break down measures such as centering and analyzing the variation factors in line B as a permanent countermeasure.

10. No.004: Control Chart

Practical Purpose

A control chart is a tool that distinguishes between ‘normal fluctuations inherent in the process’ and ‘special causes that need to be investigated’ based on the time-series changes in defect rates. Starting from lots exceeding control limits, we examine the history of changes in materials, equipment, operations, measurements, and environments.

Method and Assumptions

For a p-chart with a constant inspection sample size, estimate pˉ\bar p from reference lots on the same line and use the following control limits.

UCL=min⁡(1,pˉ+3pˉ(1−pˉ)n),LCL=max⁡(0,pˉ−3pˉ(1−pˉ)n).\begin{aligned} UCL&=\min\left(1,\bar p+3\sqrt{\frac{\bar p(1-\bar p)}{n}}\right),\\ LCL&=\max\left(0,\bar p-3\sqrt{\frac{\bar p(1-\bar p)}{n}}\right). \end{aligned}

Control limits describe expected variation in a stable process; they are separate from customer specifications. We exclude the three known special-cause lots when estimating the limits and plot each line separately. In operation, use a reference period validated by investigation. Because defect counts are small, the three-sigma limits are approximate; binomial probability limits may be more suitable. See the NIST explanation of p-charts.

Check with Python

[IN: 6]
# Estimate separate limits from reference lots on each line.
reference = lot_df.loc[~lot_df["lot_id"].isin(special_lots)]
line_totals = reference.groupby("line")[["defects", "inspected"]].sum()
p_bar_by_line = line_totals["defects"] / line_totals["inspected"]
lot_df["p_center"] = lot_df["line"].map(p_bar_by_line)
sigma_p = np.sqrt(lot_df["p_center"] * (1 - lot_df["p_center"]) / lot_df["inspected"])
lot_df["p_ucl"] = (lot_df["p_center"] + 3 * sigma_p).clip(upper=1)
lot_df["p_lcl"] = (lot_df["p_center"] - 3 * sigma_p).clip(lower=0)
lot_df["p_chart_signal"] = (lot_df["defect_rate"] > lot_df["p_ucl"]) | (
    lot_df["defect_rate"] < lot_df["p_lcl"]
)

fig, axes = plt.subplots(3, 1, figsize=(11, 8), sharex=True)
for ax, (line, group) in zip(axes, lot_df.groupby("line")):
    ax.plot(
        group["date"], 100 * group["defect_rate"], marker="o", markersize=3, linewidth=1
    )
    for column, label, color, style in [
        ("p_center", "Center line", "#54A24B", "-"),
        ("p_ucl", "UCL", "#E45756", "--"),
        ("p_lcl", "LCL", "#E45756", "--"),
    ]:
        ax.plot(
            group["date"],
            100 * group[column],
            color=color,
            linestyle=style,
            label=label,
        )
    signals = group.loc[group["p_chart_signal"]]
    ax.scatter(
        signals["date"],
        100 * signals["defect_rate"],
        color="red",
        s=45,
        zorder=3,
        label="Signal",
    )
    ax.set_title(f"Line {line }: p-Chart for Lot Defect Rate")
    ax.set_ylabel("Defect rate (%)")
    ax.grid(alpha=0.3)
    ax.legend(ncol=4, fontsize=8)
axes[-1].set_xlabel("Production date")
plt.tight_layout()
plt.show()
signals = lot_df.loc[lot_df["p_chart_signal"]]
display(signals[["lot_id", "date", "line", "defects", "defect_rate"]])
[OUT: 6]

10. No.004: Control Chart: result chart

lot_id date line defects defect_rate
21 L022 2026-01-26 A 5 0.025
41 L042 2026-02-15 C 8 0.040
102 L103 2026-04-17 A 8 0.040

Interpreting the Results

Defective points are candidates that are difficult to explain purely by chance from the perspective of the standard process. Exceeding the control limit is not a “defective product confirmation” but a “signal to investigate a special cause.” Conversely, even within management, customer standards cannot be guaranteed, so control charts and process capabilities are used together.

11. No.005: Anomaly Detection

Practical Purpose

When monitoring numerous sensors and quality characteristics, it is difficult to manually monitor all changes. By narrowing down investigation candidates with abnormality scores, quality personnel can focus on identifying the cause.

Method and Assumptions

Compute the median mm and MAD (median absolute deviation from the median) of lot means separately for each line. The resulting robust z-score avoids treating ordinary differences in mean dimensions between lines as anomalies.

zi(robust)=0.6745(xi−m)median(∣xi−m∣)z_i^{(robust)}=\frac{0.6745(x_i-m)}{\mathrm{median}(|x_i-m|)}

This method is less affected by outliers than the Z-Score based on the mean or standard deviation. ∣z∣>3.5|z|>3.5 is considered a candidate for primary investigation, but the threshold is designed based on missed and false alarm response costs.

Check with Python

[IN: 7]
def within_line_robust_z(series):
    median = series.median()
    mad = np.median(np.abs(series - median))
    if mad == 0:
        raise ValueError("MAD is zero; a robust z-score is undefined.")
    return 0.6745 * (series - median) / mad


lot_df["robust_z"] = lot_df.groupby("line")["dimension_mean"].transform(
    within_line_robust_z
)
anomalies = lot_df.loc[lot_df["robust_z"].abs() > 3.5]

fig, ax = plt.subplots(figsize=(11, 4))
ax.plot(lot_df["date"], lot_df["robust_z"], color="#4C78A8", linewidth=1)
ax.axhline(3.5, color="#E45756", linestyle="--")
ax.axhline(-3.5, color="#E45756", linestyle="--")
ax.scatter(anomalies["date"], anomalies["robust_z"], color="red", s=45, zorder=3)
ax.set_title("Robust Anomaly Score for Lot Mean")
ax.set_xlabel("Production date")
ax.set_ylabel("Robust z-score")
ax.grid(alpha=0.3)
plt.tight_layout()
plt.show()
display(anomalies[["lot_id", "date", "line", "dimension_mean", "robust_z"]])
[OUT: 7]

11. No.005: Anomaly Detection: result chart

lot_id date line dimension_mean robust_z
41 L042 2026-02-15 C 50.2693 20.1432
76 L077 2026-03-22 B 49.8470 -11.8641
102 L103 2026-04-17 A 50.3314 20.3775

Interpreting the Results

Lots with special shifts are extracted as the highest score. In actual operation, after detection, the history of raw material lots, tool changes, temperature and humidity, workers, and instrument calibration is automatically linked, and alerts lead to identifying the cause. The model shows not the cause, but the priority of the investigation.

12. No.006: Acceptance Sampling

Practical Purpose

If the full inspection is expensive or destructive, a portion is removed from the lot to determine whether it passes or fails. The number of samples nn and the number of passing cc determine not only inspection man-hours but also the producer risk of rejecting good lots and the consumer risk of passing through bad lots.

Method and Assumptions

For a sufficiently large lot with defect rate pp, sample nn units and accept the lot if at most cc are defective. The acceptance probability is

P(accept∣p)=∑x=0c(nx)px(1−p)n−xP(\mathrm{accept}\mid p)=\sum_{x=0}^{c}{n\choose x}p^x(1-p)^{n-x}

The OC curve is the representation of this pass probability relative to the defect rate. In finite lots, a hypergeometric distribution reflecting sampling without replacement is used.

Check with Python

[IN: 8]
plans = [(50, 1), (80, 1), (80, 2)]
p_grid = np.linspace(0, 0.10, 201)

fig, ax = plt.subplots(figsize=(8, 4.5))
for n, c in plans:
    accept_prob = stats.binom.cdf(c, n, p_grid)
    ax.plot(100 * p_grid, 100 * accept_prob, label=f"n={n}, c={c}")
ax.axvline(1, color="gray", linestyle=":", label="AQL example: 1%")
ax.axvline(5, color="black", linestyle=":", label="LQ example: 5%")
ax.set_title("Operating Characteristic Curves")
ax.set_xlabel("Lot defect rate (%)")
ax.set_ylabel("Probability of acceptance (%)")
ax.grid(alpha=0.3)
ax.legend()
plt.tight_layout()
plt.show()

plan_table = pd.DataFrame(
    [
        {
            "n": n,
            "c": c,
            "P_accept_at_1%": stats.binom.cdf(c, n, 0.01),
            "P_accept_at_5%": stats.binom.cdf(c, n, 0.05),
        }
        for n, c in plans
    ]
)
display(plan_table)
[OUT: 8]

12. No.006: Acceptance Sampling: result chart

n c P_accept_at_1% P_accept_at_5%
0 50 1 0.9106 0.2794
1 80 1 0.8092 0.0861
2 80 2 0.9534 0.2306

Interpreting the Results

If you increase the number of samples and make the pass judgment stricter, the probability of passing a bad lot decreases, but the chances of rejecting good lots and the cost of testing increase. AQL and LQ need to be aligned with contracts, usage, and loss amounts, making the OC curve a common language for both customers and suppliers.

13. No.007: Quality Evaluation Using Confidence Intervals

Practical Purpose

The estimation of a “defect rate of 1%” has different meanings between 200 inspections and 20,000 inspections. Including confidence intervals helps determine whether additional inspections are needed and how wide you should explain to customers.

Method and Assumptions

The Wilson interval estimates a binomial proportion and is more reliable than a simple normal interval when defect counts are small. It uses z=z1−α/2z=z_{1-\alpha/2} and adjusts both the center and half-width. A 95% confidence level describes repeated-sampling coverage, rather than a 95% posterior probability for this particular interval. Here, pooling within a line treats its defect probability as constant; investigate special-cause lots before using that assumption operationally.

Check with Python

[IN: 9]
def wilson_interval(x, n, alpha=0.05):
    z = stats.norm.ppf(1 - alpha / 2)
    phat = x / n
    denom = 1 + z**2 / n
    center = (phat + z**2 / (2 * n)) / denom
    half = z * np.sqrt(phat * (1 - phat) / n + z**2 / (4 * n**2)) / denom
    return center - half, center + half


ci_rows = []
for line, row in defect_summary.iterrows():
    low, high = wilson_interval(int(row["defects"]), int(row["inspected"]))
    ci_rows.append((line, row["defects"] / row["inspected"], low, high))
ci_df = pd.DataFrame(
    ci_rows, columns=["line", "estimate", "ci_low", "ci_high"]
).set_index("line")
display(100 * ci_df)

fig, ax = plt.subplots(figsize=(7, 4))
y = np.arange(len(ci_df))
ax.errorbar(
    100 * ci_df["estimate"],
    y,
    xerr=[
        100 * (ci_df["estimate"] - ci_df["ci_low"]),
        100 * (ci_df["ci_high"] - ci_df["estimate"]),
    ],
    fmt="o",
    capsize=4,
    color="#4C78A8",
)
ax.set_yticks(y, ci_df.index)
ax.set_title("Defect Rate with 95% Wilson Interval")
ax.set_xlabel("Defect rate (%)")
ax.set_ylabel("Line")
ax.grid(axis="x", alpha=0.3)
plt.tight_layout()
plt.show()
[OUT: 9]
estimate ci_low ci_high
line
A 0.7625 0.5941 0.9782
B 2.1375 1.8428 2.4782
C 1.1500 0.9387 1.4082

13. No.007: Quality Evaluation Using Confidence Intervals: result chart

Interpreting the Results

The horizontal lines at each point indicate the estimated error. If the range is wide, it is risky to decide on large investments based solely on the estimated ranking of points. On the other hand, if the section of Line B is located on the higher side than the others, suspicion of a process difference increases. Next, explicitly test whether the difference can be explained by chance.

14. No.008: Process Comparison Test

Practical Purpose

When assessing the effects of line changes, equipment upgrades, or supplier switching, it is necessary to distinguish between observed and reproducible differences. The test evaluates how unlikely it is that such a difference is possible under the hypothesis of “no difference.”

Method and Assumptions

For the defect rates of lines A and B, a two-sample ratio z-test is conducted for null hypothesis H0:pA=pBH_0:p_A=p_B and alternative hypothesis H1:pA≠pBH_1:p_A\ne p_B. The statistics using pooled proportion p^\hat p are

z=p^A−p^Bp^(1−p^)(1/nA+1/nB)z=\frac{\hat p_A-\hat p_B}{\sqrt{\hat p(1-\hat p)(1/n_A+1/n_B)}}

The p-value is not about the magnitude of the difference or the business value itself. Defect rate differences and relative risk are also recorded as effect sizes, and judged at a predetermined significance level of 5%.

Check with Python

[IN: 10]
a = defect_summary.loc["A"]
b = defect_summary.loc["B"]
p_a, p_b = a["defects"] / a["inspected"], b["defects"] / b["inspected"]
p_pool = (a["defects"] + b["defects"]) / (a["inspected"] + b["inspected"])
se = np.sqrt(p_pool * (1 - p_pool) * (1 / a["inspected"] + 1 / b["inspected"]))
z_stat = (p_a - p_b) / se
p_value = 2 * stats.norm.sf(abs(z_stat))

comparison = pd.DataFrame(
    {
        "metric": [
            "A defect rate",
            "B defect rate",
            "B - A (percentage points)",
            "B/A relative risk",
            "z statistic",
            "two-sided p-value",
        ],
        "value": [p_a, p_b, 100 * (p_b - p_a), p_b / p_a, z_stat, p_value],
    }
)
display(comparison)
print(
    "5%Level Determination:",
    (
        "There are statistical differences between the lines."
        if p_value < 0.05
        else "We cannot conclude that there is a difference."
    ),
)
[OUT: 10]
metric value
0 A defect rate 7.6250e-03
1 B defect rate 2.1375e-02
2 B - A (percentage points) 1.3750e+00
3 B/A relative risk 2.8033e+00
4 z statistic -7.2748e+00
5 two-sided p-value 3.4696e-13
5%Level Determination: There are statistical differences between the lines.

Interpreting the Results

If the p-value is less than 5%, it is unlikely that the current difference occurred from processes with the same defect rate. However, if the line, materials, product types, or working conditions are mixed, it cannot be definitively determined that the line itself is the cause. Add stratified aggregation and planned comparative trials, prioritizing both statistically significant differences and the monetary effect of improvements.

15. No.009: Failure Rate Estimation

Practical Purpose

Equipment failures simultaneously cause quality fluctuations, downtime losses, and delivery delays. By using the failure rate divided not only by the number of failures but also by operating hours, you can compare lines with different operating volumes and connect to spare parts, maintenance personnel, and renewal plans.

Method and Assumptions

Assume a Poisson process with constant failure rate λ\lambda. If KK failures occur over total operating time TT, the maximum-likelihood estimates of the failure rate and mean time between failures (MTBF) are as follows. Operating time here is the sum of operating hours across the equipment on each line.

λ^=KTMTBF^=1λ^=TK\begin{gathered} \hat\lambda=\frac{K}{T}\\ \widehat{MTBF}=\frac{1}{\hat\lambda}=\frac{T}{K} \end{gathered}

Since the estimation error is large when the number of failures is small, we also show a 95% confidence interval for the failure rate based on the chi-square distribution. For wear failures where the failure rate changes over time, it is necessary to use methods such as Weibull analysis rather than a constant rate model.

Check with Python

[IN: 11]
reliability = lot_df.groupby("line").agg(
    exposure_hours=("exposure_hours", "sum"), failures=("failures", "sum")
)
reliability["failures_per_1000h"] = (
    1000 * reliability["failures"] / reliability["exposure_hours"]
)
reliability["estimated_MTBF_h"] = (
    reliability["exposure_hours"] / reliability["failures"]
)
alpha = 0.05
reliability["rate_ci_low_per_1000h"] = [
    1000 * (0 if k == 0 else stats.chi2.ppf(alpha / 2, 2 * k) / (2 * t))
    for k, t in zip(reliability["failures"], reliability["exposure_hours"])
]
reliability["rate_ci_high_per_1000h"] = [
    1000 * stats.chi2.ppf(1 - alpha / 2, 2 * (k + 1)) / (2 * t)
    for k, t in zip(reliability["failures"], reliability["exposure_hours"])
]
display(reliability)

ax = reliability["failures_per_1000h"].plot(kind="bar", color="#B279A2", legend=False)
ax.set_title("Estimated Equipment Failure Rate")
ax.set_xlabel("Line")
ax.set_ylabel("Failures per 1,000 hours")
ax.grid(axis="y", alpha=0.3)
plt.tight_layout()
plt.show()
[OUT: 11]
exposure_hours failures failures_per_1000h estimated_MTBF_h rate_ci_low_per_1000h rate_ci_high_per_1000h
line
A 32204 23 0.7142 1400.1739 0.4527 1.0716
B 31725 58 1.8282 546.9828 1.3882 2.3634
C 32193 17 0.5281 1893.7059 0.3076 0.8455

15. No.009: Failure Rate Estimation: result chart

Interpreting the Results

Line B also has a high failure rate, and both poor quality and equipment condition may be poor at the same time. However, if confidence intervals overlap, you should not conclude renewal investments based solely on short-term transaction counts. Failure modes, downtime, repair costs, and impact on quality are accumulated at the equipment ID level, advancing toward risk-based maintenance.

16. No.010: Quality Simulation

Practical Purpose

A plan based solely on average values cannot secure sorting personnel, disposal costs, or customer service costs during upward swings. By using Monte Carlo simulations to distribute defects and losses for the following month, you can link your budget with your risk tolerance.

Method and Assumptions

Use a beta-binomial predictive model: a Beta distribution represents uncertainty in the defect probability, and a binomial distribution generates future defects conditional on that probability. A uniform prior p∼Beta(1,1)p\sim\mathrm{Beta}(1,1) and observations of xx defects among nn units give

p∣x,n∼Beta(1+x,1+n−x)p\mid x,n\sim\mathrm{Beta}(1+x,1+n-x)

Draw pp in each trial, then generate the number of defects among NN units next month. This is a pooled-rate approximation that assumes the production mix across lines stays unchanged. A forecast that accounts for line differences and between-lot variation should simulate defects for each line and sum them.

Check with Python

[IN: 12]
sim_rng = np.random.default_rng(SEED + 10)
observed_x = int(lot_df["defects"].sum())
observed_n = int(lot_df["inspected"].sum())
next_month_units = 300_000
unit_loss_yen = 4_500
n_sim = 20_000

sim_p = sim_rng.beta(1 + observed_x, 1 + observed_n - observed_x, n_sim)
sim_defects = sim_rng.binomial(next_month_units, sim_p)
sim_loss_yen = sim_defects * unit_loss_yen

simulation_summary = pd.Series(
    {
        "expected_defects": sim_defects.mean(),
        "median_defects": np.median(sim_defects),
        "P90_defects": np.quantile(sim_defects, 0.90),
        "P95_defects": np.quantile(sim_defects, 0.95),
        "expected_loss_yen": sim_loss_yen.mean(),
        "P95_loss_yen": np.quantile(sim_loss_yen, 0.95),
    }
)
display(simulation_summary.to_frame("value"))

fig, ax = plt.subplots(figsize=(8, 4.5))
ax.hist(sim_loss_yen / 1_000_000, bins=40, color="#4C78A8", edgecolor="white")
ax.axvline(
    np.quantile(sim_loss_yen, 0.95) / 1_000_000,
    color="#E45756",
    linestyle="--",
    label="95th percentile",
)
ax.set_title("Simulated Monthly Quality Loss")
ax.set_xlabel("Quality loss (million JPY)")
ax.set_ylabel("Simulation count")
ax.grid(axis="y", alpha=0.3)
ax.legend()
plt.tight_layout()
plt.show()
[OUT: 12]
value
expected_defects 4.0601e+03
median_defects 4.0570e+03
P90_defects 4.3660e+03
P95_defects 4.4520e+03
expected_loss_yen 1.8270e+07
P95_loss_yen 2.0034e+07

16. No.010: Quality Simulation: result chart

Interpreting the Results

Average loss is the budget standard, and the 95th percentile can be used for stricter resource planning. The post-countermeasure defect rate scenario is calculated using the same framework, and by comparing the reduction loss against the countermeasure cost, it becomes an investment valuation. Note that if there is correlation between lots or sudden process changes, the simple model underestimates the tail risk, so backtesting against actual results is necessary.

17. Using the Results in Practice

Throughout the 10 points, the key is not to use metrics in isolation.

  1. Defect Rate and Confidence Intervals, grasp current levels and estimated errors
  2. Control charts and anomaly detection, find special causes in time
  3. Cp and Cpk to separate variation and deviation
  4. Certification, check if the line difference can be explained purely by chance.
  5. sampling inspection to clearly define testing load and leakage risk
  6. Connect quality and equipment maintenance data with failure rate
  7. Simulation translates quality KPIs into loss amounts and required resources.

In this order, decisions proceed from the point that “Line B is at fault” to “Center correction, variation reduction, and equipment inspection—at what cost, and to what risk level?“

18. What is necessary for practical implementation

  • Definition unification: Deficiencies and aggregation granularity for defects, rework, disposal, inspection parameters, and stoppages
  • traceability: Connect products, lots, equipment, tools, materials, working conditions, and measuring instruments with keys
  • Measurement Reliability: Check Gage R&R and calibration history to avoid confusing measurement errors with process variations.
  • Managing the Reference Period: After process changes, review the control limits and capability index reference periods
  • Alert Operation: Streamline the workflow from post-detection assignment, deadline, cause classification, corrective actions, to effectiveness confirmation
  • Decision-making criteria: Quantify the costs associated with false alarms, missed alerts, spills, stoppages, and inspections.
  • Model Monitoring: Regularly verify distribution assumptions, independence, and coverage rates of forecast intervals

19. Summary

The example examines line B’s defect rate, dimensional variation, centering, and failure rate. Control charts and anomaly scores identify lots to investigate; capability indices and tests help assess improvements. Acceptance probabilities and the distribution of next-month losses then inform inspection settings and budgets.

Although this notebook’s hypothetical example is small-scale, in practice its value increases by connecting product hierarchies, process paths, equipment status, costs, and customer impact. It is practical to start by selecting one important quality characteristic, refine the definition and data granularity, and begin with small-scale operations of control charts and improvement actions.

20. Consultations for Corporations

At Surikobo, we support each company’s data and decision-making processes, covering everything from quality KPI design, process capability evaluation, anomaly detection, equipment maintenance, quality loss simulation, to implementation of analytical platforms. In addition to training, you can also consult about analysis and operational design that can be continuously used on-site.

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