具有numpy的多元多项式回归

MRo*_*lin 20 python statistics regression numpy

我有很多样本(y_i, (a_i, b_i, c_i)),y假设在a,b,c 多达一定程度上变化为多项式.例如,对于给定的一组数据和2级,我可能会生成该模型

y = a^2 + 2ab - 3cb + c^2 +.5ac

这可以使用最小二乘法完成,并且是numpy的polyfit例程的略微扩展.Python生态系统中是否存在标准实现?

Dav*_*man 15

sklearn提供了一种简单的方法.

建立一个在这里发布的例子:

#X is the independent variable (bivariate in this case)
X = array([[0.44, 0.68], [0.99, 0.23]])

#vector is the dependent data
vector = [109.85, 155.72]

#predict is an independent variable for which we'd like to predict the value
predict= [0.49, 0.18]

#generate a model of polynomial features
poly = PolynomialFeatures(degree=2)

#transform the x data for proper fitting (for single variable type it returns,[1,x,x**2])
X_ = poly.fit_transform(X)

#transform the prediction to fit the model type
predict_ = poly.fit_transform(predict)

#here we can remove polynomial orders we don't want
#for instance I'm removing the `x` component
X_ = np.delete(X_,(1),axis=1)
predict_ = np.delete(predict_,(1),axis=1)

#generate the regression object
clf = linear_model.LinearRegression()
#preform the actual regression
clf.fit(X_, vector)

print("X_ = ",X_)
print("predict_ = ",predict_)
print("Prediction = ",clf.predict(predict_))
Run Code Online (Sandbox Code Playgroud)

继承人的产量:

>>> X_ =  [[ 0.44    0.68    0.1936  0.2992  0.4624]
>>>  [ 0.99    0.23    0.9801  0.2277  0.0529]]
>>> predict_ =  [[ 0.49    0.18    0.2401  0.0882  0.0324]]
>>> Prediction =  [ 126.84247142]
Run Code Online (Sandbox Code Playgroud)


rep*_*cus 2

polyfit 确实有效,但是有更好的最小二乘最小化器。我会推荐 kmpfit,可在

http://www.astro.rug.nl/software/kapteyn-beta/kmpfittutorial.html

它比 polyfit 更强大,并且他们的页面上有一个示例,展示了如何进行简单的线性拟合,该拟合应该提供进行二阶多项式拟合的基础知识。


def model(p, v, x, w):       
   a,b,c,d,e,f,g,h,i,j,k = p      #coefficients to the polynomials      
   return  a*v**2 + b*x**2 + c*w**2 + d*v*x + e*v*w + f*x*w + g*v + h*x + i*y + k  

def residuals(p, data):        # Function needed by fit routine
   v, x, w, z = data            # The values for v, x, w and the measured hypersurface z
   a,b,c,d,e,f,g,h,i,j,k = p   #coefficients to the polynomials  
   return (z-model(p,v,x,w))   # Returns an array of residuals. 
                               #This should (z-model(p,v,x,w))/err if 
                               # there are error bars on the measured z values


#initial guess at parameters. Avoid using 0.0 as initial guess
par0 = [1.0, 1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0] 

#create a fitting object. data should be in the form 
#that the functions above are looking for, i.e. a Nx4 
#list of lists/tuples like (v,x,w,z) 
fitobj = kmpfit.Fitter(residuals=residuals, data=data)

# call the fitter 
fitobj.fit(params0=par0)
Run Code Online (Sandbox Code Playgroud)

这些事情的成功与否很大程度上取决于拟合的起始值,因此如果可能的话请仔细选择。由于有如此多的自由参数,找到解决方案可能是一个挑战。

  • 所以这个库可以工作,但它通过迭代方法解决问题。最小二乘多项式拟合可以通过求解线性系统一步完成。我在另一个答案中发布了使用 numpy 执行此操作的代码。 (2认同)