|
|
|
@ -19,13 +19,13 @@ class Regression:
@@ -19,13 +19,13 @@ class Regression:
|
|
|
|
|
def r2(self) -> float: |
|
|
|
|
return self.score |
|
|
|
|
|
|
|
|
|
def predict(self, x: int | float = None, y: int | float = None) -> float: |
|
|
|
|
def predict(self, *, x: int | float = None, y: int | float = None) -> float: |
|
|
|
|
"""predict a value if x or y is given""" |
|
|
|
|
if x is not None: |
|
|
|
|
return self.intercept + x * self.coefficient |
|
|
|
|
if y is not None: |
|
|
|
|
return (y - self.intercept) / self.coefficient |
|
|
|
|
msg = "predict() expects 1 argument, got 0" |
|
|
|
|
msg = "predict() expects a keyword argument 'x' or 'y'" |
|
|
|
|
raise TypeError(msg) |
|
|
|
|
|
|
|
|
|
def to_dict(self): |
|
|
|
@ -65,14 +65,21 @@ def test_linear_regression(example_data):
@@ -65,14 +65,21 @@ def test_linear_regression(example_data):
|
|
|
|
|
def test_regression_predict(example_data): |
|
|
|
|
regression = linear_regression(example_data, x="A", y="B") |
|
|
|
|
|
|
|
|
|
prediction = regression.predict(10) |
|
|
|
|
prediction = regression.predict(x=10) |
|
|
|
|
|
|
|
|
|
assert pytest.approx(30.7) == prediction |
|
|
|
|
assert pytest.approx(10) == regression.predict(y=prediction) |
|
|
|
|
|
|
|
|
|
with pytest.raises(TypeError, match="expects 1 argument"): |
|
|
|
|
|
|
|
|
|
def test_regression_predict_exceptions(example_data): |
|
|
|
|
regression = linear_regression(example_data, x="A", y="B") |
|
|
|
|
|
|
|
|
|
with pytest.raises(TypeError, match="expects a keyword"): |
|
|
|
|
regression.predict() |
|
|
|
|
|
|
|
|
|
with pytest.raises(TypeError, match="takes 1 positional argument but"): |
|
|
|
|
regression.predict(1) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_regression_to_dict(example_data): |
|
|
|
|
regression = linear_regression(example_data, x="A", y="B") |
|
|
|
|