我有几个样本点的数据集共享相同的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
具有以下属性:
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
所以在理想的情况下,我希望有类似(伪代码)的东西:
myDerivative = model.derivative(x_plot)
编辑:
我也非常乐意使用另一个完成工作的模块/库,所以我也愿意接受建议。
答案 0 :(得分:1)
既然你知道拟合的多项式系数会得到你想要的吗?
deriv = np.polyder(ridge.coef_[::-1])
yd_plot = np.polyval(deriv,x_plot)