Skip to content

ENH: McFadden and Cox-Snell Pseudo R-square added to GLM. See statsmodels/statsmodels#5861 - #7367

Closed
anuragwatane wants to merge 4 commits into
statsmodels:mainfrom
anuragwatane:master
Closed

anuragwatane wants to merge 4 commits into
statsmodels:mainfrom
anuragwatane:master

Conversation

@anuragwatane

Copy link
Copy Markdown

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

  1. prsquared (McFadden's Pseudo R-square)
  2. prsquared_cox_snell (Cox & Snell's Pseudo R-square)

And two test cases are added in the file statsmodels/genmod/tests/test_glm.py

  1. test_prsquared
  2. test_prsquared_cox_snell

Below test cases are passed

  1. pytest statsmodels\genmod\tests\test_glm.py::TestGlmBinomial::test_prsquared
  2. pytest statsmodels\genmod\tests\test_glm.py::TestGlmBinomial::test_prsquared_cox_snell
  3. pytest statsmodels\genmod\tests\test_glm.py::TestGlmGamma::test_prsquared
  4. pytest statsmodels\genmod\tests\test_glm.py::TestGlmGamma::test_prsquared_cox_snell
  5. pytest statsmodels\genmod\tests\test_glm.py::TestGlmGaussian::test_prsquared
  6. pytest statsmodels\genmod\tests\test_glm.py::TestGlmGaussian::test_prsquared_cox_snell

After above code changes, GLM will have McFadden's Pseudo R-square in result.summary().

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()
print(res.summary())
print(f"McFadden's pseudo-R-squared: {res.prsquared}")
print(f"Cox & Snell's pseudo-R-squared: {res.prsquared_cox_snell}")
print(res.summary2())

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:

  • It is essential that you add a test when making code changes. Tests are not
    needed for doc changes.
  • When adding a new function, test values should usually be verified in another package (e.g., R/SAS/Stata).
  • When fixing a bug, you must add a test that would produce the bug in master and
    then show that it is fixed with the new code.
  • New code additions must be well formatted. Changes should pass flake8. If on Linux or OSX, you can
    verify you changes are well formatted by running
    git diff upstream/master -u -- "*.py" | flake8 --diff --isolated
    
    assuming flake8 is installed. This command is also available on Windows
    using the Windows System for Linux once flake8 is installed in the
    local Linux environment. While passing this test is not required, it is good practice and it help
    improve code quality in statsmodels.
  • Docstring additions must render correctly, including escapes and LaTeX.

"""
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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why do you use Decimal?

in general we are rounding only for printing, and not in code, i.e. user gets all digits

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

isn't this 1 - np.exp((llnull - llf) * 2 / nobs) ?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

but 1 - np.exp((llnull - llf)*(2/nobs)) will not under/overflow easily, and stays with our usual numpy pattern

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)) )
# ------------------------

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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.

Comment thread statsmodels/genmod/tests/test_glm.py Outdated
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)

@josef-pkt josef-pkt Mar 9, 2021 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@josef-pkt , Thank you for the response.
The code is updated. Now using assert_allclose() instead of assert_almost_equal() for test cases.

@josef-pkt

Copy link
Copy Markdown
Member

Thank you
looks good overall,
I added some inline comments, especially about use of Decimal

@josef-pkt

Copy link
Copy Markdown
Member

bump for 0.13

I ran into problems with McFadden's rsquared. It looks like that only makes sense for discrete endog.

@josef-pkt

Copy link
Copy Markdown
Member

@anuragwatane
From where did you get the reference numbers for the unit tests for McFadden prsquared for gamma and gaussian.

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.

@josef-pkt

josef-pkt commented Aug 26, 2021 •

Copy link
Copy Markdown
Member

decision for 0.13 which does not commit us to a default for attribute:

add pseudo_rsquared(self, kind="mcf") method (added as part of beta reg PR)
https://github.com/statsmodels/statsmodels/blob/main/statsmodels/base/model.py#L2423

maybe switch to cox snell as default for GLM because it applies to both continuous and discrete endog.

When we add it to summary(), we should add a definition indicator in the name, so we can switch between discrete and continuous
e.g. "prsquared (CS)" and "prsquared (McF)"

@josef-pkt

Copy link
Copy Markdown
Member

rebased version merged in #7682

@josef-pkt josef-pkt closed this Sep 7, 2021
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.

How to compute pseudo R^2 for GLM estimators

2 participants