I would like to calculate the derivative of a fitted GAM model a at specific points in pyGAM. The model contains only spline terms, such that it should be effectively a BSpline.
Indeed, use of pygam.utils.b_spline_basis gives a matrix, which I can multiply by a.coefsto recover the pyGAM prediction from a.predict.
The idea was to use the analytic derivative of the BSpline to get the derivative. See here or simply Wikipedia's BSpline article for more information.
I came up with this:
def GetGAM(x,y,err):
if len(x)>5:
gam=pygam.LinearGAM(pygam.s(0, n_splines=len(x)),penalties=__PenaltyD3,lam=0,fit_intercept=False)
gam=gam.fit(x,y, weights=1/err)
#print('done')
return gam
x1 = np.linspace(0,50,10)
y1=x1**2
err=np.ones(10)
a = GetGAM(x1,y1,err)
x0=pygam.utils.b_spline_basis(x1,pygam.utils.gen_edge_knots(x1,'numerical'),spline_order=3,n_splines=len(a.coef_), periodic=False)
x=pygam.utils.b_spline_basis(x1,pygam.utils.gen_edge_knots(x1[:-1],'numerical'),spline_order=2,n_splines=len(a.coef_), periodic=False)
To recover y1: [email protected]_works nicely.
To get the derivative I have
der2=x[:,1:]@(a.coef_[1:]-a.coef_[:-1])/((edges[1]-edges[0])/(len(a.coef_)))
I have also tried various variants of this, but could not get the solution (2*x1) to a satisfying degree.
I answered a related question, and suggested a numerical method for obtaining the derivative(s) of a pygam fit to data. Here is the link that may meet your requirements:-
Numerical derivative(s) of pygam spline.