linreg-scratch 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4 @@
1
+ from .model import LinearRegression
2
+
3
+ __all__ = ["LinearRegression"]
4
+ __version__ = "0.1.0"
@@ -0,0 +1,91 @@
1
+ """Simple linear regression (y = m*x + b) implemented from scratch with NumPy."""
2
+ import numpy as np
3
+
4
+
5
+ class LinearRegression:
6
+ """Simple (one feature) linear regression.
7
+
8
+ Parameters
9
+ ----------
10
+ lr : float
11
+ Learning rate for gradient descent.
12
+ epochs : int
13
+ Number of gradient descent iterations.
14
+ solver : {"gd", "closed"}
15
+ "gd" uses gradient descent; "closed" uses the exact least-squares formula.
16
+
17
+ Attributes
18
+ ----------
19
+ m : float
20
+ Slope.
21
+ b : float
22
+ Intercept (bias).
23
+ history : list of float
24
+ MSE at each epoch (gradient descent only).
25
+ """
26
+
27
+ def __init__(self, lr=0.01, epochs=1000, solver="gd"):
28
+ if solver not in ("gd", "closed"):
29
+ raise ValueError("solver must be 'gd' or 'closed'")
30
+ self.lr = lr
31
+ self.epochs = epochs
32
+ self.solver = solver
33
+ self.m = 0.0
34
+ self.b = 0.0
35
+ self.history = []
36
+ self._fitted = False
37
+
38
+ @staticmethod
39
+ def _to_1d(a, name):
40
+ a = np.asarray(a, dtype=float).ravel()
41
+ if a.size == 0:
42
+ raise ValueError(f"{name} must not be empty")
43
+ return a
44
+
45
+ def fit(self, x, y):
46
+ x = self._to_1d(x, "x")
47
+ y = self._to_1d(y, "y")
48
+ if x.shape != y.shape:
49
+ raise ValueError("x and y must have the same length")
50
+ n = len(x)
51
+
52
+ if self.solver == "closed":
53
+ x_mean, y_mean = x.mean(), y.mean()
54
+ var = np.sum((x - x_mean) ** 2)
55
+ if var == 0:
56
+ raise ValueError("x has zero variance; cannot fit a line")
57
+ self.m = float(np.sum((x - x_mean) * (y - y_mean)) / var)
58
+ self.b = float(y_mean - self.m * x_mean)
59
+ else:
60
+ self.m, self.b = 0.0, 0.0
61
+ self.history = []
62
+ for _ in range(self.epochs):
63
+ error = y - (self.m * x + self.b)
64
+ d_m = (-2.0 / n) * np.sum(x * error)
65
+ d_b = (-2.0 / n) * np.sum(error)
66
+ self.m -= self.lr * d_m
67
+ self.b -= self.lr * d_b
68
+ self.history.append(float(np.mean(error ** 2)))
69
+
70
+ self._fitted = True
71
+ return self
72
+
73
+ def predict(self, x):
74
+ if not self._fitted:
75
+ raise RuntimeError("Model is not fitted yet. Call fit() first.")
76
+ return self.m * np.asarray(x, dtype=float) + self.b
77
+
78
+ def mse(self, x, y):
79
+ y = self._to_1d(y, "y")
80
+ return float(np.mean((y - self.predict(self._to_1d(x, "x"))) ** 2))
81
+
82
+ def score(self, x, y):
83
+ """R^2 coefficient of determination."""
84
+ y = self._to_1d(y, "y")
85
+ pred = self.predict(self._to_1d(x, "x"))
86
+ ss_res = np.sum((y - pred) ** 2)
87
+ ss_tot = np.sum((y - y.mean()) ** 2)
88
+ return float(1 - ss_res / ss_tot) if ss_tot != 0 else 0.0
89
+
90
+ def __repr__(self):
91
+ return f"LinearRegression(m={self.m:.4f}, b={self.b:.4f}, solver='{self.solver}')"
@@ -0,0 +1,51 @@
1
+ Metadata-Version: 2.4
2
+ Name: linreg-scratch
3
+ Version: 0.1.0
4
+ Summary: Simple linear regression from scratch using only NumPy
5
+ Author-email: Your Name <you@example.com>
6
+ License: MIT
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Operating System :: OS Independent
10
+ Requires-Python: >=3.8
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: numpy>=1.20
14
+ Dynamic: license-file
15
+
16
+ # linreg-scratch
17
+
18
+ Simple linear regression (`y = m*x + b`) implemented from scratch with NumPy.
19
+
20
+ ## Install
21
+
22
+ ```bash
23
+ pip install linreg-scratch
24
+ ```
25
+
26
+ ## Usage
27
+
28
+ ```python
29
+ import numpy as np
30
+ from linreg_scratch import LinearRegression
31
+
32
+ x = np.array([1, 2, 3, 4, 5])
33
+ y = np.array([3, 5, 7, 9, 11])
34
+
35
+ model = LinearRegression(lr=0.01, epochs=5000) # gradient descent
36
+ model.fit(x, y)
37
+
38
+ print(model.m, model.b) # slope, intercept
39
+ print(model.predict([6, 7])) # predictions
40
+ print(model.score(x, y)) # R^2
41
+
42
+ # exact solution instead of gradient descent
43
+ LinearRegression(solver="closed").fit(x, y)
44
+ ```
45
+
46
+ ## Development
47
+
48
+ ```bash
49
+ pip install -e . pytest
50
+ pytest
51
+ ```
@@ -0,0 +1,7 @@
1
+ linreg_scratch/__init__.py,sha256=TWJhZmv9UP2V0xcb66DlDmJb8ka6xH0X8QQz6bCNT14,90
2
+ linreg_scratch/model.py,sha256=JT7gmKNVYwI0jOQfhwKJkIN8u2qP1k5bmZ3G-Gw0tLw,2939
3
+ linreg_scratch-0.1.0.dist-info/licenses/LICENSE,sha256=v2spsd7N1pKFFh2G8wGP_45iwe5S0DYiJzG4im8Rupc,1066
4
+ linreg_scratch-0.1.0.dist-info/METADATA,sha256=W7DvOlolPVAbwMnin5sCEHSGi_NhDiJ8Oy7H3TXUSt8,1121
5
+ linreg_scratch-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ linreg_scratch-0.1.0.dist-info/top_level.txt,sha256=xZZF9E0leQErfcqmtp0cyTH_CtLAAHlzQkSlDckWDBo,15
7
+ linreg_scratch-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Your Name
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ linreg_scratch