|
| 1 | +""" |
| 2 | +=========================================== |
| 3 | +Fast Quantile Regression with Smoothing |
| 4 | +=========================================== |
| 5 | +This example demonstrates how SmoothQuantileRegressor achieves faster convergence |
| 6 | +than scikit-learn's QuantileRegressor while maintaining accuracy, particularly |
| 7 | +for large datasets. |
| 8 | +""" |
| 9 | + |
| 10 | +# %% |
| 11 | +# Data Generation |
| 12 | +# -------------- |
| 13 | +# First, we generate synthetic data with a known quantile structure. |
| 14 | + |
| 15 | +import time |
| 16 | +import numpy as np |
| 17 | +import matplotlib.pyplot as plt |
| 18 | +from sklearn.datasets import make_regression |
| 19 | +from sklearn.preprocessing import StandardScaler |
| 20 | +from sklearn.linear_model import QuantileRegressor |
| 21 | +from skglm.experimental.smooth_quantile_regressor import SmoothQuantileRegressor |
| 22 | +from skglm.solvers import FISTA |
| 23 | + |
| 24 | +# Set random seed for reproducibility |
| 25 | +np.random.seed(42) |
| 26 | + |
| 27 | +# Generate dataset - using a more reasonable size for quick testing |
| 28 | +n_samples, n_features = 10000, 10 # Match test file size |
| 29 | +X, y = make_regression(n_samples=n_samples, n_features=n_features, |
| 30 | + noise=0.1, random_state=42) |
| 31 | +X = StandardScaler().fit_transform(X) |
| 32 | +y = y - np.mean(y) # Center y like in test file |
| 33 | + |
| 34 | +# %% |
| 35 | +# Model Comparison |
| 36 | +# --------------- |
| 37 | +# We compare scikit-learn's QuantileRegressor with our SmoothQuantileRegressor |
| 38 | +# on the 80th quantile. |
| 39 | + |
| 40 | +tau = 0.5 # median (SmoothQuantileRegressor works much better for non-median quantiles) |
| 41 | +alpha = 0.1 |
| 42 | + |
| 43 | + |
| 44 | +def pinball_loss(y_true, y_pred, tau=0.5): |
| 45 | + """Compute Pinball (quantile) loss.""" |
| 46 | + residuals = y_true - y_pred |
| 47 | + return np.mean(np.where(residuals >= 0, |
| 48 | + tau * residuals, |
| 49 | + (1 - tau) * -residuals)) |
| 50 | + |
| 51 | + |
| 52 | +# scikit-learn's QuantileRegressor |
| 53 | +start_time = time.time() |
| 54 | +qr = QuantileRegressor(quantile=tau, alpha=alpha, fit_intercept=True, |
| 55 | + solver="highs").fit(X, y) |
| 56 | +qr_time = time.time() - start_time |
| 57 | +y_pred_qr = qr.predict(X) |
| 58 | +qr_loss = pinball_loss(y, y_pred_qr, tau=tau) |
| 59 | + |
| 60 | +# SmoothQuantileRegressor |
| 61 | +start_time = time.time() |
| 62 | +solver = FISTA(max_iter=2000, tol=1e-8) |
| 63 | +solver.fit_intercept = True |
| 64 | +sqr = SmoothQuantileRegressor( |
| 65 | + smoothing_sequence=[1.0, 0.5, 0.2, 0.1, 0.05], # Base sequence, will be extended |
| 66 | + quantile=tau, alpha=alpha, verbose=True, # Enable verbose to see stages |
| 67 | + smooth_solver=solver |
| 68 | +).fit(X, y) |
| 69 | +sqr_time = time.time() - start_time |
| 70 | +y_pred_sqr = sqr.predict(X) |
| 71 | +sqr_loss = pinball_loss(y, y_pred_sqr, tau=tau) |
| 72 | + |
| 73 | +# %% |
| 74 | +# Performance Analysis |
| 75 | +# ------------------ |
| 76 | +# Let's analyze both the performance and solution quality of both methods. |
| 77 | + |
| 78 | +speedup = qr_time / sqr_time |
| 79 | +rel_gap = (sqr_loss - qr_loss) / qr_loss |
| 80 | + |
| 81 | +print("\nPerformance Summary:") |
| 82 | +print("scikit-learn QuantileRegressor:") |
| 83 | +print(f" Time: {qr_time:.2f}s") |
| 84 | +print(f" Loss: {qr_loss:.6f}") |
| 85 | +print("SmoothQuantileRegressor:") |
| 86 | +print(f" Time: {sqr_time:.2f}s") |
| 87 | +print(f" Loss: {sqr_loss:.6f}") |
| 88 | +print(f" Speedup: {speedup:.1f}x") |
| 89 | +print(f" Relative gap: {rel_gap:.1%}") |
| 90 | + |
| 91 | +# %% |
| 92 | +# Visual Comparison |
| 93 | +# --------------- |
| 94 | +# We create visualizations to compare the predictions and residuals |
| 95 | +# of both methods. |
| 96 | + |
| 97 | +# Sort data for better visualization |
| 98 | +sort_idx = np.argsort(y) |
| 99 | +y_sorted = y[sort_idx] |
| 100 | +qr_pred = y_pred_qr[sort_idx] |
| 101 | +sqr_pred = y_pred_sqr[sort_idx] |
| 102 | + |
| 103 | +# Create figure with two subplots |
| 104 | +fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5)) |
| 105 | + |
| 106 | +# Plot predictions |
| 107 | +ax1.scatter(y_sorted, qr_pred, alpha=0.5, label='scikit-learn', s=10) |
| 108 | +ax1.scatter(y_sorted, sqr_pred, alpha=0.5, label='SmoothQuantile', s=10) |
| 109 | +ax1.plot([y_sorted.min(), y_sorted.max()], |
| 110 | + [y_sorted.min(), y_sorted.max()], 'k--', alpha=0.3) |
| 111 | +ax1.set_xlabel('True values') |
| 112 | +ax1.set_ylabel('Predicted values') |
| 113 | +ax1.set_title(f'Predictions (τ={tau})') |
| 114 | +ax1.legend() |
| 115 | + |
| 116 | +# Plot residuals |
| 117 | +qr_residuals = y_sorted - qr_pred |
| 118 | +sqr_residuals = y_sorted - sqr_pred |
| 119 | +ax2.hist(qr_residuals, bins=50, alpha=0.5, label='scikit-learn') |
| 120 | +ax2.hist(sqr_residuals, bins=50, alpha=0.5, label='SmoothQuantile') |
| 121 | +ax2.axvline(x=0, color='k', linestyle='--', alpha=0.3) |
| 122 | +ax2.set_xlabel('Residuals') |
| 123 | +ax2.set_ylabel('Count') |
| 124 | +ax2.set_title('Residual Distribution') |
| 125 | +ax2.legend() |
| 126 | + |
| 127 | +plt.tight_layout() |
| 128 | + |
| 129 | +# %% |
| 130 | +# Progressive Smoothing Analysis |
| 131 | +# ---------------------------- |
| 132 | +# Let's examine how the smoothing parameter affects the solution quality. |
| 133 | + |
| 134 | +stages = sqr.stage_results_ |
| 135 | +deltas = [s['delta'] for s in stages] |
| 136 | +errors = [s['quantile_error'] for s in stages] |
| 137 | +losses = [s['obj_value'] for s in stages] |
| 138 | + |
| 139 | +fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5)) |
| 140 | + |
| 141 | +# Plot quantile error progression |
| 142 | +ax1.semilogx(deltas, errors, 'o-') |
| 143 | +ax1.set_xlabel('Smoothing parameter (δ)') |
| 144 | +ax1.set_ylabel('Quantile error') |
| 145 | +ax1.set_title('Quantile Error vs Smoothing') |
| 146 | +ax1.grid(True, alpha=0.3) |
| 147 | + |
| 148 | +# Plot objective value progression |
| 149 | +ax2.semilogx(deltas, losses, 'o-') |
| 150 | +ax2.set_xlabel('Smoothing parameter (δ)') |
| 151 | +ax2.set_ylabel('Objective value') |
| 152 | +ax2.set_title('Objective Value vs Smoothing') |
| 153 | +ax2.grid(True, alpha=0.3) |
| 154 | + |
| 155 | +plt.tight_layout() |
| 156 | +plt.show() |
0 commit comments