alphas = np.logspace(-3, 4, 200)
# Ridge path
ridge_coefs = np.array([
Ridge(alpha=a).fit(X_scaled, y_full).coef_
for a in alphas
])
# Lasso path
lasso_coefs = np.array([
Lasso(alpha=a, max_iter=10000).fit(X_scaled, y_full).coef_
for a in alphas
])
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
palette = sns.color_palette('tab10', n_colors=8)
for j, name in enumerate(feature_names):
axes[0].plot(np.log10(alphas), ridge_coefs[:, j],
lw=1.8, color=palette[j], label=name)
axes[1].plot(np.log10(alphas), lasso_coefs[:, j],
lw=1.8, color=palette[j], label=name)
for ax, title, best_a in [
(axes[0], 'Ridge Coefficient Path', ridge_cv.alpha_),
(axes[1], 'Lasso Coefficient Path', lasso_cv.alpha_),
]:
ax.axvline(np.log10(best_a), color='crimson', lw=2,
linestyle='--', label=f'CV-selected $\\lambda$')
ax.axhline(0, color='gray', lw=0.8)
ax.set_xlabel('$\\log_{10}(\\lambda)$')
ax.set_ylabel('Coefficient value')
ax.set_title(title)
ax.legend(fontsize=7, ncol=2)
plt.suptitle('Regularization Paths — California Housing', fontsize=13, y=1.02)
plt.tight_layout(); plt.show()