如何使用sklearn进行多项式回归

问题描述 投票:0回答:2

我有一些不适合线性回归的数据:

事实上应该“完全”拟合二次函数:

P = R*I**2 

我正在做这个:

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)

是否有机会通过执行以下操作来解决它:

model.fit([X,X**2],Y)
python pandas scikit-learn polynomials non-linear-regression
2个回答
5
投票

您可以使用 numpy 的 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()

出:

[  0.24052058   2.1426103   25.59437789]


1
投票

使用多项式特征。

import numpy as np
from sklearn.preprocessing import PolynomialFeatures

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

输出:

array([[1., 1., 1.],
       [1., 2., 4.],
       [1., 3., 9.]])
© www.soinside.com 2019 - 2024. All rights reserved.