1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
| class LinearRegression: """ Linear Regression model implementation using JAX with JIT and jax.lax.scan. Supports both JIT-compiled and non-JIT versions for performance comparison.
Attributes: key (jnp.ndarray): Random key for weight initialization. lr (float): Learning rate for gradient descent. epochs (int): Number of training epochs. W (jnp.ndarray): Weights of the linear regression model. use_jit (bool): Whether to use JIT compilation. """
def __init__( self, key: jnp.ndarray, batch_size: int = 32, lr: float = 0.01, epochs: int = 1000, ridge_alpha: float = 0.0, use_jit: bool = True): self.key = key self.init_lr = lr self.epochs = epochs self.batch_size = batch_size self.ridge_alpha = ridge_alpha self.use_jit = use_jit self.W: jnp.ndarray = None self.decay = 0.001 self.scheduler_progress = [] self.loss_progress = []
@staticmethod def _batch_forward_impl(W: jnp.ndarray, X_batched: jnp.ndarray, y_batched: jnp.ndarray, epoch: int, init_lr: float, decay: float, ridge_alpha: float): """ Process all batches using jax.lax.scan (JIT-compatible). X_batched: (num_batches, batch_size, num_features + 1) y_batched: (num_batches, batch_size, 1) """ num_batches = X_batched.shape[0] batch_size = X_batched.shape[1]
def scan_fn(carry, inputs): W, step = carry X_batch, y_batch = inputs
y_pred = X_batch @ W
dW = (2 / batch_size) * (X_batch.T @ (y_pred - y_batch)) + ridge_alpha * W
num_steps = num_batches * epoch + step lr = init_lr / (1. + decay * num_steps)
W_new = W - lr * dW
loss = (1/batch_size) * jnp.sum((y_pred - y_batch) ** 2) + (ridge_alpha/2) * jnp.sum(W**2)
return (W_new, step + 1), (loss, lr)
(W_final, _), (losses, lrs) = jax.lax.scan(scan_fn, (W, 0), (X_batched, y_batched)) return W_final, losses, lrs
_batch_forward_jit = staticmethod( jax.jit(_batch_forward_impl.__func__, static_argnums=(4, 5, 6)) )
@staticmethod def _batch_forward_no_jit(W: jnp.ndarray, X_batched: jnp.ndarray, y_batched: jnp.ndarray, epoch: int, init_lr: float, decay: float, ridge_alpha: float): """ Process all batches using Python loop (no JIT, for comparison). """ num_batches = X_batched.shape[0] batch_size = X_batched.shape[1] losses = [] lrs = [] for step in range(num_batches): X_batch = X_batched[step] y_batch = y_batched[step] y_pred = X_batch @ W
dW = (2 / batch_size) * (X_batch.T @ (y_pred - y_batch)) + ridge_alpha * W
num_steps = num_batches * epoch + step lr = init_lr / (1. + decay * num_steps)
W = W - lr * dW
loss = (1/batch_size) * jnp.sum((y_pred - y_batch) ** 2) + (ridge_alpha/2) * jnp.sum(W**2) losses.append(loss) lrs.append(lr)
return W, jnp.array(losses), jnp.array(lrs)
@staticmethod def _predict_impl(W: jnp.ndarray, X: jnp.ndarray) -> jnp.ndarray: """Core prediction logic.""" return X @ W
_predict_jit = staticmethod(jax.jit(_predict_impl.__func__))
def fit(self, X: jnp.ndarray, y: jnp.ndarray, verbose: bool = True) -> None: """ Fit the linear regression model to the training data.
Args: X (jnp.ndarray): Input features of shape (num_samples, num_features). y (jnp.ndarray): Target values of shape (num_samples,) or (num_samples, 1). verbose (bool): Whether to print progress. Default True. """ num_samples = X.shape[0] num_features = X.shape[1] self.W = jax.random.normal(self.key, shape=(num_features + 1, 1)) X = jnp.hstack((jnp.ones(shape=(num_samples, 1)), X)) y = y.reshape(-1, 1)
batch_comp = (num_samples // self.batch_size) * self.batch_size
if num_samples != batch_comp: pad_size = self.batch_size - (num_samples - batch_comp) X_padded = jnp.vstack([X, jnp.zeros((pad_size, X.shape[1]))]) y_padded = jnp.vstack([y, jnp.zeros((pad_size, 1))]) num_batches = (num_samples + pad_size) // self.batch_size else: X_padded = X y_padded = y num_batches = num_samples // self.batch_size
X_batched = X_padded.reshape(num_batches, self.batch_size, -1) y_batched = y_padded.reshape(num_batches, self.batch_size, -1)
forward_fn = self._batch_forward_jit if self.use_jit else self._batch_forward_no_jit
all_losses = [] all_lrs = [] for epoch in range(self.epochs): self.W, epoch_losses, epoch_lrs = forward_fn( self.W, X_batched, y_batched, epoch, self.init_lr, self.decay, self.ridge_alpha ) avg_loss = jnp.mean(epoch_losses) all_losses.append(float(avg_loss)) all_lrs.extend(epoch_lrs.tolist()) if verbose: print(f"Epoch {epoch + 1}: Loss {avg_loss:.6f}")
self.loss_progress = all_losses self.scheduler_progress = all_lrs
def predict(self, X: jnp.ndarray) -> jnp.ndarray: """ Predict the target values for the given input features.
Args: X (jnp.ndarray): Input features of shape (num_samples, num_features).
Returns: jnp.ndarray: Predicted target values of shape (num_samples, 1). """ X = jnp.hstack((jnp.ones(shape=(X.shape[0], 1)), X)) if self.use_jit: return self._predict_jit(self.W, X) else: return self._predict_impl(self.W, X)
|