All articles →

100 Exercises / numerical computation / Numerical Computation: 100 Exercises

Learning Numerical Integration and Differentiation in Manufacturing | Temperature Monitoring and Power Calculation for Continuous Furnaces: 10 Exercises

Compute temperature rates and energy use in Python; compare quadrature, differentiation, noise effects, autograd, and gradient checks.

This article uses a fictional heat-treatment plant to compare numerical differentiation, integration, automatic differentiation, and backpropagation. We estimate heating rates and energy use, then check gradients used to train quality models. Step size and measurement noise are considered throughout.

Note This material was adapted from notebooks used in corporate training by Surikobo or its representative, Hiroshi Wayama, with permission from the participating companies.
All examples use fictional data, not records from real companies or factories.

Introduction: Practical Challenges in Manufacturing Covered in This Article

In continuous furnaces, not only the current temperature but also “how quickly it has changed” and the instantaneous power value “how much is consumed over a certain period” are important. Furthermore, to improve quality forecasting models, it is necessary to calculate which operating conditions will significantly affect the predicted values. In this article, we will stably estimate the rate of change and cumulative amount from discrete measurements and translate them into operational decisions.

Common situations on site

  • Only the temperature limit is monitored, missing sudden rises and drops
  • The five-minute readings from the electricity meter are simply summed up, and the time units are mistaken.
  • They always believe that using high-precision integration methods is beneficial, and do not check for data roughness or noise
  • Quality prediction models work, but they cannot explain sensitivity or how they learn

Why is this issue so difficult to judge?

Field data are not continuous functions, but samples rounded at regular intervals and contain noise. Differentiation amplifies noise, while integration accumulates bias. Small step sizes are not always high precision; a balance between discretization and rounding errors is necessary. Also, the gradient obtained by automatic differentiation is a local sensitivity and cannot be interpreted as a causal effect as is.

Overview of the Exercises

No.ThemeJudgment in the manufacturing industry
061Forward differenceMonitor the temperature rise rate online
062central differenceImproving Change Rate with Historical Analysis
063trapezoid formulaCalculating power consumption from measured power
064Simpson’s ruleAchieving high precision in cumulative smooth load curves
065Gaussian quadratureHeat load is evaluated using a small evaluation point
066Romberg IntegrationStep-by-step accuracy verification and integration
067error in numerical differentiationDesign of step size and noise acceptance standards
068automatic differentiationAccurately calculating local sensitivity of quality models
069backpropagation methodConfirm the learning principles of the quality prediction model
070Implementation of Gradient CalculationQuality assurance of model implementation through gradient verification

Preparing the Python environment

Run the cells in order in Jupyter Notebook. [IN: n] identifies a code cell; [OUT: n] contains its tables, values, and figures. Low-order digits and runtimes may vary with library versions, BLAS, and hardware.

Numerical calculations are performed with NumPy and SciPy, tables with pandas, visualization with matplotlib, and automatic differentiation for PyTorch is used for No.068 to No.070. Fix the random number seed so you can reproduce the same result.

Show setup code: libraries and display settings
[IN: 1]
%matplotlib inline

from IPython.display import display
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import japanize_matplotlib
from scipy import integrate
from numpy.polynomial.legendre import leggauss
import torch

SEED = 20260712
rng = np.random.default_rng(SEED)
torch.manual_seed(SEED)
pd.set_option("display.precision", 4)
print(f"NumPy {np.__version__} / pandas {pd.__version__} / PyTorch {torch.__version__}")
[OUT: 1]
NumPy 2.5.1 / pandas 3.0.3 / PyTorch 2.13.0

Creating the Fictional Data

It simulates the 120-minute operation of a continuous furnace at one-minute intervals. The furnace temperature stabilizes after heating, and small disturbances occur around the 70-minute mark. Heater power includes temperature deviations and periodic load fluctuations. For explanation, both true values without noise and observed values with sensor noise added are retained.

Show setup code: generate the fictional data
[IN: 2]
t_min = np.arange(0, 121, dtype=float)
temp_true = (
    760 + 85 * (1 - np.exp(-t_min / 24)) - 9 * np.exp(-(((t_min - 72) / 7) ** 2))
)
temp_obs = temp_true + rng.normal(0, 0.65, len(t_min))
power_kw = (
    72
    + 35 * np.exp(-t_min / 30)
    + 4 * np.sin(2 * np.pi * t_min / 25)
    + rng.normal(0, 0.8, len(t_min))
)
furnace_df = pd.DataFrame(
    {
        "elapsed_time_min": t_min,
        "furnace_temperature_true_value_C": temp_true,
        "furnace_temperature_observation_C": temp_obs,
        "power_kW": power_kw,
    }
)
display(furnace_df.head())

