Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from typing import List
- from numpy import matrix, matmul, ndarray
- from numpy.linalg import inv
- tmp_m = [[0, 1],
- [1, 3],
- [2, 5],
- [3, 7]]
- tmp_p = 1
- def calc_a_plus(mat: matrix) -> ndarray:
- """
- Used to calcul the A+ = (A_T*A)^(-1) where x*=(A+)A_T.b
- :type mat: matrix
- :rtype: ndarray
- """
- mat_trans: ndarray = mat.transpose()
- res_matmul: ndarray = matmul(mat_trans, mat)
- a_plus: ndarray = inv(res_matmul)
- return a_plus
- def line_regression(
- main_mat: List[list],
- p: int,
- debug: bool = False)-> ndarray:
- """
- Used to calcul the main elements of Ax*=b
- :param main_mat: data: [[x, y], ..., [x, y]]
- :param p: polynomial degree of the result function
- :param debug: debug
- """
- mat: List[List[float]] = list()
- vec: list = list()
- for elem in main_mat:
- tmp: List[float] = list()
- for j in range(p + 1):
- tmp.append(pow(elem[0], j))
- mat.append(tmp)
- vec.append(elem[1])
- if debug:
- print("a = {}".format(mat))
- print("b = {}".format(vec))
- a_plus: ndarray = calc_a_plus(matrix(mat))
- tmp_res: ndarray = matmul(a_plus, matrix(mat).transpose())
- res: ndarray = matmul(tmp_res, vec)
- return res
- print("the result is : {}".format(line_regression(tmp_m, tmp_p, True)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement