Python 如何从多项式拟合中提取方程?
我的目标是将一些数据拟合到多项式函数,并获得包含拟合参数值的实际方程 我根据我的数据进行了调整,结果与预期一致 这是我的密码:Python 如何从多项式拟合中提取方程?,python,scikit-learn,regression,curve-fitting,Python,Scikit Learn,Regression,Curve Fitting,我的目标是将一些数据拟合到多项式函数,并获得包含拟合参数值的实际方程 我根据我的数据进行了调整,结果与预期一致 这是我的密码: 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
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
未存储所需参数 线性模型的系数存储在模型的截距
和系数
属性中
通过在已知模型中关闭正则化和馈送,可以更清楚地看到这一点;e、 g
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.])
还要注意的是,
多项式特征默认情况下包含一个偏差项,因此在脊线
中拟合截距对于小的α
大的来说是多余的。在我看来,有点隐蔽。我投了赞成票,后来接受了它。它是“隐藏的”,因为scikit learn是一个机器学习库,而不是一个统计建模库。一般来说,机器学习关注的是模型的输出,而不是模型的参数。有关此划分的经典讨论,请参阅。感谢链接!您会使用scikit learn进行此类参数估计,还是使用其他更合适的方法?我这样问是因为我想避免负值,我不确定使用此模块有多容易。对于您心目中的受约束统计建模,库可能是一个更好的选择。