【问题标题】:How to fit a polynomial curve to data using scikit-learn?如何使用 scikit-learn 将多项式曲线拟合到数据中?
【发布时间】:2015-12-16 02:06:26
【问题描述】:

问题背景

scikit-learn 与Python 结合使用,我试图将二次多项式曲线拟合到一组数据中,这样模型将采用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 中,可以在代码中提供拟合公式,并且它们应该可以互换那种用例)。

问题:

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

【问题讨论】:

    标签: python numpy machine-learning scikit-learn regression


    【解决方案1】:

    可能重复: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 解决方案几乎可以肯定是对相同代码的简单封装。

    【讨论】:

      【解决方案2】:

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

      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_)
      

      【讨论】:

      • 什么是“向量”?
      • vector 是目标向量。 (方程组 Xw = b 中的 b)。
      【解决方案3】:

      AGML 的答案可以封装在一个与 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())
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-09-02
        • 2018-02-16
        • 1970-01-01
        • 2017-08-13
        • 1970-01-01
        • 2020-03-18
        • 1970-01-01
        相关资源
        最近更新 更多