def gen_basis_fns(): X, y = hepatitis() gam = LinearGAM(lam=.6, fit_intercept=False).fit(X, y) XX = gam.generate_X_grid() plt.figure() fig, ax = plt.subplots(2,1) ax[0].plot(XX, gam._modelmat(XX, feature=0).A); ax[0].set_title('b-Spline Basis Functions') ax[1].scatter(X, y, facecolor='gray', edgecolors='none') ax[1].plot(XX, gam._modelmat(XX).A * gam.coef_); ax[1].plot(XX, gam.predict(XX), 'k') ax[1].set_title('Fitted Model') fig.tight_layout() plt.savefig('imgs/pygam_basis.png', dpi=300)
def constraints(): X, y = hepatitis(return_X_y=True) gam1 = LinearGAM(s(0, constraints='monotonic_inc')).fit(X, y) gam2 = LinearGAM(s(0, constraints='concave')).fit(X, y) fig, ax = plt.subplots(1, 2) ax[0].plot(X, y, label='data') ax[0].plot(X, gam1.predict(X), label='monotonic fit') ax[0].legend() ax[1].plot(X, y, label='data') ax[1].plot(X, gam2.predict(X), label='concave fit') ax[1].legend() fig.tight_layout() plt.savefig('imgs/pygam_constraints.png', dpi=300)
def constraints(): X, y = hepatitis() plt.figure() fig, ax = plt.subplots(1,2) gam = LinearGAM(constraints='monotonic_inc').fit(X, y) ax[0].plot(X, y, label='data') ax[0].plot(X, gam.predict(X), label='monotonic fit') ax[0].legend() gam = LinearGAM(constraints='concave').fit(X, y) ax[1].plot(X, y, label='data') ax[1].plot(X, gam.predict(X), label='concave fit') ax[1].legend() fig.tight_layout() plt.savefig('imgs/pygam_constraints.png', dpi=300)
def hepatitis_X_y(): # y is real # recommend LinearGAM return hepatitis(return_X_y=True)
XX = gam.generate_X_grid(term=i) pdep, confi = gam.partial_dependence(term=i, width=.95) ax.plot(XX[:, i], pdep) ax.plot(XX[:, i], confi, c='r', ls='--') ax.set_title(titles[i]) gam.accuracy(X, y) ###################################################### # constraints from pygam import LinearGAM, s from pygam.datasets import hepatitis X, y = hepatitis(return_X_y=True) X.shape gam1 = LinearGAM(s(0, constraints='monotonic_inc')).fit(X, y) gam2 = LinearGAM(s(0, constraints='concave')).fit(X, y) fig, ax = plt.subplots(1, 2) ax[0].plot(X, y, label='data') ax[0].plot(X, gam1.predict(X), label='monotonic fit') ax[0].legend() ax[1].plot(X, y, label='data') ax[1].plot(X, gam2.predict(X), label='concave fit') ax[1].legend() ######################################################