Repository navigation
ENH: McFadden and Cox-Snell Pseudo R-square added to GLM. See statsmodels/statsmodels#5861 - #7367
anuragwatane wants to merge 4 commits into
Conversation
…n the result.summary()
| """ | ||
| Lnull = Decimal(exp(1))**Decimal(self.llnull) | ||
| Lf = Decimal(exp(1))**Decimal(self.llf) | ||
| return round( 1 - pow( (Lnull/Lf) , Decimal(2/self.nobs) ) , 5) |
There was a problem hiding this comment.
why do you use Decimal?
in general we are rounding only for printing, and not in code, i.e. user gets all digits
There was a problem hiding this comment.
isn't this 1 - np.exp((llnull - llf) * 2 / nobs) ?
There was a problem hiding this comment.
@josef-pkt, Thank you for the response.
I tried to explain why I used Decimal() with the code below.
import statsmodels.api as sm
data = sm.datasets.star98.load(as_pandas=False)
data.exog = sm.add_constant(data.exog, prepend=False)
glm_binom = sm.GLM(data.endog, data.exog, family=sm.families.Binomial())
res = glm_binom.fit()
from decimal import Decimal
from math import exp
print(f"Cox & Snell's Pseudo-R-square formula is referred from URL: https://statisticalhorizons.com/r2logistic")
"""
Lnull: value of the Likelihood function for a model with no predictors
Lf: value of the Likelihood for the model being estimated
nobs: The number of observations n
Cox & Snell's pseudo-R-squared. `1 - (Lnull / Lf)^(2/nobs)`
"""
print(f"\nLog-Likelihood for the model is a huge negative number: {res.llf}")
print(f"\nThe Likelihood for the model can be computed as exp(Log-Likelihood).")
print(f"\nThe exponential of Log-Likelihood is: {exp(res.llf)} zero.")
print(f"\nDividing by {exp(res.llf)} (Likelihood) will give ZeroDivisionError. To handle this error, Decimal() is used.")
print(f"\nAnother way to calculate Likelihood for the model is: {Decimal(exp(1))**Decimal(res.llf)}")
Lnull = Decimal(exp(1))**Decimal(res.llnull)
Lf = Decimal(exp(1))**Decimal(res.llf)
prsquared_cox_snell = round( 1 - pow( (Lnull/Lf) , Decimal(2/res.nobs) ) , 5)
print(f"\nCox & Snell's pseudo-R-squared: {prsquared_cox_snell}")
Please let me know if any changes are needed.
There was a problem hiding this comment.
but 1 - np.exp((llnull - llf)*(2/nobs)) will not under/overflow easily, and stays with our usual numpy pattern
There was a problem hiding this comment.
The following Cox & Snell Pseudo R-squared formula can be verified from the URL https://www.real-statistics.com/logistic-regression/significance-testing-logistic-regression-model/
1 - np.exp((llnull - llf)*(2/nobs))
And the following Cox & Snell Pseudo R-squared formula can be verified from the URL https://statisticalhorizons.com/r2logistic
Lnull: value of the Likelihood function for a model with no predictors
Lf: value of the Likelihood for the model being estimated
nobs: The number of observations n
1 - (Lnull / Lf)^(2/nobs)
There was a problem hiding this comment.
I used both formulas to compare the value of Cox & Snell Pseudo R-squared for five different datasets. And I found out that the two formulas give the same result for the respective dataset.
import statsmodels.api as sm
from math import exp
from decimal import Decimal
import numpy as np
# ------------------------
print(f"GLM: Binomial response data")
data = sm.datasets.star98.load(as_pandas=False)
data.exog = sm.add_constant(data.exog, prepend=False)
glm_binom = sm.GLM(data.endog, data.exog, family=sm.families.Binomial())
res = glm_binom.fit()
print(f"\nCox & Snell's Pseudo R-squared using formula 1:")
Lnull = Decimal(exp(1))**Decimal(res.llnull)
Lf = Decimal(exp(1))**Decimal(res.llf)
print( round( 1 - pow( (Lnull/Lf) , Decimal(2/res.nobs) ) , 5) )
print(f"\nCox & Snell's Pseudo R-squared using formula 2:")
print( 1 - np.exp((res.llnull - res.llf)*(2/res.nobs)) )
# ------------------------
print(f"\nGLM: Gamma for proportional count response")
data2 = sm.datasets.scotland.load()
data2.exog = sm.add_constant(data2.exog, prepend=False)
glm_gamma = sm.GLM(data2.endog, data2.exog, family=sm.families.Gamma(sm.families.links.log()))
glm_results = glm_gamma.fit()
print(f"\nCox & Snell's Pseudo R-squared using formula 1:")
Lnull = Decimal(exp(1))**Decimal(glm_results.llnull)
Lf = Decimal(exp(1))**Decimal(glm_results.llf)
print( round( 1 - pow( (Lnull/Lf) , Decimal(2/glm_results.nobs) ) , 5) )
print(f"\nCox & Snell's Pseudo R-squared using formula 2:")
print( 1 - np.exp((glm_results.llnull - glm_results.llf)*(2/glm_results.nobs)) )
# ------------------------
print(f"\nGLM: Gaussian distribution with a noncanonical link")
nobs2 = 100
x = np.arange(nobs2)
np.random.seed(54321)
X = np.column_stack((x,x**2))
X = sm.add_constant(X, prepend=False)
lny = np.exp(-(.03*x + .0001*x**2 - 1.0)) + .001 * np.random.rand(nobs2)
gauss_log = sm.GLM(lny, X, family=sm.families.Gaussian(sm.families.links.log()))
gauss_log_results = gauss_log.fit()
print(f"\nCox & Snell's Pseudo R-squared using formula 1:")
Lnull = Decimal(exp(1))**Decimal(gauss_log_results.llnull)
Lf = Decimal(exp(1))**Decimal(gauss_log_results.llf)
print( round( 1 - pow( (Lnull/Lf) , Decimal(2/gauss_log_results.nobs) ) , 5) )
print(f"\nCox & Snell's Pseudo R-squared using formula 2:")
print( 1 - np.exp((gauss_log_results.llnull - gauss_log_results.llf)*(2/gauss_log_results.nobs)) )
# ------------------------
print(f"\nTest Gaussian family with canonical identity link")
from statsmodels.datasets.longley import load
data = load(as_pandas=False)
data.exog = sm.add_constant(data.exog, prepend=False)
longley_res = sm.GLM(data.endog, data.exog, family=sm.families.Gaussian()).fit()
print(f"\nCox & Snell's Pseudo R-squared using formula 1:")
Lnull = Decimal(exp(1))**Decimal(longley_res.llnull)
Lf = Decimal(exp(1))**Decimal(longley_res.llf)
print( round( 1 - pow( (Lnull/Lf) , Decimal(2/longley_res.nobs) ) , 5) )
print(f"\nCox & Snell's Pseudo R-squared using formula 2:")
print( 1 - np.exp((longley_res.llnull - longley_res.llf)*(2/longley_res.nobs)) )
# ------------------------
print(f"\nCommittee Dataset")
from statsmodels.datasets.committee import load
from statsmodels.tools.sm_exceptions import DomainWarning
import warnings
data = load(as_pandas=False)
data.exog[:, 2] = np.log(data.exog[:, 2])
interaction = data.exog[:, 2] * data.exog[:, 1]
data.exog = np.column_stack((data.exog, interaction))
data.exog = sm.add_constant(data.exog, prepend=False)
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=DomainWarning)
fam = sm.families.NegativeBinomial()
committee_res = sm.GLM(data.endog, data.exog, family=fam).fit(scale='x2')
print(f"\nCox & Snell's Pseudo R-squared using formula 1:")
Lnull = Decimal(exp(1))**Decimal(committee_res.llnull)
Lf = Decimal(exp(1))**Decimal(committee_res.llf)
print( round( 1 - pow( (Lnull/Lf) , Decimal(2/committee_res.nobs) ) , 5) )
print(f"\nCox & Snell's Pseudo R-squared using formula 2:")
print( 1 - np.exp((committee_res.llnull - committee_res.llf)*(2/committee_res.nobs)) )
# ------------------------
There was a problem hiding this comment.
@josef-pkt, as per your suggestion the formula for the Cox & Snell's Pseudo R-squared is updated. Now the formula is as below.
1 - np.exp((llnull - llf)*(2/nobs))
Use of Decimal() is avoided in the code.
| decimal_prsquared = DECIMAL_2 | ||
| def test_prsquared(self): | ||
| if hasattr(self.res2, 'prsquared'): | ||
| assert_almost_equal(self.res1.prsquared, self.res2.prsquared, self.decimal_prsquared) |
There was a problem hiding this comment.
modern usage is to use assert_allclose, which allows better definition of tolerance
assert_almost_equal is in ancient code from before numpy had assert_allclose
There was a problem hiding this comment.
@josef-pkt , Thank you for the response.
The code is updated. Now using assert_allclose() instead of assert_almost_equal() for test cases.
|
Thank you |
|
bump for 0.13 I ran into problems with McFadden's rsquared. It looks like that only makes sense for discrete endog. |
|
@anuragwatane AFAIU now, after looking at it for Beta regression, McFadden rsquared should not be appropriate for continuous endog. I think we either need to stick to cox-snell as default or switch between McFadden and Cox-snell depending on whether the family is for discrete endog or not. |
|
decision for 0.13 which does not commit us to a default for attribute: add maybe switch to cox snell as default for GLM because it applies to both continuous and discrete endog. When we add it to |
|
rebased version merged in #7682 |
NumPy's guide.
The GLM does not have McFadden's Pseudo R-square in its result.summary().
The GLM have McFadden's Pseudo R-square in its result.summary2().
I have added two functions in the file statsmodels/genmod/generalized_linear_model.py
And two test cases are added in the file statsmodels/genmod/tests/test_glm.py
Below test cases are passed
After above code changes, GLM will have McFadden's Pseudo R-square in result.summary().
McFadden's Pseudo R-square in result.summary() is almost equal to McFadden's Pseudo R-square in result.summary()2.
Cox & Snell's Pseudo R-square can be obtained by result.prsquared_cox_snell.
Details
Notes:
needed for doc changes.
then show that it is fixed with the new code.
verify you changes are well formatted by running
flake8is installed. This command is also available on Windowsusing the Windows System for Linux once
flake8is installed in thelocal Linux environment. While passing this test is not required, it is good practice and it help
improve code quality in
statsmodels.