Which is the simplest way to make a polynomial regression with sklearn?

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-28 09:31:18

问题


I have some data that doesn't fit a linear regression,

In fact should fit 'exactly' a quadratic function:

P = R*I**2 

I'm miking this:

model = sklearn.linear_model.LinearRegression()

X = alambres[alambre]['mediciones'][x].reshape(-1, 1)
Y = alambres[alambre]['mediciones'][y].reshape(-1, 1)
model.fit(X,Y)

Is there any chance to solve it by doing something like:

model.fit([X,X**2],Y) ?


回答1:


You can use numpy's polyfit.

import numpy as np
from matplotlib import pyplot as plt
X = np.linspace(0, 100, 50)
Y = 23.24 + 2.2*X + 0.24*(X**2) + 10*np.random.randn(50) #added some noise
coefs = np.polyfit(X, Y, 2)
print(coefs)
p = np.poly1d(coefs)
plt.plot(X, Y, "bo", markersize= 2)
plt.plot(X, p(X), "r-") #p(X) evaluates the polynomial at X
plt.show()

Out:

[  0.24052058   2.1426103   25.59437789]




回答2:


Use PolynomialFeatures.

import numpy as np
from sklearn.preprocessing import PolynomialFeatures

x = np.array([[1,],[2,],[3,]])
X = PolynomialFeatures(degree=2).fit_transform(x)
X

Output:

array([[1., 1., 1.],
       [1., 2., 4.],
       [1., 3., 9.]])


来源:https://stackoverflow.com/questions/37110879/which-is-the-simplest-way-to-make-a-polynomial-regression-with-sklearn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!