def fit_line(self, x, y):
# Takes x data (1d array) and y data (Nd array)
# last dimension of y array is fit dimension
# Solve linear least squares matrix equations for m, b of y = mx + b
# Returns m, b
# y_i = 1*b + x_i * m
# Generate X matrix (X_i = [1, x_i])
X = np.ones((len(x), 2))
X[:,1] = x[:]
# Solve "normal equations" for B that minimizes least sq
# B = C*y = {((X^T)X)^(-1) * (X^T)} y
C = np.linalg.inv(X.T.dot(X)).dot(X.T)
if len(y.shape) < 2:
B = C.dot(y)
else:
B = C.dot(np.swapaxes(y, -1, 1))
return B[1], B[0]
评论列表
文章目录