如何使用scikit-learn将多项式曲线拟合到数据? [英] How to fit a polynomial curve to data using scikit-learn?
问题描述
在Python中使用 scikit-learn
,我试图将二次多项式曲线拟合到一组数据,以便模型的形式为 y = a2x ^ 2+ a1x + a0
和 an
系数将由模型提供.
Using scikit-learn
with Python, I'm trying to fit a quadratic polynomial curve to a set of data, so that the model would be of the form y = a2x^2 + a1x + a0
and the an
coefficients will be provided by a model.
我不知道如何使用该程序包来拟合多项式曲线,而且似乎很少有明确的参考资料(如何使用(我已经寻找了一段时间)).我已经看到有关使用NumPy进行类似操作的问题,以及
I don't know how to fit a polynomial curve using that package and there seem to be surprisingly few, clear references on how to do it (I've looked for a while). I've seen this question on doing something similar with NumPy, and also this question which does a more complicated fit than I require.
希望,这样一个好的解决方案(根据我使用的线性拟合代码改编而成的示例):
Hopefully, a good solution would go around like this (sample adapted from linear fit code that I'm using):
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
中,可以在-代码,并且对于这种用例,它们应该可以互换).
I would imagine scikit-learn
would have a facility like this, since it's pretty common (for example, in R
, the formula for fitting can be provided in-code, and they should be able to be pretty interchangeable for that kind of use-case).
执行此操作的好方法是什么,或者在哪里可以找到有关如何正确执行此操作的信息?
What is a good way to do this, or where can I find information about how to do this properly?
推荐答案
可能的重复项:https://stats.stackexchange.com/questions/58739/polynomial-regression-using-scikit-learn .
使用scikit-learn完成此操作是否出于某些原因至关重要?您可以使用numpy轻松执行所需的操作:
Is it crucial for some reason that this be done using scikit-learn? The operation you want can be performed very easily using numpy:
z = np.poly1d(np.polyfit(x,y,2))
之后, z(x)
返回 x
处的拟合值.
After which z(x)
returns the value of the fit at x
.
几乎可以肯定,一个scikit-learn解决方案只是封装相同的代码.
A scikit-learn solution would almost certainly be simply a wrapper around the same code.
这篇关于如何使用scikit-learn将多项式曲线拟合到数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!