Python 如何从多项式拟合中提取导数?
我有几个数据集的样本点共享相同的x坐标,并做了多项式拟合考虑到所有这些样本点。工作正常,如下图所示: 使用以下代码:Python 如何从多项式拟合中提取导数?,python,scikit-learn,curve-fitting,derivative,Python,Scikit Learn,Curve Fitting,Derivative,我有几个数据集的样本点共享相同的x坐标,并做了多项式拟合考虑到所有这些样本点。工作正常,如下图所示: 使用以下代码: 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
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([[3620000.,26000000.,187000000.,348000000.,475000000.,483000000.,456000000.,384000000.],
[3750000.,25900000.,187000000.,362000000.,449000000.,465000000.,488000000.,408000000.],
[3720000.,26100000.,184000000.,341000000.,455000000.,458000000.,446000000.,430000000.]])
x_all = np.ravel(x + np.zeros_like(y))
y_all = np.ravel(y)
plt.scatter(x, y[0], label="training points 1", c='r')
plt.scatter(x, y[1], label="training points 2", c='b')
plt.scatter(x, y[2], label="training points 3", c='g')
x_plot = np.linspace(0, max(x), 100)
for degree in np.arange(5, 6, 1):
model = make_pipeline(PolynomialFeatures(degree), Ridge(alpha=50, fit_intercept=False))
model.fit(x_all[:, None], y_all)
y_plot = model.predict(x_plot[:, None])
plt.plot(x_plot, y_plot, label="degree %d" % degree)
ridge = model.named_steps['ridge']
print(degree, ridge.coef_)
plt.legend(loc='best')
plt.show()
我真正感兴趣的不是拟合多项式的方程,而是它的实际导数
是否有直接获取拟合函数导数的方法?上述代码中的对象模型具有以下属性:
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
因此,在理想情况下,我希望有一些类似(伪代码):
编辑:
我也非常乐意使用另一个模块/库来完成这项工作,因此我也愿意听取建议。既然你知道拟合多项式系数,这会得到你想要的吗
deriv = np.polyder(ridge.coef_[::-1])
yd_plot = np.polyval(deriv,x_plot)
很好,谢谢(我投了赞成票并接受了)。你知道如何避免拟合函数的负值吗?现在y_图中的前几个值是负数,这是不应该发生的…我不知道如何避免负数。@Cleb这是多项式拟合固有的。您可以使用较小的度数(希望最好),也可以使用不同的型号。@toasted_flakes:谢谢;较小的学位不好用。你会建议其他什么模型(可以任意复杂)?@Cleb我不认为这总是可行的,但使用任何可以指定损失函数并使其变得更复杂的模型∞ 因为负面预测可以奏效吗?否则,一种愚蠢的方法是执行prediction=max(prediction,0)
-edit:定义不等式约束最小二乘估计量,它看起来就像您想要的。
deriv = np.polyder(ridge.coef_[::-1])
yd_plot = np.polyval(deriv,x_plot)