fig, ax1 = plt.subplots(figsize=(9, 4))
ax1.plot(
    t_min, temp_obs, color="tab:red", lw=1.4, label="Furnace Temperature (Observation)"
)
ax1.set(
    title="Fictional continuous furnace data",
    xlabel="elapsed_time [min]",
    ylabel="furnace_temperature [℃]",
)
ax1.grid(alpha=0.3)
ax2 = ax1.twinx()
ax2.plot(t_min, power_kw, color="tab:blue", alpha=0.65, label="Power")
ax2.set_ylabel("Power [kW]")
fig.tight_layout()
plt.show()
[OUT: 2]
elapsed_time_min furnace_temperature_true_value_C furnace_temperature_observation_C power_kW
0 0.0 760.0000 760.4801 107.0138
1 1.0 763.4689 763.9120 105.9277
2 2.0 766.7962 767.0677 106.0636
3 3.0 769.9878 770.2546 104.0749
4 4.0 773.0491 773.3184 105.8155

png

No.061: Forward Difference

Practical Use

The forward difference is calculated by determining the rate of temperature change from the difference at adjacent points. It serves as the prototype for online monitoring that is easy to implement and updates every new measurement received.

Model and Method

Set the derivative of time tt with a step width hh

f′(t)≈f(t+h)−f(t)hf'(t)\approx\frac{f(t+h)-f(t)}{h}

Taylor expansion gives a truncation error of O(h)O(h) for a sufficiently smooth function. The formula uses the future sample at t+ht+h, so an online implementation can report this interval’s slope only when that sample arrives.

Check with Python

[IN: 3]
h = 1.0
forward_rate = np.diff(temp_obs) / h
rate_df = pd.DataFrame(
    {"section_start_min": t_min[:-1], "forward_difference_C_per_min": forward_rate}
)
display(
    rate_df.loc[
        rate_df["forward_difference_C_per_min"].abs().nlargest(5).index
    ].sort_values("section_start_min")
)

plt.figure(figsize=(9, 3.5))
plt.plot(t_min[:-1], forward_rate, color="tab:orange")
plt.axhline(3.0, color="red", ls="--", label="Verification Criteria +3.0 ℃/min")
plt.axhline(-3.0, color="red", ls="--")
plt.title("Rate of Change in Furnace Temperature by Forward Difference")
plt.xlabel("elapsed_time [min]")
plt.ylabel("rate of change [℃/min]")
plt.grid(alpha=0.3)
plt.legend()
plt.tight_layout()
plt.show()
[OUT: 3]
section_start_min forward_difference_C_per_min
0 0.0 3.4319
2 2.0 3.1869
6 6.0 3.1885
7 7.0 3.2805
17 17.0 3.6901

png

Interpreting the Results

The heating rate is large at startup. Near steady temperature, sensor noise becomes more visible in the derivative estimate. A rate alarm can detect a change before a temperature limit is crossed, but should be assessed with persistence rules or smoothing and thresholds appropriate to the recipe and sensor.

No.062: Central Difference

Practical Use

For post-event cause analysis, measurements from before and after can be used. The central difference is more accurate than the forward difference of the same step size, making it suitable for detailed investigation of disturbance occurrence times and maximum heating speeds.

Model and Method

f′(t)≈f(t+h)−f(t−h)2hf'(t)\approx\frac{f(t+h)-f(t-h)}{2h}

The truncation error is O(h2)O(h^2). Since noise in both neighboring samples is also subtracted, even if the true value is smooth and accurate, separate measures against observation noise are required. You cannot apply the formula at the endpoints.

Check with Python

[IN: 4]
central_obs = (temp_obs[2:] - temp_obs[:-2]) / (2 * h)
central_true = (temp_true[2:] - temp_true[:-2]) / (2 * h)
true_derivative = (85 / 24) * np.exp(-t_min / 24) + 18 * (t_min - 72) / 49 * np.exp(
    -(((t_min - 72) / 7) ** 2)
)
comparison = pd.DataFrame(
    {
        "technique": [
            "Forward difference (true value)",
            "Central difference (true value)",
        ],
        "RMSE_C_per_min": [
            np.sqrt(np.mean((np.diff(temp_true) - true_derivative[:-1]) ** 2)),
            np.sqrt(np.mean((central_true - true_derivative[1:-1]) ** 2)),
        ],
    }
)
display(comparison)

plt.figure(figsize=(9, 3.5))
plt.plot(
    t_min[1:-1], central_obs, label="Central difference (observed value)", alpha=0.7
)
plt.plot(t_min[1:-1], true_derivative[1:-1], label="Analytical Truth", lw=2)
plt.title("Central Difference and True Rate of Temperature Change")
plt.xlabel("elapsed_time [min]")
plt.ylabel("rate of change [℃/min]")
plt.grid(alpha=0.3)
plt.legend()
plt.tight_layout()
plt.show()
[OUT: 4]
technique RMSE_C_per_min
0 Forward difference (true value) 0.0490
1 Central difference (true value) 0.0046

png

Interpreting the Results

In noise-free data, the RMSE of the central difference is small, and accuracy improves as per theory. On the other hand, the curve of the observed values still shows fluctuations. If you prioritize real-time performance, you need to use one-sided differences; if you prioritize post-event accuracy, you need to use central differences.

No.063: Trapezoidal Rule

Practical Use

The process of calculating power consumption from instantaneous values in the electricity meter is numerical integration. The trapezoidal formula is a reliable method for connecting adjacent points with straight lines to calculate energy intensity by equipment and lot.

Model and Method

If we divide interval [a,b][a,b] into nn and let h=(b−a)/nh=(b-a)/n,

∫abf(t)dt≈h(f02+∑i=1n−1fi+fn2)\int_a^b f(t)dt\approx h\left(\frac{f_0}{2}+\sum_{i=1}^{n-1}f_i+\frac{f_n}{2}\right)

To integrate power [kW] with time [h] to obtain the amount of electricity [kWh], unit conversion by dividing minutes by 60 is essential.

Check with Python

[IN: 5]
energy_trap_kwh = np.trapezoid(power_kw, x=t_min / 60)
simple_sum_kwh = power_kw.sum() / 60
display(
    pd.DataFrame(
        {
            "Calculation method": ["trapezoid formula", "Simple sum of each point"],
            "energy_over_120_minutes_kWh": [energy_trap_kwh, simple_sum_kwh],
        }
    )
)

cumulative_kwh = integrate.cumulative_trapezoid(power_kw, t_min / 60, initial=0)
plt.figure(figsize=(9, 3.5))
plt.plot(t_min, cumulative_kwh, color="tab:green")
plt.title("Cumulative energy from the trapezoidal rule")
plt.xlabel("elapsed_time [min]")
plt.ylabel("Cumulative energy [kWh]")
plt.grid(alpha=0.3)
plt.tight_layout()
plt.show()
[OUT: 5]
Calculation method energy_over_120_minutes_kWh
0 trapezoid formula 161.1355
1 Simple sum of each point 162.5969

png

Interpreting the Results

Simple sum counts points at both ends one by one, which differs from the trapezoidal formula. If the measurement interval is missing, the actual timestamp is passed to the integrator, not the number of lines. For energy intensity, divide this energy by good-product mass or the number of processed units, and the range including setup and standby time is also standardized.

No.064: Simpson’s Rule

Practical Use

When the load curve is smooth and measured at equal intervals, Simpson’s rule can accurately evaluate cumulative heat even with fewer measurement points. This is useful when comparing small differences in energy-saving measures.

Model and Method

Every two intervals, approximate the quadratic polynomial and denote the composite Simpson rule

∫abf(t)dt≈h3[f0+fn+4∑j=1n/2f2j−1+2∑j=1n/2−1f2j]\int_a^b f(t)dt\approx\frac{h}{3}\left[f_0+f_n+4\sum_{j=1}^{n/2}f_{2j-1}+2\sum_{j=1}^{n/2-1}f_{2j}\right]

The number of sections is even, with even intervals assumed. If smooth enough, the error is O(h4)O(h^4).

Check with Python

[IN: 6]
def smooth_power(t):
    return 72 + 35 * np.exp(-t / 30) + 4 * np.sin(2 * np.pi * t / 25)

