numpy 如何使用scikit-learn拟合多项式曲线?

mwyxok5s  于 12个月前  发布在  其他
关注(0)|答案(4)|浏览(150)

问题上下文

在Python中使用scikit-learn,我尝试将二次多项式曲线拟合到一组数据,因此模型的形式为y = a2x^2 + a1x + a0,并且an系数将由模型提供。

问题

我不知道如何使用该软件包拟合多项式曲线,而且似乎很少有关于如何做到这一点的明确参考(我已经找了一段时间)。我看过this question on doing something similar with NumPy,还有this question which does a more complicated fit than I require

一个好的解决方案应该是什么样子

希望,一个好的解决方案会像这样(示例改编自我使用的线性拟合代码):

x = my_x_data.reshape(len(profile), 1)
y = my_y_data.reshape(len(profile), 1)
regression = linear_model.LinearRegression(degree=2) # or PolynomialRegression(degree=2) or QuadraticRegression()
regression.fit(x, y)

我想scikit-learn应该有这样的功能,因为它很常见(例如,在R中,可以在代码中提供拟合公式,并且它们应该能够在这种用例中互换)。

问题:

什么是一个好的方法来做到这一点,或者我可以在哪里找到有关如何正确地做到这一点的信息?

7nbnzgx9

7nbnzgx91#

可能重复:https://stats.stackexchange.com/questions/58739/polynomial-regression-using-scikit-learn
出于某种原因,使用scikit-learn来完成这一点是否至关重要?你想要的操作可以很容易地使用numpy执行:

z = np.poly1d(np.polyfit(x,y,2))

之后,z(x)返回x处的拟合值。
一个scikit-learn解决方案几乎可以肯定只是一个 Package 器,围绕着相同的代码。

gstyhher

gstyhher2#

我相信萨尔瓦多达利here的回答会回答你的问题。在scikit-learn中,从数据中构造多项式特征就足够了,然后在扩展的数据集上运行线性回归。如果您有兴趣阅读一些关于它的文档,您可以在这里找到更多信息。为了方便起见,我将发布萨尔瓦多达利提供的示例代码:

from sklearn.preprocessing import PolynomialFeatures
from sklearn import linear_model

X = [[0.44, 0.68], [0.99, 0.23]]
vector = [109.85, 155.72]
predict= [0.49, 0.18]

poly = PolynomialFeatures(degree=2)
X_ = poly.fit_transform(X)
predict_ = poly.fit_transform(predict)

clf = linear_model.LinearRegression()
clf.fit(X_, vector)
print clf.predict(predict_)
kt06eoxx

kt06eoxx3#

AGML的答案可以 Package 在scikit-learn兼容的类中,如下所示:

class PolyEstimator:
    def __init__(self, degree=2):
        self.degree = degree

    def fit(self, x, y):
        self.z = np.poly1d(np.polyfit(x.flatten().tolist(), y, self.degree))

    def predict(self, x):
        return self.z(x.flatten().tolist())
gmxoilav

gmxoilav4#

下面是如何在一个整洁的管道中完成它

from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler

model = Pipeline([
    ('scaler', StandardScaler()),
    ('poly', PolynomialFeatures(degree=3)),
    ('linear', LinearRegression())
])

model.fit(x, y)

model.predict([[1], [2]])

相关问题