DEV Community

Wenlo
Wenlo

Posted on AI-assisted

A good-looking fitted line can hide a curved error pattern

A fitted line and a small table can conceal a systematic problem. Plotting observed minus fitted values against the input often makes the shape easier to see. This fictional example deliberately contains curvature that a straight line cannot represent.

Run the example

I ran this example in PythonIDE on an English iPhone simulator. All measurements are fictional.

import numpy as np
import matplotlib.pyplot as plt

# Fictional measurements have a curved response.
x = np.array([0, 1, 2, 3, 4, 5, 6], dtype=float)
y = np.array([2.0, 3.1, 6.0, 11.2, 18.1, 27.0, 38.2])
A = np.column_stack([x, np.ones_like(x)])
coef, _, rank, _ = np.linalg.lstsq(A, y, rcond=None)
assert rank == 2
predicted = A @ coef
residuals = y - predicted
rmse = np.sqrt(np.mean(residuals ** 2))
print('FICTIONAL RESIDUAL CHECK')
print(f'Linear slope={coef[0]:.3f}, intercept={coef[1]:.3f}')
print(f'Training RMSE: {rmse:.3f} response units')
for value, actual, fitted, error in zip(x, y, predicted, residuals):
    print(f'x={value:.0f}: actual={actual:.2f}, '
          f'fitted={fitted:.2f}, residual={error:+.2f}')
assert np.isclose(residuals.sum(), 0, atol=1e-8)
print('Residual sum is near zero, but errors are not random.')

fig, axes = plt.subplots(2, 1, figsize=(7, 6), sharex=True)
axes[0].scatter(x, y, label='Observations')
axes[0].plot(x, predicted, color='orange', label='Linear fit')
axes[0].set(ylabel='Response', title='Fictional model diagnosis')
axes[0].legend()
axes[1].scatter(x, residuals, color='#EF4444')
axes[1].axhline(0, color='black', linewidth=1)
extent = max(abs(residuals)) * 1.2
axes[1].set_ylim(-extent, extent)
axes[1].set(xlabel='Input', ylabel='Observed - fitted')
axes[1].grid(alpha=.2)
plt.tight_layout()
plt.show()
Enter fullscreen mode Exit fullscreen mode

Residual calculation source in PythonIDE

Residual plot source in PythonIDE

Actual residual output and two-panel graph

Read the behavior and its boundaries

The upper panel shows observations and the linear fit. The lower panel centers errors on a visible zero reference and uses symmetric vertical limits so positive and negative deviations are comparable. Residuals at both ends tend to be positive while middle residuals are negative, suggesting missing curvature.

The near-zero residual sum is expected for ordinary least squares with an intercept, within floating-point error. It does not establish that the residuals are independent, random, normally distributed or small. This is why an aggregate such as mean residual can hide poor fit. RMSE keeps magnitude visible but still does not describe the pattern.

A residual plot suggests what to investigate; it does not prove the cause. Additional measurements, domain knowledge and held-out checks are needed before choosing another model. These are training residuals from invented data, not an independent validation experiment.

Try one change

Fit a quadratic and redraw the residuals with the same axis limits. Compare the pattern rather than only the RMSE, and explain what evidence would still be missing before trusting new predictions.

I build PythonIDE, a Python coding app for iPhone and iPad. AI assisted with drafting and translation; the code, numerical output and graph were checked in PythonIDE on an iPhone simulator.

Observed run: slope 6.018, intercept -2.968, training RMSE 3.461. The actual two-panel graph shows positive endpoint residuals and negative middle residuals.

View PythonIDE on the App Store

Top comments (0)