center = np.array([2.0, 0.6])
def region_loss(w1, w2):
return (w1 - center[0]) ** 2 + 1.5 * (w2 - center[1]) ** 2
angles = np.linspace(0, 2 * np.pi, 20001)
circle = np.column_stack([np.cos(angles), np.sin(angles)])
diamond = circle / np.abs(circle).sum(axis=1, keepdims=True)
gx, gy = np.meshgrid(np.linspace(-1.5, 3, 300), np.linspace(-1.5, 2, 300))
fig, axes = plt.subplots(1, 2, figsize=(9.6, 4.0))
for ax, shape, title in ((axes[0], diamond, "L1"), (axes[1], circle, "L2")):
best = shape[np.argmin(region_loss(*shape.T))]
ax.fill(shape[:, 0], shape[:, 1], color="tab:blue", alpha=0.2)
ax.plot(shape[:, 0], shape[:, 1], color="tab:blue", lw=1.5)
ax.contour(gx, gy, region_loss(gx, gy), levels=[0.2, 0.6, 1.2, region_loss(*best), 3.5], colors="gray", linewidths=0.9)
ax.plot(*center, "x", color="black", ms=9, mew=2)
ax.plot(*best, "o", color="tab:red", ms=8, zorder=4)
ax.axhline(0, color="black", lw=0.6)
ax.axvline(0, color="black", lw=0.6)
ax.set_title(f"{title}: ({best[0]:.2f}, {best[1]:.2f})")
ax.set_xlabel(r"$w_1$")
ax.set_ylabel(r"$w_2$")
ax.set_aspect("equal")
plt.tight_layout()
plt.show()