vswe
Published in

vswe

Least squares with Numpy

Find the optimum solution of linear equation in many unknow variable

Input.data

We want to find the b to achieve min(Ab — Y)²-

B = (AT * A)^-1 * AT * Y

filepath = "input.data"rows = []
col = []
with open(filepath) as fp:
line = fp.readline()
while line:
# convert string list to list
row = list(map(float, line.split()[0,6]))
rows.append(row)
col.append(float(line.split()[6]))
line = fp.readline()
x = np.array(rows)
y = np.array(col)
xt = x.T
xtx = xt.dot(x)
inv_xtx = np.linalg.inv(xtx)
b = inv_xtx.dot(xt).dot(y)
# result
print(b)
pred_y = x.dot(b)
square_err = np.sqrt((pred_y - y)**2)
mean_square_err = square_err.sum() / square_err.size
print("\nCount:", suare_err.size)
print("MSE: %.2f" %(mean_square_err))

Reference

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store