python实现最小二乘法

发布于 2016-05-08  3877 次阅读


import numpy as np
from scipy.optimize import leastsq
import xlrd
import pylab as pl
def func(x, p):
a, b = p
return (a*x + b)
def residuals(p, x, y):
return func(x, p) - y
data=xlrd.open_workbook("data.xlsx")
table=data.sheet_by_index(0)
income=table.col_values(2)
spend=table.col_values(3)
X1=np.array(income, dtype=float)
X2=np.array(spend,dtype=float)

r = leastsq(residuals, [1, 1], args=(X1, X2))
print (r[0])
print (np.poly1d(r[0]))

x = np.linspace(0,100, 1000)
pl.plot(X1,X2,'*')
pl.plot(x, func(x, r[0]), label="fitting data")
pl.legend()
pl.show()