reference, _ = integrate.quad(lambda x: smooth_power(x) / 60, 0, 120, epsabs=1e-12)
rows = []
for step in [20, 10, 5, 2]:
    grid = np.arange(0, 120 + step, step, dtype=float)
    y = smooth_power(grid)
    rows.append([step, np.trapezoid(y, grid / 60), integrate.simpson(y, x=grid / 60)])
accuracy_df = pd.DataFrame(
    rows, columns=["measurement_interval_min", "trapezoid_kWh", "simpson_kWh"]
)
accuracy_df["trapezoid_absolute_error"] = abs(accuracy_df["trapezoid_kWh"] - reference)
accuracy_df["simpson_absolute_error"] = abs(accuracy_df["simpson_kWh"] - reference)
display(accuracy_df)
[OUT: 6]
measurement_interval_min trapezoid_kWh simpson_kWh trapezoid_absolute_error simpson_absolute_error
0 20 161.1771 160.4518 0.1857 9.1099e-01
1 10 161.4131 161.4918 0.0503 1.2900e-01
2 5 161.3777 161.3659 0.0150 3.1844e-03
3 2 161.3653 161.3628 0.0025 6.8897e-05

Interpreting the Results

Simpson’s rule has larger errors than the trapezoidal rule at 20- and 10-minute intervals, but smaller errors at 5 and 2 minutes. Coarse sampling does not resolve the 25-minute periodic component well. Higher order alone therefore does not guarantee better accuracy, even for a smooth function. Check convergence as the spacing decreases and account for measurement noise and missing-data interpolation.

No.065: Gaussian Quadrature

Practical Use

In cases like heat conduction simulations, where a single function evaluation is expensive, there are situations where it is better to select points with a larger amount of information than to evaluate many at equal intervals. Gaussian quadrature aims for high accuracy with only a few evaluation points.

Model and Method

An nn-point Gauss–Legendre rule uses the roots xix_i of the degree-nn Legendre polynomial and weights wiw_i on [−1,1][-1,1].

∫−11f(x)dx≈∑i=1nwif(xi)\int_{-1}^{1}f(x)dx\approx\sum_{i=1}^n w_i f(x_i)

In exact arithmetic, the rule integrates polynomials of degree at most 2n−12n-1 exactly. An affine change of variables maps other finite intervals to [−1,1][-1,1].

Check with Python

[IN: 7]
def gauss_integral(func, a, b, n):
    x, w = leggauss(n)
    mapped = (b - a) * x / 2 + (a + b) / 2
    return (b - a) / 2 * np.sum(w * func(mapped))

gauss_rows = []
for n in [2, 3, 4, 6, 8]:
    estimate = gauss_integral(lambda x: smooth_power(x) / 60, 0, 120, n)
    gauss_rows.append([n, estimate, abs(estimate - reference)])
display(
    pd.DataFrame(
        gauss_rows,
        columns=["node_count", "power_consumption_kWh", "absolute_error_kWh"],
    )
)
[OUT: 7]
node_count power_consumption_kWh absolute_error_kWh
0 2 156.9831 4.3797
1 3 164.9006 3.5378
2 4 163.9079 2.5451
3 6 157.8160 3.5467
4 8 160.2179 1.1449

Interpreting the Results

The error is not monotonic in the number of nodes: it increases from about 2.55 kWh at four nodes to 3.55 kWh at six. Even eight nodes leave about 1.14 kWh of error. Increase the node count or subdivide the interval to check convergence for this oscillatory function. Because the evaluation locations are chosen by the method, it suits simulations better than aggregation of existing regularly sampled logs.

No.066: Romberg Integration

Practical Use

If you want to check not only the value of numerical integration but also the convergence when the increments are fine, the Romberg integral is helpful. It can explain the accuracy of heat balance calculations step by step, helping to build consensus on calculation time and accuracy.

Model and Method

Create a trapezoidal formula Rk,0R_{k,0} with the step size halved, and use Richardson extrapolation

Rk,j=Rk,j−1+Rk,j−1−Rk−1,j−14j−1R_{k,j}=R_{k,j-1}+\frac{R_{k,j-1}-R_{k-1,j-1}}{4^j-1}

Richardson extrapolation cancels leading error terms in the trapezoidal approximation. It can converge rapidly for sufficiently smooth functions, but it does not remove measurement noise or justify inventing missing samples.

