Advertisement
Korotkodul

lsm_regressor_clean

Oct 5th, 2024
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.94 KB | None | 0 0
  1. from typing import Sequence, Union
  2. from numbers import Real
  3.  
  4. from regressor_abc import RegressorABC
  5.  
  6.  
  7. class RegressorLSM(RegressorABC):
  8.     _a: int
  9.     _b: int
  10.  
  11.     def fit(self, abscissa: Sequence[Real], ordinates: Sequence[Real]) -> None:
  12.         x_avg = 0
  13.         y_avg = 0
  14.         xy_avg = 0
  15.         x2_avg = 0
  16.         n = len(abscissa)
  17.         for i in range(n):
  18.             x_avg += abscissa[i]
  19.             y_avg += ordinates[i]
  20.             xy_avg += abscissa[i] * ordinates[i]
  21.             x2_avg += abscissa[i] ** 2
  22.         x_avg /= n
  23.         y_avg /= n
  24.         xy_avg /= n
  25.         x2_avg /= n
  26.         self._a = (xy_avg - x_avg * y_avg) / (x2_avg - x_avg ** 2)
  27.         self._b = y_avg - self._a * x_avg
  28.  
  29.     def predict(self, abscissa: Union[Real, Sequence[Real]]) -> list:
  30.         if isinstance(abscissa, Real):
  31.             return [self._a * abscissa + self._b]
  32.         return [(self._a * x + self._b) for x in abscissa]
  33.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement