2626from __future__ import annotations
2727
2828from dataclasses import dataclass
29+ from typing import Optional
30+
2931import httpx
3032import numpy as np
31- from typing import Optional
3233
3334
3435@dataclass
@@ -49,7 +50,7 @@ class RidgeRegression:
4950 learning_rate : float = 0.01
5051 lambda_ : float = 0.1
5152 epochs : int = 1000
52- weights : Optional [ np .ndarray ] = None
53+ weights : np .ndarray | None = None
5354
5455 def __post_init__ (self ) -> None :
5556 if self .learning_rate <= 0 :
@@ -87,18 +88,18 @@ def fit(
8788 if features .shape [0 ] != target .shape [0 ]:
8889 raise ValueError ("Number of samples must match" )
8990
90- X = features if not add_intercept else self ._add_intercept (features )
91- n_samples , n_features = X .shape
91+ x = features if not add_intercept else self ._add_intercept (features )
92+ n_samples , n_features = x .shape
9293
9394 # initialize weights (including bias as weights[0])
9495 self .weights = np .zeros (n_features )
9596
9697 for _ in range (self .epochs ):
97- preds = X @ self .weights
98+ preds = x @ self .weights
9899 errors = preds - target
99100
100101 # gradient without regularization
101- grad = (X .T @ errors ) / n_samples
102+ grad = (x .T @ errors ) / n_samples
102103
103104 # add L2 regularization term (do not regularize bias term)
104105 reg = np .concatenate (([0.0 ], 2 * self .lambda_ * self .weights [1 :]))
@@ -118,8 +119,8 @@ def predict(self, features: np.ndarray, add_intercept: bool = True) -> np.ndarra
118119 """
119120 if self .weights is None :
120121 raise ValueError ("Model is not trained" )
121- X = features if not add_intercept else self ._add_intercept (features )
122- return X @ self .weights
122+ x = features if not add_intercept else self ._add_intercept (features )
123+ return x @ self .weights
123124
124125
125126def mean_absolute_error (predicted : np .ndarray , actual : np .ndarray ) -> float :
@@ -146,16 +147,15 @@ def collect_dataset() -> np.matrix:
146147
147148def main () -> None :
148149 data = collect_dataset ()
149- n = data .shape [0 ]
150150
151151 # features and target (same layout as linear_regression.py)
152- X = np .c_ [data [:, 0 ].astype (float )]
152+ x = np .c_ [data [:, 0 ].astype (float )]
153153 y = np .ravel (data [:, 1 ].astype (float ))
154154
155155 model = RidgeRegression (learning_rate = 0.0002 , lambda_ = 0.01 , epochs = 50000 )
156- model .fit (X , y )
156+ model .fit (x , y )
157157
158- preds = model .predict (X )
158+ preds = model .predict (x )
159159 mae = mean_absolute_error (preds , y )
160160
161161 print ("Learned weights:" )
0 commit comments