Advertisement
Korotkodul

lsm_regressor

Oct 5th, 2024 (edited)
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.43 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.  
  34.  
  35. from random import *
  36. file=open("testlsm.txt","w")
  37. a=1
  38. b=0
  39. for x in range(1,1000):
  40.     otkl=randint(-1000,1000)/100
  41.     file.write(str(x)+" "+str(a*x+b+otkl)+"\n")
  42. file.close()
  43.  
  44. data=open("testlsm.txt").readlines()
  45. print("data", data)
  46. A=[list(map(float,i.split()))[0] for i in data]
  47. B=[list(map(float,i.split()))[1] for i in data]
  48. print("A", A)
  49. print("B", B)
  50. RegressorLSM=RegressorLSM()
  51. RegressorLSM.fit(A,B)
  52. print("a b ", RegressorLSM._a, RegressorLSM._b)
  53. print(RegressorLSM.predict(A))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement