Skip to content

WIP/ENH Gam 2744 rebased2 - #5296

Closed
josef-pkt wants to merge 39 commits into
statsmodels:masterfrom
josef-pkt:gam_2744_rebased2
Closed

josef-pkt wants to merge 39 commits into
statsmodels:masterfrom
josef-pkt:gam_2744_rebased2

Conversation

@josef-pkt

@josef-pkt josef-pkt commented Oct 3, 2018 •

Copy link
Copy Markdown
Member

rebased version of #4575 which was rebased version of #2744
The original GSOC PR with most of the development discussion is #2435

rebase conflict in compat.python:
This has now unneeded itertools.combinations import but I dropped the py 2.6 compat code.

@josef-pkt

josef-pkt commented Oct 3, 2018 •

Copy link
Copy Markdown
Member Author

I fixed two errors because of refactored GLM in master, but didn't check the details
I have 5 failures when running test_gam.py locally.
There are several failures in comparison of predicted y which are likely either refactoring in GLM or rebase problems.

test_smooth_basis.py passes locally with 2 Runtime warning (zero division and invalid value)

@josef-pkt

Copy link
Copy Markdown
Member Author

There is a problem for the unit tests because penalization weights, alphas, do not have a consistent scaling.
I fixed 2 of the failing unit tests by manually adjusting the alphas until the tests passed. But the match is still not very close, i.e. the tolerance in the current unit tests is pretty large.

I think just mechanically adjusting the test will not help because any refactoring in, for example, scale will most likely affect the penalization weights.
i.e. I had a similar problem in GLM-Gaussian versus TheilRidge

In this case the pirls might not even have a penweight that implies a constant relative penalization (weight between loglike and penalty) during the iterations..

@josef-pkt

Copy link
Copy Markdown
Member Author

Also, I guess, there is still the bug in the PenalizationMixin class that is fixed in master but not yet used by GAM.

@josef-pkt

Copy link
Copy Markdown
Member Author

there is a serious problem with cov_params in the unit test case second assert

for the case when alpha is small positive number
exog is rank deficient, but GLM has cov_params in a reasonable range
but GAM cov_params blow up
increasing alpha didn't help in getting GAM cov_params to a reasonable range.
i.e. some bug somewhere, or we use inv on the near singular matrix.
pirls uses WLS so implicitly it uses pinv
switching to 'bfgs' raises an exception in cov_params because normalized_cov_params is None

hessian in pirls estimate is singular

(Pdb)  np.linalg.matrix_rank(res_glm_gam.model.hessian(res_glm_gam.params))
19
(Pdb) res_glm_gam.params.shape
(20,)
..\eclipse_ws\statsmodels\statsmodels_py34_pr\statsmodels\gam\tests\test_gam.py
F
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> traceback >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    def test_cov_params():

        np.random.seed(0)
        n = 1000
        x = np.random.uniform(0, 1, (n, 2))
        x = x - x.mean()
        y = x[:, 0] * x[:, 0] + np.random.normal(0, .01, n)
        y -= y.mean()

        bsplines = BSplines(x, degree=[3] * 2, df=[10] * 2)
        alpha = 0
        glm_gam = GLMGam(y, bsplines, alpha=alpha)
        res_glm_gam = glm_gam.fit(method='pirls', max_start_irls=0,
                                  disp=0, maxiter=5000, maxfun=5000)
        glm = GLM(y, bsplines.basis_)
        res_glm = glm.fit()

        assert_allclose(res_glm.cov_params(), res_glm_gam.cov_params(), rtol=0.0
025) # test passed

        alpha = 1.e-14
        glm_gam = GLMGam(y, bsplines, alpha=alpha)
        res_glm_gam = glm_gam.fit(method='pirls', max_start_irls=0,
                                  disp=0, maxiter=5000, maxfun=5000)

