Advertisement
VikkaLorel

non linear regression

Nov 19th, 2018
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.37 KB | None | 0 0
  1. from typing import List
  2.  
  3. from numpy import matrix, matmul, ndarray
  4. from numpy.linalg import inv
  5.  
  6. tmp_m = [[0, 1],
  7.          [1, 3],
  8.          [2, 5],
  9.          [3, 7]]
  10. tmp_p = 1
  11.  
  12.  
  13. def calc_a_plus(mat: matrix) -> ndarray:
  14.     """
  15.    Used to calcul the A+ = (A_T*A)^(-1) where x*=(A+)A_T.b
  16.  
  17.    :type mat: matrix
  18.    :rtype: ndarray
  19.    """
  20.     mat_trans: ndarray = mat.transpose()
  21.     res_matmul: ndarray = matmul(mat_trans, mat)
  22.     a_plus: ndarray = inv(res_matmul)
  23.     return a_plus
  24.  
  25.  
  26. def line_regression(
  27.         main_mat: List[list],
  28.         p: int,
  29.         debug: bool = False)-> ndarray:
  30.     """
  31.    Used to calcul the main elements of Ax*=b
  32.  
  33.    :param main_mat: data: [[x, y], ..., [x, y]]
  34.    :param p: polynomial degree of the result function
  35.    :param debug: debug
  36.    """
  37.     mat: List[List[float]] = list()
  38.     vec: list = list()
  39.     for elem in main_mat:
  40.         tmp: List[float] = list()
  41.         for j in range(p + 1):
  42.             tmp.append(pow(elem[0], j))
  43.         mat.append(tmp)
  44.         vec.append(elem[1])
  45.     if debug:
  46.         print("a = {}".format(mat))
  47.         print("b = {}".format(vec))
  48.     a_plus: ndarray = calc_a_plus(matrix(mat))
  49.     tmp_res: ndarray = matmul(a_plus, matrix(mat).transpose())
  50.     res: ndarray = matmul(tmp_res, vec)
  51.     return res
  52.  
  53.  
  54. print("the result is : {}".format(line_regression(tmp_m, tmp_p, True)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement