如何从多项式拟合中提取方程?

Posted

技术标签:

【中文标题】如何从多项式拟合中提取方程?【英文标题】:How to extract equation from a polynomial fit? 【发布时间】:2016-02-25 21:43:18 【问题描述】:

我的目标是将一些数据拟合到多项式函数中,并获得包含拟合参数值的实际方程。

我根据我的数据调整了this example,结果符合预期。

这是我的代码:

import numpy as np
import matplotlib.pyplot as plt

from sklearn.linear_model import Ridge
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline


x = np.array([0., 4., 9., 12., 16., 20., 24., 27.])
y = np.array([2.9,4.3,66.7,91.4,109.2,114.8,135.5,134.2])

x_plot = np.linspace(0, max(x), 100)
# create matrix versions of these arrays
X = x[:, np.newaxis]
X_plot = x_plot[:, np.newaxis]

plt.scatter(x, y, label="training points")

for degree in np.arange(3, 6, 1):
    model = make_pipeline(PolynomialFeatures(degree), Ridge())
    model.fit(X, y)
    y_plot = model.predict(X_plot)
    plt.plot(x_plot, y_plot, label="degree %d" % degree)

plt.legend(loc='lower left')

plt.show()

但是,我现在不知道在哪里提取实际方程和拟合参数值以进行相应的拟合。我在哪里可以访问实际的拟合方程?

编辑:

变量model具有以下属性:

model.decision_function  model.fit_transform      model.inverse_transform  model.predict            model.predict_proba      model.set_params         model.transform          
model.fit                model.get_params         model.named_steps        model.predict_log_proba  model.score              model.steps

model.get_params 不存储所需的参数。

【问题讨论】:

【参考方案1】:

线性模型的系数存储在模型的intercept_coeff_属性中。

您可以通过关闭正则化并输入已知模型来更清楚地看到这一点;例如

import numpy as np
from sklearn.linear_model import Ridge
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures

x = 10 * np.random.random(100)
y = -4 + 2 * x - 3 * x ** 2

model = make_pipeline(PolynomialFeatures(2), Ridge(alpha=1E-8, fit_intercept=False))
model.fit(x[:, None], y)
ridge = model.named_steps['ridge']
print(ridge.coef_)
# array([-4.,  2., -3.])

另请注意,PolynomialFeatures 默认包含一个偏差项,因此在Ridge 中拟合截距对于小的alpha 将是多余的。

【讨论】:

太好了,这行得通。在我看来,有点隐藏。我支持它并稍后接受它。 它是“隐藏的”,因为 scikit-learn 是一个机器学习库,而不是统计建模库。一般来说,机器学习关注模型的输出而不是模型的参数。请参阅Statistical Modeling: The Two Cultures 了解有关这种分歧的经典讨论。 感谢您的链接!您会使用 scikit-learn 进行这种参数估计,还是其他更合适的方法?我问是因为我想要例如为了避免负值,我不确定使用这个模块有多容易。 statsmodels 库可能是您想要的受限统计建模的更好选择。

以上是关于如何从多项式拟合中提取方程?的主要内容,如果未能解决你的问题,请参考以下文章

二次曲线拟合

二次曲线拟合

二次曲线拟合

曲线拟合(多项式标准椭圆方程)最小二乘法

matlab中如何拟合光滑曲线

OpenCV曲线拟合与圆拟合