Repository navigation
Description
Hello
I'm trying to replicate a GAM model created in R using the mgcv package. I am new to GAMs, and started experimenting with statsmodels package only yesterday. I have some questions further down.
But first, some context.
I have tried, but still have questions if I'm matching everything correctly. For one s() and te() terms are used, as well as bs='cr' and bs='re': bs is the penalized smoothing basis, 'cr' means cubic regression spline, penalized by conventional integrated square second derivative cubic spline penalty and 're' means random effects, penalized by a ridge penalty.
Some terms did not have the number of splines defined, were computed them internally. Bu they are all related to the categorical variable which has 32 unique categories.
The train data looks somewhat like:
| Y | A | B | C | D |
|---|---|---|---|---|
| 1 | 5 | 0.2536 | 0 | “ABCD” |
| 0 | 32 | -1.1789 | 4.1298 | “EFGH” |
| 0 | 55 | 9.8792 | 0 | “IJKL” |
| 1 | 13 | -7.6432 | -0.8477 | “ABCD” |
So, the code in R looks somewhat like:
model <- bam(Y ~
s(A, k=5, bs='cr') +
s(D, bs='re') +
ti(A, D, bs='re') +
ti(B, D, bs='re') +
s(B, k=4, bs='cr') +
s(C, k=3, bs='cr'),
data=train_set
family=binomial(link="logit"),
method="REML",
na.action= na.omit,
control = gam.control(mgcv.tol = 1e-2,
maxit = 50,
irls.reg = 0,
trace = TRUE))
And these are the resulting coefficients:
| Intercept |
|---|
| s(A).1 |
| s(A).2 |
| s(A).3 |
| s(A).4 |
| s(D).1 |
| … |
| s(D).32 |
| ti(A, D).1 |
| … |
| ti(A, D).31 |
| ti(B, D).1 |
| … |
| ti(B, D).31 |
| s(B).1 |
| s(B).2 |
| s(B).3 |
| s(C).1 |
| s(C).2 |
So, 4 A coefficients, 32 D coefficients, 31 coefficients for the interaction of A and D, 31 coefficients for the interaction of B and D, 3 B coefficients and 2 C coefficients.
Now, my first draft using statsmodel looks like:
x_spline = train_set[['A', 'B', 'C']]
bs = BSplines(x_spline, df=[5, 4, 3], degree=[3, 3, 2])
alpha=np.array([0.1, 0.1, 0.1])
gam_bs = GLMGAM.from_formula('Y ~ C(D) + A:C(D) + B:C(D)',
data= train_set,
smoother=bs, alpha=alpha,
family=sm.families.Binomial())
res_bs = gam_bs.fit(tol=1e-2, maxiter=50)
print(res_bs.summary())
I followed this doc and got some hints for other things from issues here on github.
1. Regarding the parameters besides the formula, how can I set the method of smoothing parameter estimation to REML like in R? And how can I set irls.reg = 0 in statsmodel?
I set the family to sm.families.Binomial that by default also takes the logit link, to match the code in R. The same also for tol and maxiter.
2. Do my Bsplines make sense?
Since all s() terms, except s(D), have bs='cr', I decided to used BSplines for them. I think it makes sense since
B-spline basis is a commonly used spline basis that is based on a special parametrization of a cubic spline
3. Do I need to set the degree to 3 for the BSpline variables, to ensure they are a cubic spline? If not, what value should degree have for each variable?
4. If I run select_penweight() I will get the same alphas for my model variables as the ones mgcv does?
I set all alphas to 0.1, because I saw in the doc that after the model fit you ran either select_penweight() or select_penweight_kfold(), to discover the best alphas. I noticed, in the example, the returned values from select_penweight() matched the ones you defined in the alpha variable and I read in a notebook by @josef-pkt that the values specified there were values from the unit tests obtained by the mgcv package.
5. In my code we have s(D, bs='re'), does it make sense in statsmodel to match it by adding to the formula C(D)? Where can I find the documentation on this C(), and what other options are available? If it is penalized by random effects in the original code, bs='re' does it still make sense to define it here? If I define it in x_spline, how can I set the penalized smoothing basis to be random effects?
I created my model by using the from_formula() GLMGam class method, like in the example in the doc. I read the formula interface only supports the linear part. So I added my variable D, which is categorical, and I saw in some examples here on github the use of C() and I thought it made sense using it. Can you confirm?
6. I have two interactions, in the original code they were ti(A, D, bs='re') and ti(B, D, bs='re'). I matched in statsmodel by adding to the formula A:C(D) + B:C(D). Does it make sense?
I think it is not because I get one extra coefficient than I did in R for both interactions (other variables are matching in terms of number of coefficients).
See below for coefficients in statsmodel:
| Intercept |
|---|
| C(D).[T.1.0] |
| ... |
| C(D).[T.31.0] |
| A:C(D)[0.0] |
| ... |
| A:C(D)[0.31] |
| B:C(D)[0.0] |
| ... |
| B:C(D)[0.31] |
| A_s0 |
| A_s1 |
| A_s2 |
| A_s3 |
| B_s0 |
| B_s1 |
| B_s2 |
| C_s0 |
| C_s1 |
So, 4 A coefficients, 32 D coefficients, 32 coefficients for the interaction of A and D, 32 coefficients for the interaction of B and D, 3 B coefficients and 2 C coefficients.
So I must be doing something wrong to have an extra coefficient for both interactions.
7. How do I make predictions using the result statsmodel GAM model for new data?
I tried following the example in the issue #7830 and did (doing predict for the train_set just to test the functionality):
predictions= res_bs.predict(train_set, exog_smooth=train_set[['age', 'norm_gt', 'norm_incident_freq']]
Activity
josef-pkt commentedon Jan 21, 2022
Hi,
I try to go over this during the weekend. That's many questions and I'm not sure how much I remember of this, and I don't remember part of the mgcv formula notation.
Overall, we have the core GAM features matching mgcv, but there are several parts that mgcv has that statsmodels is missing.
josef-pkt commentedon Jan 24, 2022
Neither of the following is available in statsmodels:
We don't have any support for interaction terms or multivariate splines as needed for
tiAFAICS from the mgcv documentation "re" is just adding a Ridge penalty.
GAM currently only allows for spline penalties. Adding a ridge penalty would be possible in the generic penalization case but options for additional penalization terms are not included in GAM.
The standard case of a univariate continuous regressor is the case that's available.
It might be possible to replicate something like
ti(A, D, bs='re')by explicitly specifying a spline for each level (except reference level) of the categorical variable.However, mgcv might use the same penalization weight for all levels which will not be the case if separate splines are specified.
In your model
to 5:
C() only means that the variable should be treated as categorical, That's useful for integer values, but strings as in your
Dvariable is always treated as categorical. In this case specifyingC(D)is redundant and using justDshould produce the same design matrix.C(D) + A:C(D) + B:C(D)will not be penalizedonly the 'A', 'B', 'C' will be penalized B-splines
When patsy handle the interaction terms, then it doesn't take into account that we also have spline terms that are not in the formula.
I just realized I misunderstood "ti". Because it also uses "re" it doesn't create a spline, I guess it includes only the linear term and creates another Ridge penalty across levels of the categorical variable.
My guess is that in order to account for the 2 extra columns, it would be necessary to drop them from the design matrix.
eg. ('Y ~ A + B + C(D) + A:C(D) + B:C(D)' and then delete the columns for A and B, because those will be replaced by the spline basis functions.
to 4) I'm not sure I remember correctly,
AFAIR it's true for aic (and likely for gcv) criterion but likely not for k-fold cross-validation
to 7) did it work and look correct?
I don't remember the details.
So, AFAICS, the main thing missing in statsmodels are the additional Ridge penalties across categorical levels.
I'm not sure how we can support the formula adjustments for the extra interaction terms. It's difficult to override the formula handling by patsy.
(I guess we would have to internally add A+B + C to the formula and then drop columns, but predict has the same issue when creating the design matrix for new exog.
Alternative would be to make spline orthogonal to linear x additional to the constant and drop a column from the basis functions.
)
nathanln commentedon Jan 6, 2023
Hello, @josef-pkt, I'm digging around this question of adapting a mgcv GAM model (in R) into a statsmodels GAM model (in python). I'm wondering if an option similar to the 'by' option (in mgcv's splines) is available in statsmodels ? This option helps to specify a variable with factor levels, so that a cubic spline is modeled for each of these levels. I read that such an option wasn't implemented in 2019, but it might have been done since then.
Thanks in advance for your answer
josef-pkt commentedon Jan 7, 2023
no news on this, I have not worked on GAM extensions since then.
I don't remember what the problem with interacting spline basis function with dummy variables are.
(I thought I have some experimental code, but don't find any files for it on my (new) computer.
example case regression discontinuity #2460
)
one continuous-dummy interaction should be a good starting point (much easier than continuous-continuous interactions)
josef-pkt commentedon Oct 1, 2023
random idea:
interaction of 2 continuous variables
instead of interacting the spline basis functions, we can have a simplified model with additive spline of interacted exog
spline(x1) + spline(x2) + spline(x1*x2)
spline-dummy interaction is issue #5332