Check with Python

[IN: 8]
def romberg_table(func, a, b, levels=6):
    R = np.zeros((levels, levels))
    for k in range(levels):
        n = 2**k
        x = np.linspace(a, b, n + 1)
        R[k, 0] = np.trapezoid(func(x), x)
        for j in range(1, k + 1):
            R[k, j] = R[k, j - 1] + (R[k, j - 1] - R[k - 1, j - 1]) / (4**j - 1)
    return R

R = romberg_table(lambda x: smooth_power(x) / 60, 0, 120, levels=7)
romberg_df = pd.DataFrame(R).mask(np.triu(np.ones_like(R, dtype=bool), 1))
romberg_df.index.name = "Levels of Subdivision k"
romberg_df.columns = [f"Extrapolating order j={j}" for j in range(R.shape[1])]
display(romberg_df.round(8))
print(
    f"Final estimate: {R[-1, -1]:.8f} kWh / Difference from reference value: {abs(R[-1, -1] - reference):.2e} kWh"
)
[OUT: 8]
Extrapolating order j=0 Extrapolating order j=1 Extrapolating order j=2 Extrapolating order j=3 Extrapolating order j=4 Extrapolating order j=5 Extrapolating order j=6
Levels of Subdivision k
0 175.8368 NaN NaN NaN NaN NaN NaN
1 167.0063 164.0628 NaN NaN NaN NaN NaN
2 163.5388 162.3830 162.2711 NaN NaN NaN NaN
3 161.4236 160.7186 160.6076 160.5812 NaN NaN NaN
4 161.3944 161.3846 161.4290 161.4420 161.4454 NaN NaN
5 161.3714 161.3637 161.3623 161.3612 161.3609 161.3608 NaN
6 161.3650 161.3628 161.3628 161.3628 161.3628 161.3628 161.3628
Final estimate: 161.36277623 kWh / Difference from reference value: 1.10e-05 kWh

Interpreting the Results

If the value stabilizes as you move toward the lower right of the table, you can judge that the discretization error is being controlled. In actual testing, the gap between adjacent levels falls below the operational tolerance limit. It’s not about increasing the number of digits itself, but about aligning with the accuracy of the electric meter and the range of energy-saving measures being determined.

No.067: Error in Numerical Differentiation

Practical Use

In differentiation, a smaller step size does not always guarantee better results. If the increments are large, discretization errors occur; if too small, cancellation and measurement noise dominate. This forms the basis for determining the monitoring cycle and smoothing range.

Model and Method

The truncation error for the central difference is generally C1h2C_1h^2, and the rounding error is about C2ε/hC_2\varepsilon/h. The total error forms a U-shape, and there is an optimal step size. In actual measurements, sensor noise can be much greater than the rounding error.

Check with Python

[IN: 9]
x0 = 1.0
hs = np.logspace(-16, -1, 80)
exact = np.cos(x0)
errors64 = np.array(
    [abs((np.sin(x0 + h) - np.sin(x0 - h)) / (2 * h) - exact) for h in hs]
)
rng_noise = np.random.default_rng(SEED)
noise_level = 1e-5
errors_noisy = []
for h_ in hs:
    yp = np.sin(x0 + h_) + rng_noise.normal(0, noise_level)
    ym = np.sin(x0 - h_) + rng_noise.normal(0, noise_level)
    errors_noisy.append(abs((yp - ym) / (2 * h_) - exact))

plt.figure(figsize=(8, 4))
plt.loglog(hs, errors64, label="floating-point only")
plt.loglog(hs, errors_noisy, label="Contains slight measurement noise", alpha=0.75)
plt.title("Step Size and Error in Central Difference")
plt.xlabel("Step size h")
plt.ylabel("absolute_error")
plt.grid(True, which="both", alpha=0.3)
plt.legend()
plt.tight_layout()
plt.show()
print(f"Best Step Size for Floating-Point Only: {hs[np.argmin(errors64)]:.2e}")
[OUT: 9]

png

Best Step Size for Floating-Point Only: 6.65e-06

Interpreting the Results

Even without noise, step sizes that are too small can increase errors, and amplification becomes even more pronounced when noise is present. In equipment monitoring, before shortening the sampling cycle, sensor resolution, detection delays due to smoothing, and the time scale of changes to be detected are evaluated together.

No.068: Automatic Differentiation

Practical Use

To understand how much defect risk changes when moving the furnace temperature by 1°C in quality prediction models, a gradient is necessary. Automatic differentiation does not specify the step size of finite differences, but finds the derivative with floating-point precision along the calculated graph.

Model and Method

Let the prediction score be s=0.018(T−820)2+0.12v2+0.004(T−820)vs=0.018(T-820)^2+0.12v^2+0.004(T-820)v. Automatic differentiation combines the local derivatives of each operation, such as addition and multiplication, using the chain rule. This is neither a symbolic transformation of a formula nor a finite difference.

Check with Python

[IN: 10]
T = torch.tensor(828.0, requires_grad=True)
v = torch.tensor(1.8, requires_grad=True)
score = 0.018 * (T - 820) ** 2 + 0.12 * v**2 + 0.004 * (T - 820) * v
score.backward()
autograd_df = pd.DataFrame(
    {
        "variable": ["furnace_temperature T [℃]", "transport speed v [m/min]"],
        "present value": [T.item(), v.item()],
        "local gradient": [T.grad.item(), v.grad.item()],
    }
)
display(autograd_df)
[OUT: 10]
variable present value local gradient
0 furnace_temperature T [℃] 828.0 0.2952
1 transport speed v [m/min] 1.8 0.4640

Interpreting the Results

The sign for the local gradient indicates the direction of score change when the variable is increased around the current point. Absolute values of gradients with different units are not directly compared; instead, the realistic change is multiplied by the effect amount. Also, the gradient of the observation model is a local sensitivity based on correlation and does not guarantee causal effects of manipulation.

No.069: Backpropagation Method

Practical Use

Backpropagation computes the loss gradient with respect to each neural-network parameter by applying the chain rule from the output back through the layers. An optimizer then uses those gradients to update the weights.

Model and Method

Let a model with a single hidden layer y^=W2tanh⁡(W1x+b1)+b2\hat y=W_2\tanh(W_1x+b_1)+b_2 and mean squared error be L=n−1∑(y^−y)2L=n^{-1}\sum(\hat y-y)^2. Reverse-mode automatic differentiation efficiently propagates from ∂L/∂W2\partial L/\partial W_2 to the preceding gradient by the chain rule.

Check with Python

[IN: 11]
n = 120
X_np = np.column_stack([rng.normal(820, 8, n), rng.normal(1.8, 0.25, n)])
y_np = (
    0.018 * (X_np[:, 0] - 820) ** 2
    + 0.12 * X_np[:, 1] ** 2
    + 0.004 * (X_np[:, 0] - 820) * X_np[:, 1]
)
y_np += rng.normal(0, 0.08, n)
X = torch.tensor((X_np - X_np.mean(0)) / X_np.std(0), dtype=torch.float32)
y = torch.tensor(y_np[:, None], dtype=torch.float32)

model = torch.nn.Sequential(
    torch.nn.Linear(2, 6), torch.nn.Tanh(), torch.nn.Linear(6, 1)
)
optimizer = torch.optim.Adam(model.parameters(), lr=0.03)
losses = []
for epoch in range(301):
    optimizer.zero_grad()
    loss = torch.mean((model(X) - y) ** 2)
    loss.backward()
    optimizer.step()
    losses.append(loss.item())

plt.figure(figsize=(8, 3.5))
plt.plot(losses)
plt.title("Training Quality Prediction Models Using Backpropagation Methods")
plt.xlabel("epoch")
plt.ylabel("mean squared error")
plt.grid(alpha=0.3)
plt.tight_layout()
plt.show()
print(f"initial loss: {losses[0]:.4f} / Final loss: {losses[-1]:.4f}")
[OUT: 11]

png

initial loss: 7.8346 / Final loss: 0.1815

Interpreting the Results

The decreasing loss shows that backpropagation provides useful training gradients. Training loss alone does not establish predictive performance. Validate on separate equipment, product types, or periods, and assess how prediction errors affect operating decisions.

No.070: Implementation of Gradient Calculation

Practical Use

Errors in gradient implementation can cause the model to fail to learn or to recommend incorrect operating conditions. Gradient checks that match self-made analytical gradients, automatic differentiation, and finite differences serve as acceptance tests for analysis codes.

Model and Method

Let the loss of linear regression be L(w)=n−1∥Xw−y∥22L(w)=n^{-1}\|Xw-y\|_2^2, then the analytical gradient is

∇wL=2nXT(Xw−y)\nabla_wL=\frac{2}{n}X^T(Xw-y)

Approximate each component using central differences, compare absolute differences with the automatic-differentiation results. Finite differences are for verification purposes, and the computational complexity is too large for large-scale model training.

Check with Python

[IN: 12]
X_check = np.column_stack(
    [np.ones(8), np.linspace(-1, 1, 8), np.linspace(-1, 1, 8) ** 2]
)
y_check = np.array([1.5, 1.2, 1.0, 0.9, 1.0, 1.3, 1.7, 2.2])
w = np.array([1.0, -0.2, 0.5])

def mse_np(w_):
    return np.mean((X_check @ w_ - y_check) ** 2)

analytic = 2 / len(y_check) * X_check.T @ (X_check @ w - y_check)
eps = 1e-6
finite = np.array(
    [
        (mse_np(w + eps * np.eye(3)[j]) - mse_np(w - eps * np.eye(3)[j])) / (2 * eps)
        for j in range(3)
    ]
)
wt = torch.tensor(w, dtype=torch.float64, requires_grad=True)
Xt = torch.tensor(X_check, dtype=torch.float64)
yt = torch.tensor(y_check, dtype=torch.float64)
torch.mean((Xt @ wt - yt) ** 2).backward()
auto = wt.grad.detach().numpy()

gradient_df = pd.DataFrame(
    {
        "coefficient": ["slice", "Linear term", "Quadratic term"],
        "analytical gradient": analytic,
        "finite difference": finite,
        "automatic differentiation": auto,
        "analytic_vs_autograd_absolute_difference": abs(analytic - auto),
    }
)
display(gradient_df)
print(f"Maximum difference in gradient check: {np.max(abs(analytic - auto)):.2e}")
[OUT: 12]
coefficient analytical gradient finite difference automatic differentiation analytic_vs_autograd_absolute_difference
0 slice -0.2714 -0.2714 -0.2714 0.0
1 Linear term -0.4714 -0.4714 -0.4714 0.0
2 Quadratic term -0.2294 -0.2294 -0.2294 0.0
Maximum difference in gradient check: 0.00e+00

Interpreting the Results

If the three methods match with sufficiently small margins, the basic integrity of gradient implementations can be confirmed. In production, random multiple points, near boundaries, and nondifferentiable activation points are treated separately from ordinary derivative checks, and tolerances are determined according to the data type. Gradient check is not about model accuracy, but about assessing the validity of implementation.

Lessons from the Examples

  1. Change rate and cumulative amount capture different anomalies: Differentiation visualizes sudden changes, while integration visualizes small deviations over long periods.
  2. Prerequisites are more important than higher-order methods: If the spacing, smoothness, noise, and endpoint processing are compromised, theoretical accuracy cannot be achieved.
  3. Accuracy is determined by the task unit: Convert numerical errors into power consumption, cost, temperature deviation, and quality loss, and determine the required magnitudes.
  4. Gradient is the local sensitivity of the model: Before using them for operational recommendations, check constraints, interactions, causality, and data scope.

Putting the Methods into Practice

  • Sensor calibration, time synchronization, missing measurements, unit, and sampling cycle management
  • Operational context that distinguishes recipe changes, scheduling, and stoppage intervals
  • Clarification of step size, interpolation, smoothing, endpoint processing, and convergence tolerance
  • Unit tests and regression tests using analytical values, automatic differentiation, and finite differences
  • Acceptance criteria separating numerical error, measurement error, and model error
  • Workflow for post-alarm confirmation, operational permissions, safety restrictions, and model updates

Conclusion

No.061–No.070 compare forward and central differences, trapezoidal and Simpson rules, Gaussian quadrature, and Romberg integration, followed by automatic differentiation and gradient checks. Select methods using data spacing, smoothness, noise, and the error tolerance needed for the decision, and retain checks that make the calculation reproducible.

Business Inquiries

At Surikobo, we support everything from problem organization to implementation and operational design, covering everything from numerical analysis of manufacturing data, energy intensity design, equipment anomaly detection, quality prediction models, gradient-based optimization, to on-site staff training.

📩 Contact Us: www.surikobo.co.jp/contact
Contact us to discuss your project.