Skip to content

Commit a0db9d6

Browse files
committed
machine_learning: fix ruff issues (imports, annotations, naming, tests package)
1 parent 51d9176 commit a0db9d6

File tree

3 files changed

+22
-21
lines changed

3 files changed

+22
-21
lines changed

machine_learning/ridge_regression.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,10 @@
2626
from __future__ import annotations
2727

2828
from dataclasses import dataclass
29+
from typing import Optional
30+
2931
import httpx
3032
import 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

125126
def mean_absolute_error(predicted: np.ndarray, actual: np.ndarray) -> float:
@@ -146,16 +147,15 @@ def collect_dataset() -> np.matrix:
146147

147148
def 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:")

machine_learning/tests/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# Package for machine_learning tests

machine_learning/tests/test_ridge_regression.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,11 @@
55

66

77
def test_fit_perfect_linear_no_regularization():
8-
X = np.array([[1.0], [2.0], [3.0]])
8+
x = np.array([[1.0], [2.0], [3.0]])
99
y = np.array([2.0, 4.0, 6.0])
1010

1111
model = RidgeRegression(learning_rate=0.1, lambda_=0.0, epochs=2000)
12-
model.fit(X, y)
12+
model.fit(x, y)
1313

1414
# bias ~ 0, slope ~ 2
1515
assert pytest.approx(0.0, abs=1e-2) == model.weights[0]
@@ -18,15 +18,15 @@ def test_fit_perfect_linear_no_regularization():
1818

1919
def test_regularization_reduces_weight_norm():
2020
rng = np.random.default_rng(0)
21-
X = rng.normal(size=(200, 2))
21+
x = rng.normal(size=(200, 2))
2222
true_w = np.array([0.0, 5.0, -3.0])
23-
y = X @ true_w[1:] + true_w[0] + rng.normal(scale=0.1, size=200)
23+
y = x @ true_w[1:] + true_w[0] + rng.normal(scale=0.1, size=200)
2424

2525
no_reg = RidgeRegression(learning_rate=0.01, lambda_=0.0, epochs=5000)
26-
no_reg.fit(X, y)
26+
no_reg.fit(x, y)
2727

2828
strong_reg = RidgeRegression(learning_rate=0.01, lambda_=10.0, epochs=5000)
29-
strong_reg.fit(X, y)
29+
strong_reg.fit(x, y)
3030

3131
norm_no_reg = np.linalg.norm(no_reg.weights[1:])
3232
norm_strong_reg = np.linalg.norm(strong_reg.weights[1:])
@@ -35,12 +35,12 @@ def test_regularization_reduces_weight_norm():
3535

3636

3737
def test_predict_and_mae():
38-
X = np.array([[1.0], [2.0]])
38+
x = np.array([[1.0], [2.0]])
3939
y = np.array([3.0, 5.0])
4040
model = RidgeRegression(learning_rate=0.1, lambda_=0.0, epochs=1000)
41-
model.fit(X, y)
41+
model.fit(x, y)
4242

43-
preds = model.predict(X)
43+
preds = model.predict(x)
4444
assert preds.shape == (2,)
4545
assert mean_absolute_error(preds, y) < 1e-2
4646

0 commit comments

Comments
 (0)