Code
import numpy as np
import plotly.graph_objects as go
# "Capacity" axis: 0 = very simple, 1 = very flexible
capacity = np.linspace(0.0, 1.0, 200)
# Toy curves (just for visualization)
gen_error = 0.35 * (capacity - 0.55) ** 2 + 0.2 # U-shaped generalization error
train_error = 0.5 - 0.35 * capacity # monotonically decreasing training error
sweet_spot = 0.55
too_flexible = 0.9
fig = go.Figure()
# Generalization error
fig.add_trace(
go.Scatter(
x=capacity,
y=gen_error,
mode="lines",
name="Expected generalization error",
)
)
# Training error (for context)
fig.add_trace(
go.Scatter(
x=capacity,
y=train_error,
mode="lines",
name="Training error",
line=dict(dash="dash")
)
)
# Sweet spot marker
fig.add_vline(
x=sweet_spot,
line=dict(width=2),
annotation_text="sweet spot",
annotation_position="top"
)
# Arrow: regularization pushing from high capacity back toward sweet spot
fig.add_annotation(
x=too_flexible,
y=float(gen_error[capacity.argmax()]), # just park it near the right
ax=sweet_spot + 0.02,
ay=float(gen_error[np.abs(capacity - sweet_spot).argmin()]) + 0.03,
text="↑ λ (stronger regularization)",
showarrow=True,
arrowhead=2
)
fig.update_layout(
xaxis_title="Model capacity (complexity)",
yaxis_title="Error",
margin=dict(l=40, r=10, t=30, b=40),
legend=dict(x=0.02, y=0.98)
)
fig


