Skip to content

Request: BinomialModel #2192

Closed
Closed

Description

@kousu

A Logit model is usually used on boolean data, but it is actually more general than that. #2040 loosened the type restrictions in light of working scientists' need for them. Also, a boolean logit model is a special case of a binomial logit model.

My generalized linear model is Counts ~ Bin(n, XB) (subtlety: in our dataset, n is a vector, since each sample potential had a different number of cases)

Intuitively, I want to be able to say something like

fit = sm.Logit(Counts, sm.add_constant(_c[X1, X2]), N=n).fit()

But there's no N parameter and if I leave it out anyway I run up against the [0,1]-restriction nag that #2040 tweaked.

fit = sm.Logit(Counts/n, sm.add_constant(_c[X1, X2])).fit()

The fit runs, but gives me skewed results: the predictions are reasonable but not equivalent to the results from R and not equivalent to the results from first rewriting the binomials as a large number of bernoullis and then running Logit as before.

Instead, what you have to do to do binomial regression is a snippet of code that you need to reverse engineer out of the tests

fit = sm.GLM(_c[Counts, n-Counts], _c[X1, X2], family=statsmodels.families.Binomial()).fit()

I faithfully request that this be made cleaner and clearer. It would be nice if there was an explicit BinomialModel class that understands the data in basic counts-and-categories form. LogitModel could be renamed BernoilliModel, made to inherit from BinomialModel, and then aliased for backwards compatibility/readability. It's user-facing side could be sm.Binomial().

To be fair, you can't do this very clearly in R either. The closest you can get in R is one of

fit <- glm(cbind(Counts, N-Counts) ~ X1 + X2, family=binomial)
fit <- glm(Counts/N ~ X1 + X2, weights=N, family=binomial)

Both of these are awkward!

What is the rational behind the two column response? I can't find an explanation for how I'm supposed to read this, either in the statsmodel docs nor in R's. If my prof hadn't pointed it out I would have no idea about this "feature".

For the second, it's a mathematical accident that "weights" in IRLS used on this weird scaled-binomial model is the same as "N" and the division is just awkawrd.

statsmodels here has a chance to set the tone of notation that will be used in the far future.

Activity

  1. josef-pkt commented on Jan 19, 2015

    @josef-pkt
    Member

    If I understand correctly, what you want for the binomial model is implemented in GLM, where y/endog can be a two column array with (number successes, number failures) the sum of which is the total number of trials. see docstring of GLM and there should be an example somewhere.

  2. jseabold commented on Jan 19, 2015

    @jseabold
    Member

    See also #203. I waffled on this long ago, and @jonathan-taylor also suggested that the time that we not follow R here.

    A PR implementing the changes you suggest for the MLE models would be welcome.

  3. kousu commented on Jan 21, 2015

    @kousu
    Author

    You're right Josef. I didn't check the GLM docstring. I still wish this was more obvious, and when I am done this assignment I'll take a look at some edits :)

  4. kousu commented on Jan 21, 2015

    @kousu
    Author

    Note to self: statsmodels.genmod.families.family.Binomial.__init__() has a commented out "n" parameter which is almost exactly what I was looking for, and I'll take it if I can get it to work.

        def __init__(self, link=L.logit):  # , n=1.):
            # TODO: it *should* work for a constant n>1 actually, if data_weights
            # is equal to n
            self.n = 1
            # overwritten by initialize if needed but always used to initialize
            # variance since endog is assumed/forced to be (0,1)
            self.variance = V.Binomial(n=self.n)
            self.link = link()
    

    For some reason, poking the internal .n with a squishy stick gives the wrong results--the same as if it was ignoring .n entirely. Both of these fits give the same numbers:

    D = pandas.read_csv("counts.csv")
    N = array(D.yes) + array(D.no)
    
    Model = sm.families.Binomial() #TODO: tweak class families.Binomial so the next line can be merged in here.
    Model.n = N
    fit = sm.GLM(D.yes / Model.n, sm.add_constant(D.x), family=Model).fit()
    print(fit.summary())
    
    fit2 = sm.Logit(D.yes / N, sm.add_constant(D.x)).fit()
    print(fit2.summary())
    

    counts.csv:

    x,yes,no
    5, 11, 9
    6, 12, 21
    7, 30, 35
    8, 48, 35
    9, 27, 14
    10, 16, 10
    
  5. jseabold commented on Jan 21, 2015

    @jseabold
    Member

    IIRC this is the issue I posted above. PRs to re-enable this are welcome.
    Otherwise, I can maybe take a look before next release.

  6. josef-pkt commented on Jan 21, 2015

    @josef-pkt
    Member

    just FYI: No quick refactoring before a release in any core code and it's API (with the exception of new functionality, bugfixes and internal enhancements).

    statsmodels is too much in use now for quick changes in existing core code.

    Binomial is already an outlier that causes headaches, and doesn't have enough test coverage for the "meta-model" things (e.g. Stata's prefix)

    an 0.8 proposal and PR will give us time to handle the fallout.

  7. kousu commented on Feb 3, 2015

    @kousu
    Author

    Note to self and anyone else scratching their heads:
    this works:

    print(sm.GLM.from_formula("yes + no ~ x", D, family=sm.families.Binomial()).fit().summary())
    

    This isn't documented and I'm not sure it's an /intended/ to work like this, but it does, and you'll realize why once you read a) patsy's docs b) Binomial()'s code, c) from_formula()'s docs. Whatever work I end up doing on this PR will be with an eye to making this sort of thing more obvious.

  8. springcoil commented on Feb 27, 2015

    @springcoil

    Is this just a case of wrapping a function around that functionality and documenting it?
    I think some of the PR's are just a case of documentation.

  9. josef-pkt commented on Nov 23, 2015

    @josef-pkt
    Member

    I've also been working with two endogenous terms for Binomial analysis of contingency tables, like:
    print(sm.GLM.from_formula("yes + no ~ x", D, family=sm.families.Binomial()).fit().summary())

    some draft versions for notebooks are here https://github.com/josef-pkt/misc/tree/loglinear/notebooks focused on contingency tables and loglinear and Binomial analysis.
    (I figured out only some time ago that GLM Binomial is for count data and not just for binary/Bernoulli.)

  10. josef-pkt commented on Nov 23, 2015

    @josef-pkt
    Member

    I think right now this is mainly a doc issue. It works and there is no direct need for change. Adding frequency weights is in several other issues, and needs a general solution.

  11. josef-pkt commented on Dec 15, 2023

    @josef-pkt
    Member

    I'm closing this

    GLM handles what is requested here, including using a proportion as endog with the help of var_weights.

    #5282 is a separate issue for Binomial as a proper count model instead of a model for proportions.

  12. added this to the 0.14 milestone on Apr 8, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions