Data Modeler
Data Modeler

Reputation: 57

How to run a GLM gamma regression in Python with R like formulas

I am running a GLM regression in Python using statsmodels using the following code. I specifically want to implement a log link function. I am able to write R like formulas using Statsmodels.

The following code successfully runs but throws up a Deprecation Warning. Can anyone suggest how to get rid of this warning. Thanks for the help.

Code:

mod = smf.glm(formula='y ~  C(x1) + C(x2) + C(x3) + x4 + x5', data=data,family=sm.families.Gamma(link=sm.families.links.log))
reg = mod.fit()
print(reg.summary())

Warning: DeprecationWarning: Calling Family(..) with a link class as argument is deprecated. Use an instance of a link class instead.

Upvotes: 4

Views: 5956

Answers (3)

Jinhua Wang
Jinhua Wang

Reputation: 1759

I don't think any of the above answers are correct. The correct method, as instructed by the warning, is to use the corresponding instance of the link function inside the bracket:

mod = smf.glm(formula='y ~  C(x1) + C(x2) + C(x3) + x4 + x5', data=data,family=sm.families.Gamma(link=sm.families.links.log()))
reg = mod.fit()
print(reg.summary())

Upvotes: 3

Chavo del 8
Chavo del 8

Reputation: 1

here is the solution:

sm.families.family.Gamma.links
link_g = sm.genmod.families.links.log
link_g

fit = sm.GLM.from_formula(formula, data=df, family=sm.families.Gamma(link_g())).fit()

Upvotes: 0

Carli
Carli

Reputation: 28

I'm working on the same problem. I noticed that if I removed everything inside the (), the results are exactly the same without the error. The model summary has the same values and the AIC value is identical.

Code with warnings:

glm_poisson_log = sm.GLM(endog, exog, family = sm.families.Poisson(sm.families.links.log))
results = glm_poisson_log.fit()

Code without warnings:

glm_poisson_log = sm.GLM(endog, exog, family = sm.families.Poisson **()**)
results = glm_poisson_log.fit()

Try removing the links information.

This site was also particularly helpful: https://www.statsmodels.org/stable/glm.html

Upvotes: 0

Related Questions