>       assert_allclose(res_glm.cov_params(), res_glm_gam.cov_params(), rtol=0.0
025) # test not passed
E       AssertionError:
E       Not equal to tolerance rtol=0.0025, atol=0
E
E       (mismatch 100.0%)
E        x: array([[  5.592902e-06,  -4.114541e-06,   1.960534e-06,  -1.090418e-
06,
E                 3.312471e-07,  -4.222416e-07,  -1.145371e-08,  -3.445898e-07,
E                -4.833459e-08,  -3.836960e-07,  -1.582085e-07,   3.998780e-07,.
..
E        y: array([[  3.768192e+17,   3.768192e+17,   3.768192e+17,   3.768192e+
17,
E                 3.768192e+17,   3.768192e+17,   3.768192e+17,   3.768192e+17,
E                 3.768192e+17,   3.768192e+17,  -3.768192e+17,  -3.768192e+17,.
..

..\eclipse_ws\statsmodels\statsmodels_py34_pr\statsmodels\gam\tests\test_gam.py:
771: AssertionError

@josef-pkt

Copy link
Copy Markdown
Member Author

possible problem:
Based on the example, it looks like that the spline bases are perfectly collinear, i.e. the constant is not removed in each term.
To get non-singular hessian in the optimization, either

  • we reparameterize to non-singular exog, or
  • we add constraint, or
  • we add an additional sum to 0 penalty, I guess x.mean(0) dot params = 0

Wood mentions the reparameterization in his GAM in R, 1st ed. book
Note, if we rotate/transform exog, then we also need to transform the penalization 'cov' matrix.

This means most likely I have to go through all the pieces instead of starting at the end.

@josef-pkt

josef-pkt commented Oct 4, 2018 •

Copy link
Copy Markdown
Member Author

using pinv(hessian) with strong penalization

(Pdb) np.sqrt(np.diag(np.linalg.pinv(-res_glm_gam.model.hessian(res_glm_gam.params))))
array([ 0.05635434,  0.05153926,  0.04203311,  0.02844394,  0.01757379,
        0.01774965,  0.02865356,  0.0418576 ,  0.05129011,  0.05581714,
        0.05593723,  0.05147028,  0.04174147,  0.02856064,  0.01781797,
        0.01744225,  0.0285127 ,  0.04212617,  0.05118957,  0.05534723])
(Pdb) res_glm.bse
array([ 0.00236493,  0.00288267,  0.00256957,  0.00197272,  0.00193059,
        0.00191334,  0.00202478,  0.00266   ,  0.00279489,  0.00250968,
        0.00276395,  0.00274005,  0.00266238,  0.00205356,  0.00184837,
        0.00198964,  0.00210117,  0.0024235 ,  0.00249568,  0.00260051])

(Pdb) res_glm.params
array([ 0.14367595,  0.10623541,  0.02048091, -0.06133778, -0.10923083,
       -0.10687274, -0.06227415,  0.01754518,  0.09392257,  0.14283772,
        0.0149526 ,  0.02316668,  0.01797777,  0.01777724,  0.01880239,
        0.01961575,  0.01652899,  0.02119478,  0.01415709,  0.02080898])
(Pdb) res_glm_gam.params
array([-0.00018784, -0.00029566, -0.00051204, -0.00083937, -0.00118041,
       -0.00151492, -0.00185044, -0.00216469, -0.00237673, -0.00247686,
        0.00685035,  0.00637176,  0.00531203,  0.00379199,  0.00219773,
        0.00060314, -0.0010723 , -0.00264074, -0.0036277 , -0.00407349])

with alpha=1e-10

(Pdb) np.sqrt(np.diag(np.linalg.pinv(-res_glm_gam.model.hessian(res_glm_gam.para
ms))))
array([ 0.24359173,  0.29690022,  0.26467213,  0.20320752,  0.19887366,
        0.19709629,  0.20856746,  0.27397888,  0.28784096,  0.25848585,
        0.28468582,  0.28220983,  0.27423118,  0.21153518,  0.19040432,
        0.20495675,  0.21643839,  0.24962409,  0.25702924,  0.26784204])
(Pdb) res_glm.bse
array([ 0.00236493,  0.00288267,  0.00256957,  0.00197272,  0.00193059,
        0.00191334,  0.00202478,  0.00266   ,  0.00279489,  0.00250968,
        0.00276395,  0.00274005,  0.00266238,  0.00205356,  0.00184837,
        0.00198964,  0.00210117,  0.0024235 ,  0.00249568,  0.00260051])

(Pdb) res_glm_gam.params
array([ 19.53442427,  19.49698323,  19.41122943,  19.32941018,
        19.28151758,  19.28387512,  19.32847462,  19.40829226,
        19.48467235,  19.53358461, -19.37579477, -19.36758246,
       -19.37276961, -19.37297137, -19.3719455 , -19.37113276,
       -19.3742188 , -19.36955419, -19.37659005, -19.36994016])
(Pdb) res_glm.params
array([ 0.14367595,  0.10623541,  0.02048091, -0.06133778, -0.10923083,
       -0.10687274, -0.06227415,  0.01754518,  0.09392257,  0.14283772,
        0.0149526 ,  0.02316668,  0.01797777,  0.01777724,  0.01880239,
        0.01961575,  0.01652899,  0.02119478,  0.01415709,  0.02080898])

the example has two components, two spline bases, but no constant

(Pdb) res_glm_gam.model.penal.k_variables
2
(Pdb) res_glm_gam.model.penal.mask
[array([ True,  True,  True,  True,  True,  True,  True,  True,  True,
        True, False, False, False, False, False, False, False, False,
       False, False], dtype=bool), array([False, False, False, False, False, Fal
se, False, False, False,
       False,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True], dtype=bool)]
(Pdb) res_glm_gam.model.penal.gp
[<statsmodels.gam.gam_penalties.UnivariateGamPenalty object at 0x000000000804FD3
0>, <statsmodels.gam.gam_penalties.UnivariateGamPenalty object at 0x000000000804
FC18>]

@josef-pkt

Copy link
Copy Markdown
Member Author

another case alpha=1e-5
fittedvalues are pretty close
but alpha should be close to zero to correspond to unpenalized GAM

(Pdb) np.sqrt(np.diag(np.linalg.pinv(-res_glm_gam.model.hessian(res_glm_gam.para
ms))))
array([ 0.13065677,  0.09122432,  0.11928826,  0.11296147,  0.11989609,
        0.11791286,  0.11344218,  0.12367532,  0.08677403,  0.12597571,
        0.1372523 ,  0.09373057,  0.12153429,  0.11628968,  0.11334781,
        0.12443002,  0.12244501,  0.1150598 ,  0.08788016,  0.12754651])
(Pdb) res_glm_gam.params
array([ 0.22880005,  0.19028928,  0.11114828,  0.02500467, -0.02178573,
       -0.02009094,  0.02541654,  0.10489379,  0.18502954,  0.22220762,
       -0.06816447, -0.06758605, -0.06714927, -0.06971488, -0.06807581,
       -0.06847574, -0.06928154, -0.06873977, -0.06940489, -0.06934706])
(Pdb) res_glm.params
array([ 0.14367595,  0.10623541,  0.02048091, -0.06133778, -0.10923083,
       -0.10687274, -0.06227415,  0.01754518,  0.09392257,  0.14283772,
        0.0149526 ,  0.02316668,  0.01797777,  0.01777724,  0.01880239,
        0.01961575,  0.01652899,  0.02119478,  0.01415709,  0.02080898])

(Pdb) res_glm_gam.fittedvalues[:10]
array([-0.08548938, -0.07666746, -0.08108629, -0.08340189,  0.12300104,
       -0.00257329, -0.08338463,  0.10342097,  0.1436862 , -0.01078753])
(Pdb) res_glm.fittedvalues[:10]
array([-0.08565823, -0.07622082, -0.08118223, -0.08350208,  0.123875  ,
       -0.00267846, -0.08434432,  0.10574724,  0.14678139, -0.01071152])

(Pdb) np.max(np.abs(res_glm_gam.fittedvalues - res_glm.fittedvalues))
0.0076743280485976062
(Pdb) np.max(np.abs(res_glm_gam.fittedvalues / res_glm.fittedvalues -1))
49.927406145412192
(Pdb) np.max(np.abs((1 + res_glm_gam.fittedvalues) / (1+res_glm.fittedvalues) -1
))
0.0066204574231449875
(Pdb) res_glm_gam.bse
array([ 32528.56409614,  32528.56409614,  32528.56409614,  32528.56409614,
        32528.56409614,  32528.56409614,  32528.56409614,  32528.56409614,
        32528.56409614,  32528.56409614,  32528.56409614,  32528.56409614,
        32528.56409614,  32528.56409614,  32528.56409614,  32528.56409614,
        32528.56409614,  32528.56409614,  32528.56409614,  32528.56409614])

@josef-pkt

Copy link
Copy Markdown
Member Author

Ok, my guess is that this is the normalization problem with multiple splines in GAM.

Checking one example in the notebook with only a single component which has full rank shows reasonable bse.
notebook updated from 2015 version is here https://gist.github.com/josef-pkt/5e164ab0b25a21f317fa5d540d850243

@josef-pkt

josef-pkt commented Oct 4, 2018 •

Copy link
Copy Markdown
Member Author

looks like cov_type has no effect
gam_res_cs_hc = gam_cs.fit(cov_type='hc0')
produces the same bse as unspecified and is the same as
gam_cs.fit(cov_type='nonrobust').bse

However, fit properly transmits the cov_type to super and to results class.

plotting get_prediction conf_int looks reasonable, the look maybe a bit wide with 95% coverage prob.

update
fit calls _fit_pirls but does not transmit extra arguments/keywords
after adding cov_type there, the cov_type changes bse

also, after restarting my notebook kernel the confidence intervals for predicted mean look very narrow (instead of wide as before)

@josef-pkt

Copy link
Copy Markdown
Member Author

effective degrees of freedom are missing, AFAICS
df_resid is inherited,
inherited aic, bic are monotonic in alpha (pen_weights), and AFAICS don't use effective degrees of freedom.
#4257 (comment)
and unresolved in merged #4576

related from GLMResults inherited get_influence works but it's not clear whether those definitions handle penalized MLE.

@josef-pkt

Copy link
Copy Markdown
Member Author

fit_constrained does not work, does not correctly recreate model
alpha is missing in __init__, and when I add it I get
AttributeError: 'numpy.ndarray' object has no attribute 'smoothers_'
in line if len(multivariate_smoother.smoothers_) != len(alpha)

constraints = np.ones(gam_cs_h.exog.shape[1])
#gam_cs_h._init_keys.extend(['alpha'])    # do not use in repeated calls
gam_cs_h._init_keys =['var_weights', 'offset', 'freq_weights', 'exposure', 'family', 'penal', 'pen_weight', 'alpha']
res_constr = gam_cs_h.fit_constrained(constraints)
print(res_constr.summary())

@josef-pkt

Copy link
Copy Markdown
Member Author

possibly a problem with args in __init__ when we only have kwds in _init_kwds
__init__(self, endog, smoother, alpha,
but that doesn't fix it.
GLMGAM does not have exog in the second position, which I think is generally assumed in recreating a model. and exog is not in _init_kwd and is always added automatically

How are partial linear model currently handled? Do we have a unpenalized dummy class for a linear component?

@josef-pkt

Copy link
Copy Markdown
Member Author

refactor GLMGAM.__init__ to follow more the standard pattern and make linear component easier to use, possibly like the following

  • add exog=None as second argument
  • except for endog use only keywords.
  • interpret exog if not None as a linear component and add whatever internal representation we need
  • internally we need to distinguish exog provide by user, from combined exog that includes the spline bases. (IIRC I have a general issue for exog_extra that are generated exog without going through formula and patsy)

check signature in R mgcv

@josef-pkt

Copy link
Copy Markdown
Member Author

However, using fit_constrained directly does not help yet to impose the normalization constraints on the spline bases, we still need to transform the penalization matrices.

@josef-pkt

Copy link
Copy Markdown
Member Author

Adding exog=None as second argument kind of works, it handles now init_kwds correctly.
However, there is a fundamental problem with recreating the model with a different exog because the spline basis are not part of the exog init argument, but created afterwards.
Essentially transformation of all exog would have to happen after the spline bases have been added, i.e. internal to the model after the initialization of the spline bases.
e.g. (just an idea) regression models and other models have an initialize and/or whiten methods to process the provided exog and endog.
This is getting most likely tricky because attributes like df_model and df_resid need to be set also, after exog transformation in the case of fit_constrained or fit_zeros.

My guess this rules out for now that we use fit_constrained to recreate a model that has non-singular design matrix through spline basis rotation/transformation.

patsy's splines have a "remove constant" option. I don't know how that works and figuring out the transformed penalization matrices might not be trivial.

Adding an additional penalization towards zero mean to impose the constraint might be easier, and would lead us to more composable penalization structures.
(Aside, I also had problems, ie. didn't fully manage to figure out the zero mean normalization in the backfitting algorithm inherited from stats.models times which was buggy and I was pretty "clueless".)

@josef-pkt

Copy link
Copy Markdown
Member Author

basic class structure:

  • PenalizedMixin Models; full exog is given and user provided, penalization instance is given separately also provided by user
  • GLMGAM: user specifies spline basis and alpha, exog and penalization structure is created in __init__.
    Then calls super PenalizedMixin with the given exog and penal instance.

one possibility would be to outsource those extra parts to a dispatch function or method, so GLMGAM has a similar signature as PenalizedMixin and other Models, i.e. similar to from_formula.

@josef-pkt

Copy link
Copy Markdown
Member Author

many unit tests are missing random seeds

@josef-pkt

Copy link
Copy Markdown
Member Author

I don't have an overview for the implementation yet, and I don't remember enough about GAM
3 main parts:

  • construct splines and corresponding penalization matrix
  • estimate the model with penalized MLE
  • choose smoothing parameters, penalization weights and more basically which function basis and how many knots

Penalization is quadratic in params, b S b or b R' R b
part one should provide exog (spline basis) and R or S
part two should be standard penalized MLE with L2 penalty

I think I try to separate these two parts and use PenalizedMixin directly, as in my merged penalized PR.
S is block diagonal with multiple components, but the current implementation uses sum over components in the penalization class.
Having R directly makes it easier to add extra constraints or penalties, e.g. for the normalization, and PenalizedMixin already allows for unpenalized linear exog.

Note we need R or S embedded for the full params, i.e. pad with zeros.

If we have exog and R or S, then we can also use TheilRidge for the linear case.

We need something like design_infor to keep the information about how the component was constructed, which we need for some post-estimation results.

class hierarchy for Models with penalized splines?
GAMMLE: the general version for any type of mle models, big unknown is effective degrees of freedom
(this would actually work for any M-Estimator)
GAMGLM special case for GLM
GAMLogit, ... special cases for discrete classes
GAMGLS additive model with TheilRidge or PenalizedMixin backend

Wood in mgcv often uses QR decomposition in the R tradition, I would prefer to stay more general at the beginning at the cost of not using model specific speedups (e.g. avoid recomputing some parts during cross validation)

@josef-pkt

josef-pkt commented Oct 5, 2018 •

Copy link
Copy Markdown
Member Author

Notes: UnivariateGamPenalty

1) params are the coefficients in the regression model
2) der2  is the second derivative of the splines basis
3) cov_der2 is obtained as np.dot(der2.T, der2)

R is der2_basis_, I guess n_samples is nobs
S = R' R

f = R dot params
func = alpha * np.sum(f ** 2) / self.n_samples #JP same as alpha b' R' R b / n

grad/deriv:
deriv = 2 * alpha * S dot params / self.n_samples

deriv2 = 2 * alpha * S / self.n_samples

MultivariateGamPenalty is the sum over components using mask to extract the subset of params
TODO: to embed in larger exog we need and option to change mask, eg. k_linear or k_other as starting index, e.g assuming splines are the last columns of exog.

In this representation it would not be difficult to augment the R matrix by a concatenating mean of spline basis as additional restriction/penalization term.

@josef-pkt

josef-pkt commented Nov 3, 2018 •

Copy link
Copy Markdown
Member Author

close to the last missing piece:

mgcv doc for gam function mentions that deviance is used for gcv
in the gaussian case, pearson chi2 and deviance are the same and the following matches mgcv for gcv

self.nobs * self.deviance / (self.nobs - self.hat_matrix_trace)**2
10.257426815719956
self.nobs * (res1a.resid_deviance**2).sum() / (self.nobs - self.hat_matrix_trace)**2
10.257426815719963

self.nobs * (res1a.resid_pearson**2).sum() / (self.nobs - self.hat_matrix_trace)**2
10.257426815719963

AFAICS right now the definition doesn't look like it matches up with TheilGLS gcv, but I don't have the TheilGLS example right now to compare.

Wiring up edf based df_resid and it's use in scale is going to be a bit messy. scale in GLM is estimated in the model and df_resid is defined in the model class, in GLM.estimate_scale
edf and df_resid now depend on the estimation result similar to hat_matrix which is evaluated at the estimated params and not a exog/data property as in OLS.

i.e. we need the sequence

  • estimate params
  • compute hat_matrix_diag and edf
  • update df_resid
  • then estimate scale with edf corrected df_resid
  • then compute the remaining Results

If scale is estimated during fit, then we would need edf estimate also in fit.
If we use MLE scale estimate, then divisor is nobs and does not depend on edf.
In models based on LEF, then we don't really need scale in fit, and could move it's computation to the Results class.

messy: circular computation: edf computation currently uses scale but we need edf to compute scale.

@josef-pkt

josef-pkt commented Nov 4, 2018 •

Copy link
Copy Markdown
Member Author

BUG : fit_pirls hardcodes self.scaletype = 'dev'
we have an option and don't want to match R mgcv.

(I made a change and added GAMResults.__init__ to change df_resid and scale but now pirls scale is wrong. I don't see yet where this is changed to something wrong.
scale handling is still very messy and difficult in GLM.)

@josef-pkt

Copy link
Copy Markdown
Member Author

bug-wrong in GLM: scale-type='dev' has wrong computation
looks like the same as #4032 (comment)

But I thought bse after pirls was correct before, and has some unit tests.

Oh that's funny.
This was correct where estimate_scale is used in fit_pirls before creating the results instance, because we set self.scale=1 during optimization.
But if self.scale is not 1., then the bug produces wrong results, however that wasn't used before my uncommitted change or before refactoring in 4032.

my current solution for edf/df_resid is very hackish, but agrees with mgcv now
e.g. we can drop the edf correction factor in the unit tests

self = <statsmodels.gam.tests.test_penalized.TestGAM5Pirls object at 0x000000000
9944A20>

    def test_params(self):
        res1 = self.res1
        res2 = self.res2
        assert_allclose(res1.params, res2.params, rtol=1e-5)
        assert_allclose(np.asarray(res1.cov_params()),
>                       res2.Vp * self.covp_corrfact, rtol=1e-4)
E       AssertionError:
E       Not equal to tolerance rtol=0.0001, atol=0
E
E       (mismatch 100.0%)
E        x: array([[ 82.343472,  -0.200149,   5.724406,  -8.162391,  17.89058 ],

E              [ -0.200149,  62.755146,  13.618453,   3.343678,  18.668982],
E              [  5.724406,  13.618453,  65.734335,   1.647165,  13.483566],...
E        y: array([[ 82.553155,  -0.200658,   5.738983,  -8.183176,  17.936137],

E              [ -0.200658,  62.914948,  13.653132,   3.352192,  18.716521],
E              [  5.738983,  13.653132,  65.901724,   1.65136 ,  13.517901],...

M:\josef_new\eclipse_ws\statsmodels\statsmodels_py34_pr\statsmodels\gam\tests\te
st_penalized.py:83: AssertionError
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> entering PDB >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
> m:\josef_new\eclipse_ws\statsmodels\statsmodels_py34_pr\statsmodels\gam\tests\
test_penalized.py(83)test_params()
-> res2.Vp * self.covp_corrfact, rtol=1e-4)
(Pdb) self.covp_corrfact
1.0025464444310588
(Pdb) np.max(np.abs(np.asarray(res1.cov_params()) - res2.Vp))
1.8474111129762605e-13
(Pdb) np.max(np.abs(np.asarray(res1.cov_params()) / res2.Vp - 1))
6.5725203057809267e-14

@josef-pkt

josef-pkt commented Nov 4, 2018 •

Copy link
Copy Markdown
Member Author

"bug" unclear definition in mgcv results

Approximate significance of smooth terms:
                    edf Ref.df        F    p-value    
s(weight) 3.79617909756      5  4.34737 0.00010033 ***
s(hp)     3.53440388287      4 18.97606 2.1664e-15 ***

AFAICS: The F value is based on integer df and not on edf.
I'm not able to see what mgcv is doing here.
The reported number don't match up

stats.f.sf(4.34737, 3.79617909756, 191.66941701956722)
0.0026197343093279824

I have now, my current test_significance uses edf for computing F and for computing pvalue

print(res1b.test_significance(0))

<F test: F=array([[ 5.72597489]]), p=0.00029682536616616696, df_denom=191.66900000000001, df_num=3.7959999999999998>

print(res1b.test_significance(1))
<F test: F=array([[ 21.47582241]]), p=1.824993101612044e-13, df_denom=191.66900000000001, df_num=3.5339999999999998>

The F statistic is the same as in wald_test_terms that does not take df_constraints based on edf into account.

res1b.wald_test_terms(skip_single=True, combine_terms=['fuel', 'drive', 'weight', 'hp'])
<class 'statsmodels.stats.contrast.WaldTestResults'>
                F                     P>F  df constraint    df denom
fuel    40.116253  1.6643831719068437e-09              1  191.669417
drive    5.445138    0.005011263539596161              2  191.669417
weight   4.347365   0.0009032857757659304              5  191.669417
hp      18.976058  3.6685394395119477e-13              4  191.669417

@josef-pkt

josef-pkt commented Nov 4, 2018 •

Copy link
Copy Markdown
Member Author

travis test run doesn't work because of pytest version mismatch

$ pytest -r a ${COVERAGE_OPTS} statsmodels --skip-examples
ERROR: /home/travis/build/statsmodels/statsmodels/setup.cfg:5: requires pytest-3.6, actual pytest-3.10.0'

same error on appveyor

@josef-pkt

Copy link
Copy Markdown
Member Author

new release of pytest https://pypi.org/project/pytest/#history
and everything stops working

I guess "somebody" thinks pytest-3.10.0 < pytest-3.6

@josef-pkt

Copy link
Copy Markdown
Member Author

I commented out the minversion requiremet to see whether the tests even run with pytest 3.10

@josef-pkt

josef-pkt commented Nov 4, 2018 •

Copy link
Copy Markdown
Member Author

AIC: another unclear reverse engineering

mgcv adds 1 to the number of params (edf) in aic

self.aic, -2 * self.llf + 2 * (self.edf.sum() + 1), aic_mgcv
(1048.0164643902958, 1050.0164643902958, 1050.016464)

slightly messy in GLM, constant is assumed in counting df_model, we don't check (in contrast to regression model) whether a constant really is in exog
df_model = k_params - 1
aic uses df_model adds the 1 back in
​
see also comment above #5296 (comment)
referring to Wood's book and "corrected AIC", but I don't think that will add just a 1 to generic aic

@josef-pkt

josef-pkt commented Nov 4, 2018 •

Copy link
Copy Markdown
Member Author

removing pytest minversion requirement seems to work

changing the constrast wald_test summary causes a test failure with string comparison

>       assert_equal(wt2.summary()[-30:], wt1.summary()[-30:])
E       AssertionError: 
E       Items are not equal:
E        ACTUAL: '73, df_denom=287, df_num=15.0>'
E        DESIRED: '-273, df_denom=287, df_num=15>'
statsmodels/genmod/tests/test_constrained.py:245: AssertionError

we don't want a decimal if the df_num is integer valued

This test didn't fail on python 2.7 appveyor, so most likely string formatting (for integer valued float) has changed between python 2 and 3.

@josef-pkt

Copy link
Copy Markdown
Member Author

and the last stage: finding alpha

a quick experiment with just using fmin i.e. nelder-mead as optimizer, which is pretty fast and works pretty well in this example
(800 ms and 200 function evaluations sounds pretty good given that there was not much focus on speed, and fmin does not use gradient information.)

The alphas corresponding to mgcv (in our parameterization) based on mgcv default, I think it;s min gcv
[ 1.09169444e+07, 3.23019240e+03]
GCV = 10.257 in mgcv

fun = lambda p: gam_cc._fit_pirls(alpha=[np.exp(p[0]), np.exp(p[1])]).aic
x = fmin(fun, np.array([1, 1]))
Optimization terminated successfully.
         Current function value: 1048.013593
         Iterations: 108
         Function evaluations: 211

x, np.exp(x)
(array([ 16.15488818,   8.03176801]),
 array([  1.03747775e+07,   3.07717733e+03]))

fun = lambda p: gam_cc._fit_pirls(alpha=[np.exp(p[0]), np.exp(p[1])]).gcv
x = fmin(fun, np.array([1, 1]))
Optimization terminated successfully.
         Current function value: 10.852687
         Iterations: 102
         Function evaluations: 194

x, np.exp(x)
(array([ 16.57736778,   8.42997913]),
 array([  1.58292141e+07,   4.58240445e+03]))

@jbrockmendel

Copy link
Copy Markdown
Contributor

Does #5370 replace this or supplement it?

@josef-pkt

josef-pkt commented Dec 8, 2018 •

Copy link
Copy Markdown
Member Author

#5370 is a continuation and replacement of this.
This PR is superseded by it, but I didn't want to push the rebase to this PR, because I want to keep an unchanged record of the development including comments in this PR.
There are many moving parts and I might need to refer back to this PR to figure out or understand some details in either our implementation, the comparison to mgcv, or the underlying theoretical structure.

The same applies to the PRs that have the earlier stages of development of GAM.

@jbrockmendel

Copy link
Copy Markdown
Contributor

Thanks for clarifying.

If keeping these around make things easier for you then more power to you. But if encouraging contributors to review PRs is a consideration, pruning (or at least clearly identifying) non-actionable ones would be helpful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants