100 Exercises / Probability Statistics / Probability & Statistics: Python 100 Exercises
Manufacturing Quality and Production Risk with NumPy: 10 Python Exercises
Use NumPy to analyze production, defect rates, and dimensions, then simulate monthly profit risk with reproducible manufacturing examples.
This is the first part of a 100-exercise series on probability and statistics in Python. The series covers NumPy, probability distributions, visualization, descriptive statistics, estimation, hypothesis testing, regression, Bayesian statistics, time series, and simulation. We use production and quality data to practice calculations that support decisions about capacity, inventory, and maintenance.
Exercises No.001–010 use a fictional precision parts factory to introduce NumPy arrays, simulation, and computational performance. We start with daily production by line, then estimate dimensional variation and the probability of missing a monthly profit target.
[!NOTE] This material is a notebook previously used by Surikobo (or personally by its representative, Hiroshi Wayama), and has been reconstructed, edited, and published with the company’s permission.
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
A precision parts factory records production, dimensions, defects, and downtime for each line. The analysis must answer concrete questions: how far is the process mean from the target, how likely is next month’s profit to miss the plan, and can the calculations finish in time for daily reporting?
This notebook generates production results for 3 lines and 30 days, along with dimensional measurements obtained from each line. It clearly defines the shape of the array, uses element-specific calculations and matrix operations differently, and implements everything in a continuous sequence to create future scenarios using random numbers.
Common situations on site
- Even though production volumes differ by line, they compare quality based solely on the number of defects.
- The process of applying product-specific standard values to each measurement is now copy-and-paste spreadsheets
- Each time I run a random number simulation, the results change, and the numbers cannot be reproduced during the review.
- Averages are reported, but the margins of distribution or the ‘probability of falling below the standard’ are not shared
- Loop processing becomes prolonged, making daily analysis and scenario comparison operations unestablished
First define what each row and column represents. Then use consistent aggregation axes and random-number settings to compare lines and reproduce the results.
Why is this issue so difficult to judge?
Manufacturing data consists of multiple axes, including days, lines, products, and measurement items. If you misalign the axis of the array, the code will move but the tallying will have different meanings. Also, since future production volumes and defect numbers are not finalized, downside risks cannot be grasped based solely on average scenarios.
Furthermore, the simulation results are samples of random numbers. Without recording the number of trials, random seeds, and assumed distributions, it is impossible to reproduce the results or verify their validity. In this notebook, the shape, aggregation axis, units, and random number generator for each array are intentionally displayed.
Exercises in this article
| No. | Theme | Questions in the Manufacturing Industry |
|---|---|---|
| 001 | Creating a NumPy array | How to express the production by day and line |
| 002 | vector operation | Can we compare quality by leveling differences in production scale? |
| 003 | matrix operation | Can daily performance be consolidated by week or line in bulk? |
| 004 | Broadcasting | Can line-specific standards be safely applied all day? |
| 005 | random number generation | How to simulate unknown measurements and stop times |
| 006 | random number seed | Can a third party reproduce the analysis results? |
| 007 | Histogram Drawing | Can you read the variation and tails hidden by averages? |
| 008 | Drawing the Cumulative Distribution Function | Can you directly read the percentage of values below the standard value? |
| 009 | Monte Carlo Simulation | Can you estimate the probability of monthly profits falling downward? |
| 010 | Computational Speed Comparison | Can you calculate large-scale scenarios within the operational time? |
No.001 to No.004 cover data structures and deterministic calculations, No.005 to No.009 deal with the generation, visualization, and evaluation of uncertainty, and No.010 address computational efficiency necessary for continuous operation.
Preparing the Python environment
Run the cells from top to bottom. [IN: n] and [OUT: n] identify the input and output of the same cell. Expand the preparation sections to see their code. Timings and the last digits of stochastic estimates can vary by environment.
It does not rely on external data and uses numpy, pandas, and matplotlib. Load japanize_matplotlib to display Japanese labels. For random numbers, NumPy Generator is used to manage the reference seed in one place.
Imports and display settings
import sys
import timeit
import japanize_matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
pd.set_option("display.max_colwidth", None)
from IPython.display import display
SEED = 20260711
rng = np.random.default_rng(SEED)
np.set_printoptions(precision=3, suppress=True)
pd.options.display.float_format = "{:,.3f}".format
print(f"Python: {sys.version.split()[0]}")
print(f"NumPy: {np.__version__}")
print(f"random number seed: {SEED}")
Python: 3.14.4
NumPy: 2.5.1
random number seed: 20260711
Creation of Fictional Data
Suppose the factory has three lines—A, B, and C—and operates for 30 days. Daily production volume varies by day of the week and line capacity, while defect counts are generated from production volume and the base defect rate per line. Additionally, for parts with a nominal dimension of 10.00 mm, we create measurements for 500 pieces per line.
This generative model does not claim a real-world causal structure. This is a common scenario for comparing calculation methods, and when applied in practice, assumptions are redesigned to include equipment history, product type, lot, material, measuring instruments, and so on.
Generate and inspect the fictional data
days = np.arange(1, 31)
lines = np.array(["A", "B", "C"])
weekday_factor = np.array([1.00 if (d - 1) % 7 < 5 else 0.82 for d in days])
line_capacity = np.array([1_050, 930, 810])
expected_output = weekday_factor[:, None] * line_capacity[None, :]
production = rng.poisson(expected_output)
base_defect_rate = np.array([0.018, 0.026, 0.034])
defects = rng.binomial(production, base_defect_rate)
dimension_mean = np.array([10.000, 10.012, 9.992])
dimension_sd = np.array([0.032, 0.041, 0.052])
measurements = rng.normal(
loc=dimension_mean[:, None],
scale=dimension_sd[:, None],
size=(3, 500),
)
daily_df = pd.DataFrame(production, columns=lines, index=pd.Index(days, name="days"))
print("Production Quantity Sequence:", production.shape, "defective number sequence:", defects.shape,
"Dimensioning Array:", measurements.shape)
display(daily_df.head())
Production Quantity Sequence: (30, 3) defective number sequence: (30, 3) Dimensioning Array: (3, 500)
| A | B | C | |
|---|---|---|---|
| days | |||
| 1 | 1019 | 933 | 845 |
| 2 | 1008 | 942 | 837 |
| 3 | 1057 | 941 | 800 |
| 4 | 1092 | 976 | 769 |
| 5 | 1070 | 967 | 831 |
No.001: Creating a NumPy array
Practical use
A two-dimensional array preserves the correspondence between rows (days) and columns (lines). Record the units as well as the axis meanings so that daily totals and line totals cannot be confused.
Model and assumptions
NumPy arrays hold values of the same data type in a regular pattern. shape=(30, 3) means 30 days × 3 lines. If you aggregate with axis=0, you can sum over 30 days to get totals for each line; if axis=1, you can condense 3 lines to get daily values. In practice, each axis and unit are left in code comments and data dictionaries.
Python example
array_design = pd.DataFrame({
"Confirmation items": ["dimensional number", "shape", "number of elements", "data type", "leading day's3Line"],
"value": [production.ndim, str(production.shape), production.size,
str(production.dtype), production[0].tolist()],
})
display(array_design)
print("1Date & Line BProduction Numbers:", production[0, 1], "units")
| Confirmation items | value | |
|---|---|---|
| 0 | dimensional number | 2 |
| 1 | shape | (30, 3) |
| 2 | number of elements | 90 |
| 3 | data type | int64 |
| 4 | leading day's3Line | [1019, 933, 845] |
1Date & Line BProduction Numbers: 933 units
Interpreting the results
The production quantity consists of 30 rows × 3 columns, totaling 90 elements in an integer array. If you specify the target as in production[0, 1], you can uniquely obtain the position of Day 1 and Line B. In actual systems, to avoid losing axis labels on individual arrays, it is safer to design the input phase by combining DataFrame and metadata, and converting them to NumPy during numerical calculations.
No.002: Vector Operations
Practical use
A line with a high number of defects does not necessarily mean poor quality. Since a high production volume tends to increase defects, the defect rate and quality loss amount by line are compared using the same calculation rules.
Model and assumptions
If the number of productions per line is and the number of defects is , the defect rate vector is divided by element.
Furthermore, if the loss per defect is , the loss per line is . What is needed here is not the dot product, but the element operation that computes elements at the same position.
Python example
line_production = production.sum(axis=0)
line_defects = defects.sum(axis=0)
line_defect_rate = line_defects / line_production
loss_per_defect = np.array([4_500, 5_000, 5_800])
quality_loss = line_defects * loss_per_defect
line_kpi = pd.DataFrame({
"production_volume": line_production,
"number_of_defects": line_defects,
"non_performing_rate": line_defect_rate,
"bad1loss per unit(jpy)": loss_per_defect,
"estimated quality loss(jpy)": quality_loss,
}, index=pd.Index(lines, name="Line"))
display(line_kpi.style.format({"non_performing_rate": "{:.2%}", "estimated quality loss(jpy)": "{:,.0f}"}))
| production_volume | number_of_defects | non_performing_rate | bad1loss per unit(jpy) | estimated quality loss(jpy) | |
|---|---|---|---|---|---|
| Line | |||||
| A | 29709 | 531 | 1.79% | 4500 | 2,389,500 |
| B | 26751 | 710 | 2.65% | 5000 | 3,550,000 |
| C | 23240 | 824 | 3.55% | 5800 | 4,779,200 |
Interpreting the results
With vector operations, we were able to apply the same KPI definition to all three lines at once. Improvement priorities are determined not only by defect rates but also by quality loss reflecting production volume and loss unit prices. However, this assumes that the loss per defective item is fixed. When including defective products reaching customers, delivery delays, and sorting work, the loss model needs to be refined separately.
No.003: Matrix Operations
Practical use
If you manually create weekly and line-by-line aggregations from monthly data every time, the way periods are divided and the copy range of formulas fluctuates. If you define aggregation rules as matrices, you can apply the same period transformation to multiple lines at once.
Model and assumptions
Let be the daily production matrix and the matrix assigning each day to a week. The weekly production matrix is
In matrix product, the inner dimension 30 coincide, and the daily axis is aggregated. Since matrix product @ and element product * have different meanings, select them according to the model formula.
Python example
week_id = np.minimum((days - 1) // 7, 4)
week_matrix = np.eye(5, dtype=int)[week_id].T
weekly_production = week_matrix @ production
weekly_df = pd.DataFrame(
weekly_production,
index=pd.Index([f"No.{i}week" for i in range(1, 6)], name="Period"),
columns=lines,
)
weekly_df["All Lines"] = weekly_df.sum(axis=1)
display(weekly_df)
print("aggregation matrix @ daily queue:", week_matrix.shape, "@", production.shape,
"=", weekly_production.shape)
| A | B | C | All Lines | |
|---|---|---|---|---|
| Period | ||||
| No.1week | 6976 | 6340 | 5423 | 18739 |
| No.2week | 6843 | 6187 | 5391 | 18421 |
| No.3week | 6856 | 6277 | 5525 | 18658 |
| No.4week | 6970 | 6102 | 5281 | 18353 |
| No.5week | 2064 | 1845 | 1620 | 5529 |
aggregation matrix @ daily queue: (5, 30) @ (30, 3) = (5, 3)
Interpreting the results
From the aggregation matrix of 5×30 and the daily matrix of 30×3, we obtained the weekly matrix of 5×3. The fifth week only covers two days, the 29th and 30th, so note that it is smaller than other weeks. Instead of simply comparing weekly sums as differences in ability, we normalize and interpret them by working days or planned hours.
No.004: Broadcast
Practical use
If the planned production quantity or management standards differ for each line, there may be cases where three standard values are applied to the results of three lines × 30 days. By using broadcasts, you can calculate without explicitly making copies of the reference values.
Model and assumptions
When you subtract the line-specific reference vector for shape from the actual matrix of shape , NumPy matches the final dimensions and virtually expands the reference to each row. The plan achievement rate is
Broadcasting is convenient, but calculations can sometimes be made even with unintended shapes. shape and several manual calculations are verified.
Python example
daily_target = np.array([1_000, 900, 780])
achievement = production / daily_target
shortfall = production - daily_target
broadcast_check = pd.DataFrame({
"Line": lines,
"Daily Goals": daily_target,
"Monthly average performance": production.mean(axis=0),
"Average Achievement Rate": achievement.mean(axis=0),
"Number of days not reached": (shortfall < 0).sum(axis=0),
}).set_index("Line")
display(broadcast_check.style.format({"Monthly average performance": "{:,.1f}", "Average Achievement Rate": "{:.1%}"}))
print("Observed", production.shape, "/ Objective", daily_target.shape, "-> Achievement rate", achievement.shape)
| Daily Goals | Monthly average performance | Average Achievement Rate | Number of days not reached | |
|---|---|---|---|---|
| Line | ||||
| A | 1000 | 990.3 | 99.0% | 9 |
| B | 900 | 891.7 | 99.1% | 8 |
| C | 780 | 774.7 | 99.3% | 12 |
Observed (30, 3) / Objective (3,) -> Achievement rate (30, 3)
Interpreting the results
A single line-specific target vector was applied to all 30 days, allowing calculation of the average achievement rate and days not met by line. However, setting the same goals as weekdays on holidays can overestimate the number of days left unreached. In practice, it is necessary to reflect calendars, planned stoppages, and variety compositions in the reference sequence, and to “compare only the days that can be compared.”
No.005: Random Number Generation
Practical use
Measurements under the new conditions and equipment downtime were not finalized before implementation. Random numbers are not tools for predicting the future, but tools for creating numerous scenarios that could occur under assumed variability and to assess the sensitivity of judgments.
Model and assumptions
Choose a distribution for the quantity being simulated: a binomial distribution for defects among a fixed number of independently inspected items, a normal distribution for approximately symmetric dimensions, or an exponential distribution for a simple waiting-time model. Here the dimension is modeled as
The second parameter in this notation is the variance. NumPy’s scale=0.038 specifies the standard deviation. We generate 1,000 measurements and compare them with the specification limits.
Python example
improved_c = rng.normal(loc=10.000, scale=0.038, size=1_000)
lower_spec, upper_spec = 9.90, 10.10
random_summary = pd.DataFrame({
"indicator": ["Sample size", "average(mm)", "standard_deviation(mm)", "smallest(mm)", "largest(mm)", "Non-standard rate"],
"value": [improved_c.size, improved_c.mean(), improved_c.std(ddof=1),
improved_c.min(), improved_c.max(),
((improved_c < lower_spec) | (improved_c > upper_spec)).mean()],
})
display(random_summary)
| indicator | value | |
|---|---|---|
| 0 | Sample size | 1,000.000 |
| 1 | average(mm) | 9.999 |
| 2 | standard_deviation(mm) | 0.038 |
| 3 | smallest(mm) | 9.890 |
| 4 | largest(mm) | 10.109 |
| 5 | Non-standard rate | 0.007 |
Interpreting the results
The mean and standard deviation of the generated sample are close to the set value, but since the sample is finite, they do not match perfectly. The estimated non-standard rate also varies with each trial. When evaluating improvement proposals, separating the effect of aligning the average with the standard deviation and reducing the standard deviation makes it easier to explain whether equipment adjustment or variation reduction should be prioritized.
No.006: Random Number Seed
Practical use
In management meetings, audits, and model reviews, it is important that “the same input and code yield the same results.” By fixing seeds, pseudo-random number sequences can be reproduced, allowing comparison of only the impact of calculation changes.
Model and assumptions
Pseudorandom numbers are generated by deterministic algorithms. If you have the same generator, same seed, and same call order, the column will be the same. On the other hand, seed fixation does not guarantee the correctness of the model. Also, to avoid relying solely on a single seed for a favorable conclusion, the production evaluation uses multiple scenarios and sufficient trials.
Python example
rng_a = np.random.default_rng(SEED)
rng_b = np.random.default_rng(SEED)
rng_c = np.random.default_rng(SEED + 1)
sample_a = rng_a.integers(0, 100, size=8)
sample_b = rng_b.integers(0, 100, size=8)
sample_c = rng_c.integers(0, 100, size=8)
seed_check = pd.DataFrame({"same_seed_a": sample_a, "same_seed_b": sample_b,
"differentseed": sample_c})
display(seed_check.T)
print("Sequences of the same seed match:", np.array_equal(sample_a, sample_b))
print("Sequences of different seeds match:", np.array_equal(sample_a, sample_c))
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | |
|---|---|---|---|---|---|---|---|---|
| same_seed_a | 84 | 19 | 17 | 90 | 7 | 53 | 61 | 66 |
| same_seed_b | 84 | 19 | 17 | 90 | 7 | 53 | 61 | 66 |
| differentseed | 33 | 69 | 35 | 48 | 2 | 86 | 51 | 41 |
Sequences of the same seed match: True
Sequences of different seeds match: False
Interpreting the results
Two rows made from the same seed match perfectly, while rows of different seeds do not. In practice, in addition to seeds, library versions, distribution parameters, number of trials, and code versions are recorded in the analysis deliverables. When performing parallel processing, it is also necessary to design independent random number streams.
No.007: Histogram Drawing
Practical use
Even if the average dimensions are close to the standard center, large variation can result in non-standard measurements. The histogram visualizes the center, spread, distortion, multiple peaks, and bases, serving as an entry point to confirm process conditions that cannot be seen by averages alone.
Model and assumptions
The histogram divides the range of values into bins and counts the frequency of each interval. Since the appearance changes depending on the width of the bin, the comparison line uses the same bin. density=True normalizing area to 1 is useful for comparing distribution shapes, but it does not indicate the actual number of defects.
Python example
bins = np.linspace(9.82, 10.18, 28)
fig, ax = plt.subplots(figsize=(9, 5))
for i, line_name in enumerate(lines):
ax.hist(measurements[i], bins=bins, alpha=0.45, density=True,
label=f"Line {line_name}")
ax.axvline(lower_spec, color="crimson", linestyle="--", label="Specification Lower Limit")
ax.axvline(upper_spec, color="crimson", linestyle="--", label="specification upper limit")
ax.set_title("By Line Distribution of Dimensional Measurements")
ax.set_xlabel("Dimensions (mm)")
ax.set_ylabel("probability density")
ax.grid(True, alpha=0.3)
ax.legend()
plt.tight_layout()
plt.show()
hist_summary = pd.DataFrame({
"average(mm)": measurements.mean(axis=1),
"standard_deviation(mm)": measurements.std(axis=1, ddof=1),
"specimen non-specification rate": ((measurements < lower_spec) | (measurements > upper_spec)).mean(axis=1),
}, index=pd.Index(lines, name="Line"))
display(hist_summary.style.format({"average(mm)": "{:.4f}", "standard_deviation(mm)": "{:.4f}",
"specimen non-specification rate": "{:.2%}"}))

| average(mm) | standard_deviation(mm) | specimen non-specification rate | |
|---|---|---|---|
| Line | |||
| A | 10.0001 | 0.0311 | 0.00% |
| B | 10.0108 | 0.0406 | 1.60% |
| C | 9.9906 | 0.0495 | 4.00% |
Interpreting the results
Line B has its center shifted upward, and line C is set to have a relatively wider distribution. These two require different countermeasures: the former focuses on process centering, while the latter involves investigating variability factors including materials, equipment, and measurement systems. Without definitive process capability or distribution suitability based solely on histograms, time series, stratification, control charts, and measurement system analysis are also checked.
No.008: Drawing Cumulative Distribution Functions
Practical use
Cumulative Distribution Functions (CDF) are effective in decision-making using threshold values, such as “What percentage is below 10.05 mm?” or “What is the percentage below the minimum standard?” It can also be used to explain procurement standards, sorting criteria, and warning values for preventive maintenance.
Model and assumptions
The cumulative distribution function is
For an unknown population CDF, samples are arranged in ascending order and the proportion of each point is plotted using the Empirical Cumulative Distribution Function (ECDF). Without assuming a specific distribution pattern, you can read the ratio below the threshold based on the observation sample.
Python example
fig, ax = plt.subplots(figsize=(9, 5))
for i, line_name in enumerate(lines):
x = np.sort(measurements[i])
y = np.arange(1, x.size + 1) / x.size
ax.step(x, y, where="post", label=f"Line {line_name}")
ax.axvline(10.05, color="black", linestyle="--", label="Judgment threshold 10.05 mm")
ax.set_title("Empirical CDF of dimensions by line")
ax.set_xlabel("Dimensions (mm)")
ax.set_ylabel("Cumulative probability P(X <= x)")
ax.grid(True, alpha=0.3)
ax.legend()
plt.tight_layout()
plt.show()
threshold = 10.05
cdf_at_threshold = (measurements <= threshold).mean(axis=1)
display(pd.DataFrame({"10.05mmThe following percentages": cdf_at_threshold},
index=pd.Index(lines, name="Line")).style.format("{:.1%}"))

| 10.05mmThe following percentages | |
|---|---|
| Line | |
| A | 95.0% |
| B | 81.4% |
| C | 88.0% |
Interpreting the results
Even with the same threshold, the cumulative rate varies by line. If the ECDF rises sharply, the price will concentrate within a narrow range; if it is gradual, it can be interpreted as having greater fluctuation. If you want an exceedance rate, use , but since the boundary definition changes depending on whether it contains the sample point equivalent, < and <= are matched to the standard definition.
No.009: Monte Carlo Simulation
Practical use
Monthly profits are subject to multiple uncertainties simultaneously, such as production volume, defects, and equipment shutdowns. If the expected profits exceed the plan, you cannot identify the risk of not being met. It generates numerous future scenarios and evaluates downside probabilities and quantiles.
Model and assumptions
Generate scenarios for production volume, defect probability, and downtime, then calculate monthly profit as
Here is an integer production quantity, is the defective quantity, is the contribution margin per conforming item, is the additional loss per defective item, and is downtime loss. Conditional on and defect probability , draw from a binomial distribution. This example assumes independent production volume, defect probability, and downtime; real applications should account for dependencies such as equipment deterioration affecting both defects and stoppages.
Python example
mc_rng = np.random.default_rng(SEED + 9)
n_scenarios = 20_000
# Use the same nonnegative integer quantity for production and binomial trials.
monthly_units = mc_rng.normal(
line_production.sum(), 2_200, size=n_scenarios
).clip(0).astype(int)
scenario_defect_rate = mc_rng.beta(55, 1_945, size=n_scenarios)
scenario_defects = mc_rng.binomial(monthly_units, scenario_defect_rate)
downtime_hours = mc_rng.gamma(shape=4.0, scale=5.0, size=n_scenarios)
margin_per_good = 620
loss_per_bad = 5_200
downtime_cost_per_hour = 85_000
profit = ((monthly_units - scenario_defects) * margin_per_good
- scenario_defects * loss_per_bad
- downtime_hours * downtime_cost_per_hour)
profit_million = profit / 1_000_000
profit_target = 33.0
mc_summary = pd.DataFrame({
"indicator": ["expected benefit", "5%point", "median", "95th percentile", "33Probability of not reaching one million yen"],
"value": [profit_million.mean(), *np.quantile(profit_million, [0.05, 0.50, 0.95]),
(profit_million < profit_target).mean()],
})
display(mc_summary)
fig, ax = plt.subplots(figsize=(9, 5))
ax.hist(profit_million, bins=45, color="steelblue", alpha=0.8)
ax.axvline(profit_target, color="crimson", linestyle="--", label="Profit target: 33 million yen")
ax.axvline(profit_million.mean(), color="black", linestyle=":", label="scenario average")
ax.set_title("Monthly profit Monte Carlo simulation")
ax.set_xlabel("monthly profit (million yen)")
ax.set_ylabel("Number of scenarios")
ax.grid(True, alpha=0.3)
ax.legend()
plt.tight_layout()
plt.show()
| indicator | value | |
|---|---|---|
| 0 | expected benefit | 34.946 |
| 1 | 5%point | 31.296 |
| 2 | median | 34.984 |
| 3 | 95th percentile | 38.403 |
| 4 | 33Probability of not reaching one million yen | 0.181 |

Interpreting the results
The mean profit summarizes the scenarios, while the 5th percentile is a lower-tail threshold: about 95% of simulated profits exceed it. The probability of missing the plan is often more useful for budgeting than the mean alone. These estimates depend on the input distributions and their dependence, so compare plausible assumptions before making an investment decision.
No.010: Comparison of Calculation Speed
Practical use
Even if the analysis is correct, if it takes several hours to calculate, it cannot be used for daily operations or condition searches. NumPy vectorization can sometimes be written faster and shorter than Python’s explicit loops when applying the same process to many elements.
Model and assumptions
Here, for one million measurements, the non-standard rate is calculated using loops and vector operations. First, confirm that both answers match, then measure multiple times with timeit. Since speed is affected by CPU, library version, and array size, it is read as a relative comparison in this execution environment rather than absolute values.
Python example
speed_rng = np.random.default_rng(SEED + 10)
large_measurements = speed_rng.normal(10.0, 0.045, size=1_000_000)
def defect_rate_loop(values, lower, upper):
count = 0
for value in values:
if value < lower or value > upper:
count += 1
return count / len(values)
def defect_rate_vectorized(values, lower, upper):
return np.mean((values < lower) | (values > upper))
loop_result = defect_rate_loop(large_measurements, lower_spec, upper_spec)
vector_result = defect_rate_vectorized(large_measurements, lower_spec, upper_spec)
# Verify equal results before measuring execution time.
assert np.isclose(loop_result, vector_result)
loop_time = timeit.timeit(
lambda: defect_rate_loop(large_measurements, lower_spec, upper_spec), number=3
) / 3
vector_time = timeit.timeit(
lambda: defect_rate_vectorized(large_measurements, lower_spec, upper_spec), number=10
) / 10
speed_comparison = pd.DataFrame({
"Methods": ["Pythonloop", "NumPyvector operation"],
"Non-standard rate": [loop_result, vector_result],
"Average Execution Time(seconds)": [loop_time, vector_time],
"loop ratio": [1.0, vector_time / loop_time],
})
display(speed_comparison.style.format({"Non-standard rate": "{:.4%}",
"Average Execution Time(seconds)": "{:.6f}", "loop ratio": "{:.3f}"}))
print("The results are unanimous.:", np.isclose(loop_result, vector_result))
print(f"In this environment, vector operations are about {loop_time / vector_time:.1f} times faster")
| Methods | Non-standard rate | Average Execution Time(seconds) | loop ratio | |
|---|---|---|---|---|
| 0 | Pythonloop | 2.6316% | 0.133325 | 1.000 |
| 1 | NumPyvector operation | 2.6316% | 0.003164 | 0.024 |
The results are unanimous.: True
In this environment, vector operations are about 42.1 times faster
Interpreting the results
Both methods return the same out-of-specification rate, and at this array size, vector operations are significantly faster. For performance improvement, we first test the matching of answers and measure them at a size close to the actual data. Since vectorization consumes memory through temporary arrays, for large data, optimization includes segmentation, aggregation methods, data types, and I/O.
Practical lessons
- Array design is the very definition of the business: Clearly indicating which of the day, line, type, or measurement item to be placed on each axis can reduce aggregation errors.
- Switching between number of cases and rates: Rate is required for comparing quality conditions, and evaluation of economic impact requires the number of cases and loss unit price.
- Manage reference values as data: Even if you can apply it all at once via broadcast, ignoring the standards of holidays, product types, and equipment conditions will not make the right decisions.
- Expanding perspectives from average to distribution: With histograms and CDF, not only the center but also the tail, threshold exceedance, and variation can be used as evidence to judge the results.
- Communicating uncertainty with probabilities: The Monte Carlo method allows you to present not only expected values but also quantiles and the probability of not meeting plans.
- Including repeatability and speed in operational requirements: Seeds, environments, and code versions are recorded, and processing times are measured before continuous operation can be transferred.
Applying this in practice
- Data models that can track product IDs, lots, lines, equipment, varieties, shifts, dates and times, and measuring instruments
- Unification of units, denominators, and exclusion conditions for dimensions, defect rates, production quantities, downtime times, and loss amounts
- Data quality rules to detect missing measurements, duplicates, instrument calibration, time offsets, and planned stoppages
- Mechanisms for regularly updating distribution assumptions and parameters, as well as backtesting against actual results
- Reproducibility management that keeps seeds, Python environments, input snapshots, code versions, and approval histories
- Criteria for dividing on-site management limits, quality assurance standards, and management risk tolerance
- The workflow of who reviews the analysis results and who changes equipment conditions and production plans
In a PoC, the decision is first focused on a single point, then the current judgment, required lead time, lost misjudgments, and available data are organized. It is important to include not only model accuracy but also whether it led to improvement actions in the evaluation metrics.
Conclusion
For No.001 to No.010, manufacturing data was designed as NumPy arrays, aggregated using vectors, matrices, and broadcasts, and uncertainty was evaluated using random numbers, histograms, CDFs, and Monte Carlo methods. Finally, we confirmed that even with the same out-of-specification rate calculations, vectorization can shorten processing time.
What’s important is not just that the code works. Only when Array axes, numerical units, random number assumptions, threshold definitions, conditions under which results can be reproduced can be explained can analytics be used for decision-making on the manufacturing floor.
Consulting for businesses
At Surikobo, we support manufacturing companies in quality control, process capability evaluation, anomaly detection, demand and production simulation, mathematical optimization, and data analysis talent development. From on-site data inventory to PoC, integration into decision-making processes, and internal training, we design according to challenges and data maturity.
📩 Contact Us: www.surikobo.co.jp/contact
Please feel free to consult us first.