You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Creating binomial model from formula reverses prediction direction #2181
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.
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.
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)
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.
@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.
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.
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.
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]']
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.
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.
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.
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.)
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?
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.
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.
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.
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:
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.
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.)
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!!
Activity
josef-pkt commentedon Jan 13, 2015
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)
According to our GLM docstring, statsmodels interprets it as (success, failure) instead of patsy's (failure, success)
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.
jseabold commentedon Jan 13, 2015
Related to #2049. Needs a review.
josef-pkt commentedon Jan 13, 2015
@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
endogthe 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.
jseabold commentedon Jan 13, 2015
Yes, I imagined factors encompassing patsy-type factors. Incidentally, using the byte formula raises an error for me on Python 3.
jseabold commentedon Jan 13, 2015
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.BrenBarn commentedon Jan 13, 2015
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.
jseabold commentedon Jan 13, 2015
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.
josef-pkt commentedon Jan 13, 2015
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_namesand 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]']josef-pkt commentedon Jan 13, 2015
The MNLogit issue is #837 second part discussed on mailing list. choosing reference category in MNLogit is essentially the same point as choosing the
successlabel here.BrenBarn commentedon Jan 13, 2015
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=Trueto set True as the success value), but even being able to pass by column number would allow more flexibility than what we have now.josef-pkt commentedon Apr 14, 2015
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.
josef-pkt commentedon Mar 20, 2019
It would be possible to add a keyword in
from_formulaof 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.)
miaojingang commentedon Aug 5, 2020
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.
himotimo commentedon Mar 22, 2021
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?
josef-pkt commentedon Mar 22, 2021
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.
himotimo commentedon Mar 22, 2021
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.
josef-pkt commentedon Mar 22, 2021
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.
himotimo commentedon Mar 22, 2021
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:
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!
josef-pkt commentedon Mar 22, 2021
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.)
himotimo commentedon Mar 22, 2021
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!!