Advertisement
Korotkodul

nonparametric_regressos

Oct 5th, 2024
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.11 KB | None | 0 0
  1. from typing import Sequence, Union
  2. from numbers import Real
  3.  
  4. from regressor_abc import RegressorABC
  5.  
  6. #regressors
  7. class NonparametricRegressor(RegressorABC):
  8.     _k: int
  9.     _train: list
  10.  
  11.     def __init__(self, k: int):
  12.         self._k = k
  13.         self._train = list(zip([]))
  14.  
  15.     def fit(self, abscissa: Sequence[Real], ordinates: Sequence[Real]) -> None:
  16.  
  17.         self._train = list(zip(abscissa, ordinates))
  18.         print(self._train)
  19.  
  20.  
  21.     def predict(self, abscissa: Union[Real, Sequence[Real]]) -> list:
  22.         if isinstance(abscissa, Real):
  23.             return self._predict(abscissa)
  24.         return [self._predict(x) for x in abscissa]
  25.  
  26.     def _predict(self, x: Real):
  27.         ro = [(abs(x - xi), yi) for xi, yi in self._train]
  28.         ro.sort()
  29.  
  30.         h = ro[self._k][0]
  31.         K = [self._K(roi / h) for roi, _ in ro]
  32.         y = sum(ro[i][1] * K[i] for i in range(len(ro)))
  33.         y /= sum(K)
  34.         return y
  35.  
  36.     @staticmethod
  37.     def _K(x):
  38.         if abs(x) <= 1:
  39.             return 3 / 4 * (1 - x ** 2)
  40.         return 0
  41. from typing import Sequence, Union
  42. from numbers import Real
  43.  
  44. from regressor_abc import RegressorABC
  45.  
  46. #regressors
  47. class NonparametricRegressor(RegressorABC):
  48.     _k: int
  49.     _train: list
  50.  
  51.     def __init__(self, k: int):
  52.         self._k = k
  53.         self._train = list(zip([]))
  54.  
  55.     def fit(self, abscissa: Sequence[Real], ordinates: Sequence[Real]) -> None:
  56.  
  57.         self._train = list(zip(abscissa, ordinates))
  58.         print(self._train)
  59.  
  60.  
  61.     def predict(self, abscissa: Union[Real, Sequence[Real]]) -> list:
  62.         if isinstance(abscissa, Real):
  63.             return self._predict(abscissa)
  64.         return [self._predict(x) for x in abscissa]
  65.  
  66.     def _predict(self, x: Real):
  67.         ro = [(abs(x - xi), yi) for xi, yi in self._train]
  68.         ro.sort()
  69.  
  70.         h = ro[self._k][0]
  71.         K = [self._K(roi / h) for roi, _ in ro]
  72.         y = sum(ro[i][1] * K[i] for i in range(len(ro)))
  73.         y /= sum(K)
  74.         return y
  75.  
  76.     @staticmethod
  77.     def _K(x):
  78.         if abs(x) <= 1:
  79.             return 3 / 4 * (1 - x ** 2)
  80.         return 0
  81.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement