Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
94 commits
Select commit Hold shift + click to select a range
b6b1e41
adding 2 sample files
DonBeo May 25, 2015
91aef16
starting some examples
DonBeo May 25, 2015
0b1adf2
b splines derivative
May 26, 2015
1a8349a
update
DonBeo May 28, 2015
c0349c8
up
DonBeo May 28, 2015
059e056
cost function
DonBeo May 28, 2015
e1a32c6
cost function
DonBeo May 28, 2015
3707349
fs
DonBeo May 29, 2015
c54d7ab
grad method in penalty function
DonBeo May 29, 2015
b574363
optimize the cost function
DonBeo May 29, 2015
daead9e
update grad in penalized cost function
DonBeo May 29, 2015
2d5c314
update grad in penalized cost function
DonBeo May 29, 2015
140305d
use penalizedMixin
DonBeo Jun 2, 2015
1fda444
use penalizedMixin
DonBeo Jun 2, 2015
85b7354
logit_gam
DonBeo Jun 2, 2015
2ad8eaf
up
DonBeo Jun 3, 2015
cacc545
up
DonBeo Jun 3, 2015
b6fe4f4
up
DonBeo Jun 4, 2015
cc11922
up
DonBeo Jun 4, 2015
4f2bfb5
pi
DonBeo Jun 5, 2015
3d5985c
up
DonBeo Jun 5, 2015
2046f98
clean the code
DonBeo Jun 6, 2015
85c6f64
make plots
DonBeo Jun 6, 2015
882fd0c
update
DonBeo Jun 9, 2015
3e3db5d
draft or multivariate gam
DonBeo Jun 9, 2015
4ef250b
multivariate gam
DonBeo Jun 10, 2015
b1f137e
multivariate gam
DonBeo Jun 12, 2015
40ebc81
up
DonBeo Jun 12, 2015
a7dbce5
up
DonBeo Jun 15, 2015
59ffd84
up
DonBeo Jun 16, 2015
e802ab3
add tests
DonBeo Jun 16, 2015
478fdaf
up
DonBeo Jun 16, 2015
984c8f1
up
DonBeo Jun 16, 2015
6eadc08
up
DonBeo Jun 16, 2015
98bcae5
up
DonBeo Jun 17, 2015
3adf3e1
up
DonBeo Jun 17, 2015
127b35f
ip
DonBeo Jun 17, 2015
13f86c0
review code
DonBeo Jun 18, 2015
2a25873
clean the PR
DonBeo Jun 18, 2015
3735b1c
REF: add GLMGAMResults class (inherited fit uses attribute _results_c…
josef-pkt Jun 18, 2015
3e4f91c
Merge pull request #2 from josef-pkt/luca_gam_2435
DonBeo Jun 19, 2015
08dce2b
edit gam
DonBeo Jun 19, 2015
b96fa74
update multivariate gam
DonBeo Jun 19, 2015
5e66fdf
adjust poly_basis intercept
DonBeo Jun 19, 2015
40837fc
up
DonBeo Jun 19, 2015
77ba9f3
improve gam plot
DonBeo Jun 19, 2015
1cf37a7
BUG: fix import paths, mainly for tests, move example
josef-pkt Jun 23, 2015
a2e62d4
Merge pull request #3 from josef-pkt/luca_gam_2435
DonBeo Jun 24, 2015
4e2bc69
significance test
DonBeo Jun 29, 2015
d24d973
test for gam significance
DonBeo Jun 29, 2015
7cfc313
compute df
DonBeo Jul 1, 2015
e2d829a
partial_predict
DonBeo Jul 6, 2015
38f633d
update significance and partial plot
DonBeo Jul 6, 2015
19cdffb
update partial_values and partial_plot
DonBeo Jul 7, 2015
a76b7b8
cross validation
DonBeo Jul 8, 2015
c44ead5
crsoo validation
DonBeo Jul 9, 2015
d4b4298
cross validation test
DonBeo Jul 9, 2015
c447ac1
new kfoldcv
DonBeo Jul 10, 2015
b028c84
new version of cross validation
DonBeo Jul 10, 2015
e20d473
update cv module
DonBeo Jul 13, 2015
a48da01
pirls draft
DonBeo Jul 17, 2015
4f265c0
update pirls
DonBeo Jul 18, 2015
960a6bf
add fit pirls method
DonBeo Jul 21, 2015
9af50ba
refactoring
DonBeo Jul 29, 2015
a4ac594
refactor gam cross validation
DonBeo Jul 29, 2015
db58f0e
update tests after refactoring
DonBeo Jul 30, 2015
d70d04d
MAINT Python 2 compatibility
josef-pkt Jul 30, 2015
f9d8670
update gam examples after refactoring
DonBeo Jul 30, 2015
56ebaf5
Merge pull request #4 from josef-pkt/gam_2435_https
DonBeo Jul 30, 2015
21fa9a8
partial plot updated
DonBeo Jul 31, 2015
e8139a9
update gam example
DonBeo Jul 31, 2015
f43182e
update gam cv
DonBeo Aug 1, 2015
0e617b0
update gam cv
DonBeo Aug 2, 2015
c5f3206
correct bug in GAM cross validation
DonBeo Aug 3, 2015
b599aa5
solve bug in test_smooth_basis
DonBeo Aug 3, 2015
afae717
add gam pirls example
DonBeo Aug 3, 2015
60aabdd
pirls2
DonBeo Aug 6, 2015
e3fcc80
update pirls2
DonBeo Aug 6, 2015
ba05fd3
solve bug in pirls2
DonBeo Aug 7, 2015
e7aa40f
update pirls
DonBeo Aug 8, 2015
6d879b5
test cubic cyclic splines
DonBeo Aug 10, 2015
918a0b9
add ipython notebook
DonBeo Aug 10, 2015
bd3eb9f
update ipython notebook
DonBeo Aug 11, 2015
9a5681e
add cubic regression splines
DonBeo Aug 11, 2015
70f7059
attempt to use pirls as a fit method
DonBeo Aug 12, 2015
df4fe4b
pirls as fit method update
DonBeo Aug 12, 2015
c3c988f
uniform smoothers structure
DonBeo Aug 13, 2015
0c27515
make pirls a fit option
DonBeo Aug 13, 2015
14c93c0
solve bug in fit
DonBeo Aug 13, 2015
fe4495f
update test and examples
DonBeo Aug 14, 2015
139509b
update GamLogit
DonBeo Aug 14, 2015
2e9b5d7
update tests
Aug 20, 2015
c0a9cfc
update tests
Aug 20, 2015
25c90b2
improve gam.partial_values
Dec 23, 2015
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ marks.bzr
# Mac droppings
.DS_Store
help
# idea pycharm
.idea/

# Project specific
statsmodels/version.py
Expand All @@ -58,3 +60,4 @@ hash_dict.pickle
rehab.table
salary.table
.ipynb_checkpoints

4 changes: 4 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
numpy
scipy
pandas
matplotlib
11 changes: 11 additions & 0 deletions statsmodels/compat/python.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,17 @@ def get_class(func):
#Python 3
return func.__self__.__class__

def with_metaclass(meta, *bases):
"""Create a base class with a metaclass."""
# This requires a bit of explanation: the basic idea is to make a dummy
# metaclass for one level of class instantiation that replaces itself with
# the actual metaclass.
class metaclass(meta):
def __new__(cls, name, this_bases, d):
return meta(name, bases, d)
return type.__new__(metaclass, 'temporary_class', (), {})


try:
combinations = itertools.combinations
except:
Expand Down
4 changes: 2 additions & 2 deletions statsmodels/genmod/generalized_linear_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,6 @@ class GLM(base.LikelihoodModel):

def __init__(self, endog, exog, family=None, offset=None, exposure=None,
missing='none', **kwargs):

if (family is not None) and not isinstance(family.link, tuple(family.safe_links)):
import warnings
warnings.warn("The %s link function does not respect the domain of the %s family." %
Expand Down Expand Up @@ -763,7 +762,8 @@ def _fit_gradient(self, start_params=None, method="newton",
self.mu = self.predict(rslt.params)
self.scale = self.estimate_scale(self.mu)

glm_results = GLMResults(self, rslt.params,
results_class = getattr(self, '_results_class', GLMResults)
glm_results = results_class(self, rslt.params,
rslt.normalized_cov_params / self.scale,
self.scale,
cov_type=cov_type, cov_kwds=cov_kwds,
Expand Down
301 changes: 301 additions & 0 deletions statsmodels/sandbox/examples/gam_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,301 @@
__author__ = 'Luca Puggini: <[email protected]>'
__date__ = '08/07/15'


import numpy as np
import matplotlib.pyplot as plt
from statsmodels.sandbox.gam_gsoc2015.smooth_basis import (UnivariateBSplines, UnivariatePolynomialSmoother, BSplines,
PolynomialSmoother, UnivariateCubicSplines)
from statsmodels.sandbox.gam_gsoc2015.gam import UnivariateGamPenalty, LogitGam, GLMGam, MultivariateGamPenalty
import statsmodels.api as sm
from statsmodels.sandbox.gam_gsoc2015.gam_cross_validation.gam_cross_validation import MultivariateGAMCV, MultivariateGAMCVPath
from statsmodels.sandbox.gam_gsoc2015.gam_cross_validation.cross_validators import KFold

sigmoid = np.vectorize(lambda x: 1.0/(1.0 + np.exp(-x)))



###############################################

example = None #'ex1'
if example == 'ex1':
print(example)

n = 100
# make the data
x = np.linspace(-10, 10, n)
y = 1/(1 + np.exp(-x*x))
mu = y.mean()
y[y > mu] = 1
y[y < mu] = 0

# make the splines basis ##
df = 10
degree = 5
x = x - x.mean()

univ_bsplines = UnivariateBSplines(x, degree=degree, df=df)

# train the gam logit model ##
alphas = [0, 0.1, 1, 10]

for i, alpha in enumerate(alphas):
plt.subplot(2, 2, i+1)
params0 = np.random.normal(0, 1, df)
gp = UnivariateGamPenalty(univ_bsplines, wts=1, alpha=alpha)
g = LogitGam(y, univ_bsplines.basis_, penal=gp)
res_g = g.fit()
plt.plot(x, sigmoid(np.dot(univ_bsplines.basis_, res_g.params)))
plt.plot(x, y, '.')
plt.ylim(-1, 2)
plt.title('alpha=' + str(alpha))
plt.show()


if example == 'ex2':
# Logit 2
print(example)

spector_data = sm.datasets.spector.load()
spector_data.exog = sm.add_constant(spector_data.exog)

y = spector_data.endog
X = spector_data.exog
x = X[:, 2]

x = x - x.mean()
degree = 4
univ_bsplines = UnivariateBSplines(x, degree=degree, df=df)
for i, alpha in enumerate(alphas):
gp = UnivariateGamPenalty(univ_bsplines, alpha=alpha)
gam = LogitGam(y, univ_bsplines.basis_, penal = gp)
res_gam = gam.fit(method='nm', max_start_irls=0,
disp=1, maxiter=5000, maxfun=5000)
plt.subplot(2, 2, i+1)
plt.plot(x, sigmoid(np.dot(univ_bsplines.basis_, res_gam.params)), 'o')
plt.plot(x, y, '.')
plt.title('alpha=' + str(alpha))
plt.ylim(-1, 2)
plt.show()


if example == 'ex3':
# GAM GLM
print(example)

# y is continuous
n = 200
x = np.linspace(-10, 10, n)
y = x * x + np.random.normal(0, 5, n)
y -= y.mean()

x = x - x.mean()
univ_bsplines = UnivariateBSplines(x, degree=degree, df=df)
plt.figure()
alphas = [0, 0.001, 0.01, 100]
for i, alpha in enumerate(alphas):
plt.subplot(2, 2, i+1)

# train the model
gp = UnivariateGamPenalty(univ_bsplines, alpha=alpha)
glm_gam = GLMGam(y, univ_bsplines.basis_, penal = gp)
res_glm_gam = glm_gam.fit(method='nm', max_start_irls=0,
disp=1, maxiter=5000, maxfun=5000)
plt.plot(x, np.dot(univ_bsplines.basis_, res_glm_gam.params))
plt.plot(x, y, '.')
plt.title('GLM alpha=' + str(alpha))
plt.show()

#example = 'ex4'
if example == 'ex4':
# Multivariate GAM
print(example)
np.random.seed(0)
n = 100
x1 = np.linspace(-1, 1, n)
x2 = np.linspace(0, 1, n)

poly = x1*x1*x1 + x2*x2 + np.random.normal(0, .5, n)
y = sigmoid(poly)
mu = y.mean()
yc = y.copy()
y[y > mu] = 1
y[y <= mu] = 0

degree1 = 3
degree2 = 3
df = 3

x = np.vstack([x1, x2]).T
bsplines = BSplines(x, [df, df], [degree1, degree2])

alpha = [30] * 2
mgp = MultivariateGamPenalty(bsplines, alpha=alpha, wts=[1, 1])

mLG = LogitGam(y, bsplines.basis_, penal=mgp)
res_mLG = mLG.fit(maxiter=1000, tol=1e-13, method='nm')

y_est = np.dot(bsplines.basis_, res_mLG.params)
y_est = sigmoid(y_est)

plt.plot(y_est, label='y est')
plt.plot(y, '.', label='y')
plt.legend(loc='best')
plt.ylim(-0.2, 1.2)
plt.show()

if example == 'ex5':
print(example)

# Multivariate GLMGam.
n = 200
x = np.zeros(shape=(n, 2))
x[:, 0] = np.linspace(-10, -5, n)
x[:, 1] = np.linspace(5, 10, n)

y = x[:, 0]**3 + x[:, 1]**2 + np.random.normal(0, 10, n)
poly = PolynomialSmoother(x, degrees=[5, 5])

gp = MultivariateGamPenalty(poly, alpha=[0, 0], wts=[1, 1])
gam = GLMGam(y, poly.basis_, penal=gp)
gam_ris = gam.fit()


gam_ris.plot_partial(poly, plot_se=False)
plt.show()
print(gam_ris.params)

plt.plot(y, '.')
plt.plot(gam_ris.predict(poly.basis_, '.'))
plt.show()

if example == 'ex6':
print(example)

# Multivariate Gam CV
def cost(y1, y2):
return np.linalg.norm(y1 - y2) / len(y2)

cv = KFold(k_folds=5, shuffle=True)
gam_cv = MultivariateGAMCV(poly, alphas=[1, 1], gam=GLMGam, cost=cost, y=y, cv=cv)
ris_gam_cv = gam_cv.fit()

print('Cross validation error=', ris_gam_cv)

# Multivariate GAM CV path

alphas = np.linspace(0, 10, 5)
gam_cv_path = MultivariateGAMCVPath(poly, alphas=[alphas, alphas], gam=GLMGam, cost=cost, y=y, cv=cv).fit()

print(gam_cv_path.alpha_cv_, gam_cv_path.cv_error_)

#example = 'ex7'
if example == 'ex7':
print(example)

# GAM PIRLS
from statsmodels.sandbox.gam_gsoc2015.smooth_basis import UnivariateCubicSplines

n = 500
x = np.random.uniform(-1, 1, n)

y = 10*x**3 - 10*x + np.random.normal(0, 1, n)

y -= y.mean()
cs = UnivariateCubicSplines(x, 10)

# required only to initialize the gam. they have no influence on the result.
dummy_smoother = PolynomialSmoother(x, [2])
gp = MultivariateGamPenalty(dummy_smoother, alpha=[0])
for i, alpha in enumerate([0, 1, 5, 10]):

gam = GLMGam(y, cs.basis_, penal=gp)
gam_res = gam._fit_pirls(y=y, spl_x=cs.basis_, spl_s=cs.s, alpha=alpha)
y_est = gam_res.predict(cs.basis_)

plt.subplot(2, 2, i+1)
plt.plot(x, y, '.')
plt.plot(x, y_est, '.')
plt.title('alpha=' + str(alpha))

plt.show()

#example = 'ex8'
if example == 'ex8':
print(example)
np.random.seed(0)
# Multivariate GAM PIRLS
n = 500
x1 = np.random.uniform(-1, 1, n)
y1 = 10*x1**3 - 10*x1 + np.random.normal(0, 3, n)
y1 -= y1.mean()
x2 = np.random.uniform(-1, 1, n)
y2 = x2**2 + np.random.normal(0, 0.5, n)
y2 -= y2.mean()

Y = y1 + y2
cs1 = UnivariateCubicSplines(x1, 10)
cs2 = UnivariateCubicSplines(x2, 10)

spl_X = np.hstack([cs1.basis_, cs2.basis_])
spl_S = [cs1.s, cs2.s]

n_var1 = cs1.basis_.shape[1]
n_var2 = cs2.basis_.shape[1]

gam = GLMGam(y1, cs1.basis_)

i = 0
for alpha1, alpha2 in zip([0, 1, 2], [0, 1, 2]):

gam_results = gam._fit_pirls(Y, spl_X, spl_S, alpha=[alpha1, alpha2])
y1_est = np.dot(cs1.basis_, gam_results.params[:n_var1])
y2_est = np.dot(cs2.basis_, gam_results.params[n_var1:])

y1_est -= y1_est.mean() # TODO: the estimate is good but has a very large mean. Why is this happening?
y2_est -= y2_est.mean()

i += 1
plt.subplot(3, 2, i)
plt.title('x1 alpha=' + str(alpha1))
plt.plot(x1, y1, '.', label='Real', c='green')
plt.plot(x1, y1_est, '.', label='Estimated', c='blue')

i += 1
plt.subplot(3, 2, i)
plt.title('x2 alpha=' + str(alpha2))
plt.plot(x2, y2, '.', label='Real', c='green')
plt.plot(x2, y2_est, '.', label='Estimated', c='blue')

plt.tight_layout()
plt.show()

#example = 'ex9'
if example == 'ex9':
print(example)
# PIRLS ###
n = 500
x = np.random.uniform(-1, 1, n)

y = 10*x**3 - 10*x + np.random.normal(0, 1, n)
y -= y.mean()

# required only to initialize the gam. they have no influence on the result.
smoother = UnivariatePolynomialSmoother(x, degree=4)
smoother = UnivariateBSplines(x, degree=4, df=10)

gp = UnivariateGamPenalty(smoother, alpha=0)
gam = GLMGam(y, smoother.basis_, penal=gp)

for i, alpha in enumerate([0, .001, .01, .1]):
gam_res = gam._fit_pirls(y=y, spl_x=smoother.basis_, spl_s=smoother.cov_der2_, alpha=alpha)

y_est = np.dot(smoother.basis_, gam_res.params.T)

plt.subplot(2, 2, i+1)
plt.plot(x, y, '.')
plt.plot(x, y_est, '.')
plt.title('alpha=' + str(alpha))

plt.tight_layout()
plt.show()
Empty file.
40 changes: 40 additions & 0 deletions statsmodels/sandbox/gam_gsoc2015/cubic_splines_mgcv.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
library('mgcv')

set.seed(2) ## simulate some data...
dat <- gamSim(1,n=400,dist="normal",scale=2)
dat$x3 = NULL
dat$x1 = NULL
dat$f3 = NULL
dat$f1 = NULL
b <- gam(y~s(x0, bs = "cc")+s(x2, bs = "cc"), data=dat)
summary(b)

plot(b, pages=1)

y_est = predict(b, dat)
partial = predict(b, type = "terms")

res = cbind(dat, partial, y_est)

head(res)
#write.csv(x = res, file = 'Documenti/statsmodels/statsmodels/sandbox/gam_gsoc2015/tests/results/cubic_cyclic_splines_from_mgcv.csv')


### part 2 ###


n = 300
x = seq(-5, 5, length.out = n)
y = x*x*x - x*x + rnorm(n, 0, 10)


g_cc = gam(y~s(x, k = 30, bs = "cc" ))
g_cr = gam(y~s(x, k = 30, bs = "cr" ))
g_cs = gam(y~s(x, k=30, ))

y_est_cc = predict(g_cc)
y_est_cr = predict(g_cr)

plot(x, y)
lines(x, y_est_cc)
lines(x, y_est_cr)
Loading