2015-12-15 19 views
1

我有幾個採樣點的數據集共享相同的x座標,並考慮到所有這些採樣點進行多項式擬合。使用下面的代碼如何從多項式擬閤中提取導數?

enter image description here

:如在這個曲線中正常工作

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) 

編輯:

我我也很樂意使用另一個模塊/庫來完成工作,所以我也樂於提供建議。

回答

1

既然你知道擬合多項式係數會得到你想要的?

deriv = np.polyder(ridge.coef_[::-1]) 
yd_plot = np.polyval(deriv,x_plot) 
+0

工作正常,謝謝(我upvoted和接受)。你有什麼想法如何避免擬合函數的負值?現在y_plot中的前幾個值是負數,不應該發生... – Cleb

+0

我不知道如何避免負值。 – screenpaver

+0

@Cleb這是多項式擬合所固有的。您可以使用較小的程度(並希望最好)或使用不同的模型。 –