Skip to content

Creating binomial model from formula reverses prediction direction #2181

Open

Description

@BrenBarn

If a GLM is fit using a formula, the direction of the prediction is reversed so that positive coefficients indicate a higher likelihood of a False or zero value in the dependent variable. See discussion here.

An example:

import numpy as np
import statsmodels as sm
import statsmodels.api

x = 3*np.random.normal(size=1000)
prob = 1 / (1 + np.exp(-x))                                                                                    
y = np.random.uniform(size=1000) < prob

model = sm.api.GLM(y, x, family=sm.api.families.Binomial()).fit()
print(model.summary())

model = sm.api.GLM.from_formula(b'y~x', data={'x': x, 'y': y}, family=sm.api.families.Binomial()).fit()
print(model.summary())

In the first model, the coefficient of x is positive, as it should be (higher x value makes a True y more likely). In the second model, the coefficient of x is erroneously negative.

Also, although "positive coefficient means True/1 prediction" is probably what most people would expect, it should still be explicitly documented.

Activity

  1. josef-pkt commented on Jan 13, 2015

    @josef-pkt
    Member

    The reason for the change in interpretation of success and failure is that patsy converts a boolean (and I guess everything else non-numeric) to a two column dummy coding with (False, True)

    In [15]:
    
    en, ex = patsy.dmatrices(b'y~x', data={'x': x, 'y': y})
    
    np.asarray(en)[:5]
    
    Out[15]:
    
    array([[ 1.,  0.],
           [ 0.,  1.],
           [ 0.,  1.],
           [ 0.,  1.],
           [ 1.,  0.]])
    
    In [16]:
    
    en
    
    Out[16]:
    
    DesignMatrix with shape (1000, 2)
      y[False]  y[True]
             1        0
             0        1
             0        1
             0        1
             1        0
             0        1
             1        0
    

    According to our GLM docstring, statsmodels interprets it as (success, failure) instead of patsy's (failure, success)

    endog : array-like
    
        1d array of endogenous response variable. This array can be 1d or 2d. Binomial family models accept a 2d array with two columns. If supplied, each observation is expected to be [success, failure].
    

    Right now, I don't see much that we could do, I don't think we can robustly detect what patsy is doing and what the user "really wants". Reversing the meaning of 2-column endog to [failure, success] is not backwards compatible, and would be a strange policy to accommodate patsy's formula interpretation.

    Users can avoid it by specifying the coding for endog, but I don't remember how to do this right now.

  2. jseabold commented on Jan 13, 2015

    @jseabold
    Member

    Related to #2049. Needs a review.

  3. josef-pkt commented on Jan 13, 2015

    @josef-pkt
    Member

    @jseabold #2049 and related is for the support of categorical endog in statsmodels.

    However, the main "bug" here is patsy. Is there a way to turn of that patsy give endog the categorical "treatment"?
    The only related issue I found is #878 but I thought there are others where patsy converts endog before "we" get our hands on it.

  4. jseabold commented on Jan 13, 2015

    @jseabold
    Member

    Yes, I imagined factors encompassing patsy-type factors. Incidentally, using the byte formula raises an error for me on Python 3.

  5. jseabold commented on Jan 13, 2015

    @jseabold
    Member

    The only way I see to turn it off, is to cast the endog to int if it's boolean. We can do this under the hood, but it's a bit cumbersome. Using C(y, Treatment(True)) doesn't work because it returns the full rank endog. Hmm, a bit of a pain.

  6. BrenBarn commented on Jan 13, 2015

    @BrenBarn
    Author

    Why was (success, failure) chosen in the first place? If 0 is failure and 1 is success, it seems natural that, loosely speaking, responses[0] should be failure and responses[1] should be success. I realize some fixes might result in an incompatible change, but I think it's pretty important to fix this in the long term, as the convention that the prediction goes from "less" to "greater" seems pretty strong.

  7. jseabold commented on Jan 13, 2015

    @jseabold
    Member

    It was chosen to conform to the long-standing conventions in R's GLM,
    which, admittedly, doesn't seem like such a good idea now.

  8. josef-pkt commented on Jan 13, 2015

    @josef-pkt
    Member

    AFAIU, we have the same problem with the other categorical/binary endog also. (do we have a MNLogit solution ?)

    The only clean solution is to add an option to patsy to leave endog alone, I(y) ~ ... doesn't work either, it still converts contrary (?) to the patsy documentation.

    Another dirtier workaround is to parse the endog_names and use only the second column if it looks like patsy converted from categorical/boolean in from_formula.
    For the boolean case, checking for endog_names endswith('[True]') would be relatively unambiguous, I think.
    Guessing the reference case for string might be more difficult ['y[male]', 'y[female]']

    [23]: model.model.endog_names
    Out[23]: ['y[False]', 'y[True]']
    
  9. josef-pkt commented on Jan 13, 2015

    @josef-pkt
    Member

    The MNLogit issue is #837 second part discussed on mailing list. choosing reference category in MNLogit is essentially the same point as choosing the success label here.

  10. BrenBarn commented on Jan 13, 2015

    @BrenBarn
    Author

    What about if the discrete models had an option allowing you to specify which column of the Y matrix was to be used as "success" (and likewise as reference value for multinomial)? Ideally this could be specified by value (i.e., you could pass something like referenceValue=True to set True as the success value), but even being able to pass by column number would allow more flexibility than what we have now.

  11. josef-pkt commented on Apr 14, 2015

    @josef-pkt
    Member

    pydata/patsy#62
    discussed with Nathaniel at pycon 2015,
    This would provide options to turn of categorical handling for the endog when calling dmatrices.
    In this case, we would handle whatever transformation we need in Binomial or MNLogit in statsmodels.

    Alternative could be to request a specific encoding from patsy, instead of creating endog with the usual encoding rules.

  12. josef-pkt commented on Mar 20, 2019

    @josef-pkt
    Member

    It would be possible to add a keyword in from_formula of GLM, Logit and similar that allows user to override the default.
    That would be the only way to avoid having to guess what the user intended.

    (It would be possible to change the default for boolean endog over time with a FutureWarning if users have a keyword to get consistent behavior over versions.)

  13. miaojingang commented on Aug 5, 2020

    @miaojingang

    I was bitten by this today and was able to notice only because I had analyzed the same data in R and knew the signs to expect.

    This seems like a serious issue. Image someone using the model for decision making.

    I feel we should make smf consistent with sm and thus with R. +1 on changing the default and issuing a warning.

  14. himotimo commented on Mar 22, 2021

    @himotimo

    Hey, I'm running into this problem also. I'm using the discrete_model.Logit to create consecutive binary logistic regressions on an ordinal dataset after proportional odds assumption is not met. This causes the problem that some of the results are inverted and some are not, causing the interpretation of overall results to be impossible. In my binary logistic regressions, my independent variable is a single column with integer values 0 or 1. Could you tell me if there's a way to fix this? Is "success" somehow based on the sample sizes of the levels of dependent variable or something?

  15. josef-pkt commented on Mar 22, 2021

    @josef-pkt
    Member

    If the dependent values, endog, are integer dtype 0, 1, then there should not be a problem, and 1 should be the non-reference level.
    The formula handling by patsy does not change numeric data including integers. If endog values are boolean or strings , then they will be processed by patsy as categorical.

  16. himotimo commented on Mar 22, 2021

    @himotimo

    Okay, thank you for your answer. Is it possible that independent variables are somehow flipped then? There is some really weird discrepancy happening. My independent variables are dummy coded so that each IV has an integer value of 1 or 0 in a single column, and there are multiple individual variables in the model. When I look at the results, some of them seem to be correct when comparing to the basic visualizations of the data, but some seem to be reversed after the middle split (classes 1-2 vs 3-5). I tried to check the results by running the binary logistic regressions in SPSS for the same splits for the data, and it looks like some variables are reversed after a certain split in the Statsmodels Logit. Maybe I can send you some pictures of the visualizations of results.

  17. josef-pkt commented on Mar 22, 2021

    @josef-pkt
    Member

    Is it possible that independent variables are somehow flipped then?

    to understand
    Splitting data means that you categorize a multinomial variable into a binary variable, but you keep the same design matrix, exog?
    You are not splitting the data by observations?

    Can you make up a simple example? It can be fake data if it shows the behavior.

    And to check that it's really the formula interface.
    Can you run the Logit model with and without formula, to see if there are differences if the formula handling has to recode the data after the split.

    In general,
    When we split data by observations and run a model on a subset, then the formula interface will recode any categorical variables and other data dependent transformations in the formulas. For example, a subset might have an empty cell, and a level will be dropped, or the design matrix can become rank deficient.
    In those cases it is better to create a overall design matrix and split it directly instead of using formulas on subsets.

    If exog does not change in the split and only endog does, then the formula handling should replicate exactly the same design matrix.

  18. himotimo commented on Mar 22, 2021

    @himotimo

    I have an ordinal variable "skill level" that has integer values 1-5. The data is from a survey, where the respondents chose their skill level in a video game. The independent variables are dummy coded answers to multiple choice questions. Each option in the multiple choice question is now in its own column and has a value of 1 if it was chosen, and 0 if not. The aim of the study is to study the relationships between answers and skill level. So I run an ordinal regression with the skill level being dependent variable and answers being independent variables. If the proportional odds assumption is not met, I run individual binary logistic regressions by splitting the data in half between each consecutive skill level.
    So I run four different binary logistic regressions:

    • sm.Logit(y=[0= skill(1), 1= skill(2-5)], X=[[IV1], [IV2], [IV3], ...])
    • sm.Logit(y=[0= skill(1-2), 1= skill(3-5)], X=[[IV1], [IV2], [IV3], ...])
    • sm.Logit(y= [0= skill(1-3), 1= (skill 4-5)], X=[[IV1], [IV2], [IV3], ...])
    • sm.Logit(y= [0= skill(1-4), 1= skill(5)], X=[[IV1], [IV2], [IV3], ...])

    I fit a new Logit for each of these splits using model.fit(disp=0, method='bfgs'). All of the Logits contain the whole dataset, just the way the dataset is split into two for the exog is different. The design matrix or independent variables are the same, I don't do any elimination on the variables. The dataset has no missing values as I have dropped rows that had missing values in preprocessing phase. All the IVs are integer columns, value 0 or 1. After running the regressions, I study the coefficients and p-values to see if the original ordinal regression was in fact a good summary of the data or not.

    Now, in my problem it seems like in some cases the results are inversed for example for the third and fourth Logit. However, when I run binary logistic regressions for the same splits in SPSS, the results are not reversed.

    I'm not entirely sure what you mean by saying that I should create an overall design matrix and split it directly instead of using formulas on subsets. How exactly would I do that? And how would I split it "directly"? My data is in a Pandas DataFrame.

    Thanks for your help!

  19. josef-pkt commented on Mar 22, 2021

    @josef-pkt
    Member

    Your are not using the formulas then?

    This issue is about how formulas recode the dependent variable.

    The way you describe your calls to sm.Logit(y=[0= skill(1), 1= skill(2-5)], X=[[IV1], [IV2], [IV3], ...]) there should not be a problem with changing the direction of variables.

    The only issue I can think about that might cause this are relate convergence failures, or problems like separation, empty cells, collinearity or similar. Because you use the same independent variables it shouldn't be directly related to the design matrix.

    Check some fit statistic to see whether SPSS and statsmodels get, for example, the same loglikelihood, llf, aic.
    Check that all models have converged in the optimization.

    otherwise, SPSS is doing something strange or you have a mistake in your code.

    Aside: When I worked on and merged OrderedModel, I didn't look at the details for this comparison and we have no hypothesis tests or measures for how well proportional odds assumption matches the data.

    If you have code to contribute, then adding functionality in this area to statsmodels would be useful.
    (I might get back to ordinal models in the next months.)

  20. himotimo commented on Mar 22, 2021

    @himotimo

    Ah, I'm sorry no I'm not using formulas.. The problem just seemed similar so I thought it might be linked to what I was doing. I took care of separation by dropping columns which had a constant value for a skill level.

    At first, I only wanted to use statsmodels for my analysis because of the flexibility Python has. However I noticed statsmodels orderedmodel doesn't offer the proportional odds test, so in my workflow I test it in SPSS, and then do rest of the analysis with statsmodels. So I haven't made code for that.

    I think you may be right, the data is probably the problem. For the first and the last logits, the levels are very unbalanced. Maybe I'll try SMOTE or something to tackle the problem. Thank you very much for helping me out!!

  21. added
    type-bug-wrong
    on Sep 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    comp-formulacomp-genmoddesigntype-bugtype-bug-wrong

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions