Skip to content

formula support for categorical endog variable in logistic regression #5552

Closed

Description

@stevenlis

SM: 0.9.0
For categorical endog variable in logistic regression, I still have to gerneate a dummay variable for it like the following.

import pandas as pd
import seaborn as sns
import numpy as np
import statsmodels.formula.api as smf

df = sns.load_dataset('tips')

# generate dummy
df['male'] = df.sex.map({'Male': 1, 'Female': 0})
# regression
formula = 'male ~ C(smoker) + C(time)'
model = smf.logit(formula, data=df).fit()
model.summary()

If I just do

formula = 'C(sex) ~ C(smoker) + C(time)'
model = smf.logit(formula, data=df).fit()
model.summary()

I will get

ValueError: operands could not be broadcast together with shapes (244,2) (244,) 

This is a little bit weird, since the formula support all categorical variables but the endog. I wonder if this could be a potential feature to improve.
Btw, is there any current workaround for this issue if I wanna use formula?

Activity

  1. bashtage commented on May 7, 2019

    @bashtage
    Member

    This is a patsy limit. You could just define a function C1

    def C1(cat):
         return pd.get_dummies(cat, drop_first=True)
    

    and then use

    formula = 'C1(sex) ~ C(smoker) + C(time)'

  2. bashtage commented on May 7, 2019

    @bashtage
    Member

    This might be a request for Patsy to provide an option in C to drop one category always.

  3. stevenlis commented on May 16, 2019

    @stevenlis
    Author

    Thanks. just curious if the results will be dependent on panda's coding.

  4. stevenlis commented on Jan 29, 2020

    @stevenlis
    Author

    I wonder if there is anyway I can define a function that accept two args then use it in the formula?
    like

    def Code(col, target):
         return pd.get_dummies(col, drop_first=True)[target]
    

    This way I can select the group I'm interested.

    formula = 'Code(sex, target='Male') ~ C(smoker) + C(time)'

    Or use this:
    https://patsy.readthedocs.io/en/latest/API-reference.html#handling-categorical-data ?

  5. bashtage commented on Jan 29, 2020

    @bashtage
    Member

    The formula will have access to any functions in the calling namespace

    def f(x):
        return np.exp(x)
    def g(x):
        return np.log(x)
    
    smf.ols("f(y) ~ g(z)", data)
    
  6. stevenlis commented on Jan 29, 2020

    @stevenlis
    Author

    for one arg is fine but what if I have two args?

  7. josef-pkt commented on Jan 29, 2020

    @josef-pkt
    Member

    If the y array is not numerical, then patsy always transforms to two col categorical

    however, because patsy just evals arbitrary code, the following works in the example

    ex = np.array("a a b b a b".split())
    endo, exo = patsy.dmatrices("I((ex=='a').astype(int)) ~ 1", {"ex": ex})
    
    
    np.asarray(endo)
    array([[1.],
           [1.],
           [0.],
           [0.],
           [1.],
           [0.]])
    
  8. stevenlis commented on Jan 29, 2020

    @stevenlis
    Author

    Sorry @josef-pkt I'm not quite following. How should I write this in a function form so that I can use it in formula of SM?

  9. josef-pkt commented on Jan 29, 2020

    @josef-pkt
    Member

    you can use "I((ex=='a').astype(int))" directly in the formula, then you can edit the reference level in the formula, i.e. replace 'a'

    e.g. the following should work

    formula = 'I((sex=='Male').astype(int)) ~ C(smoker) + C(time)'

  10. josef-pkt commented on Jan 29, 2020

    @josef-pkt
    Member

    to confirm that it also works with pandas (using column name in I())

    same result with

    import pandas as pd
    df = pd.DataFrame(ex, columns=["ex"])
    endo, exo = patsy.dmatrices("I((ex=='a').astype(int)) ~ 1", df)
    np.asarray(endo)
    
  11. stevenlis commented on Jan 29, 2020

    @stevenlis
    Author

    @josef-pkt Thanks buddy. That seems really work, but I have no idea why i worked. The doc basically says it's an identify function and nothing more
    https://patsy.readthedocs.io/en/latest/builtins-reference.html#patsy.builtins.I

    Could you please explain it a little bit?

  12. bashtage commented on Jan 30, 2020

    @bashtage
    Member

    I() prevents patsy from trying to parst what is in the (). For example, y ~ 1 + x1 + x2 + x3 vs y ~ 1 + x1 + I(x2 + x3). You should be able to replace the I above with a function

    def trans(x):
        (x == "a").astype(int)
    endo, exo = patsy.dmatrices("trans(ex) ~ 1", df)
    
  13. stevenlis commented on Jan 30, 2020

    @stevenlis
    Author

    @bashtage It seems like I had some trouble to understand what would be the input of the function we define. Now it makes sense.

    For the first approach using a user-defined function, the issue that we need to hard-code the selected category and neither the formula nor our output Dep. Variable will include the select group.

    def Code(col):
        return pd.get_dummies(col)['Male']
    
    formula = "Code(sex) ~ smoker + time"
    model = smf.logit(formula, data=df)
    results = model.fit()
    print(results.summary())
    Optimization terminated successfully.
             Current function value: 0.630824
             Iterations 5
                               Logit Regression Results                           
    ==============================================================================
    Dep. Variable:              Code(sex)   No. Observations:                  244
    Model:                          Logit   Df Residuals:                      241
    Method:                           MLE   Df Model:                            2
    Date:                Wed, 29 Jan 2020   Pseudo R-squ.:                 0.03160
    Time:                        20:34:41   Log-Likelihood:                -153.92
    converged:                       True   LL-Null:                       -158.94
    Covariance Type:            nonrobust   LLR p-value:                  0.006582
    ==================================================================================
                         coef    std err          z      P>|z|      [0.025      0.975]
    ----------------------------------------------------------------------------------
    Intercept         -0.0841      0.306     -0.275      0.784      -0.684       0.516
    smoker[T.No]       0.0381      0.282      0.135      0.892      -0.514       0.590
    time[T.Dinner]     0.9302      0.294      3.163      0.002       0.354       1.507
    ==================================================================================
    

    If we use I function, we can select the interested group on fly and it will also be displayed in our results output.

    formula = "I(pd.get_dummies(sex)['Male']) ~ smoker + time"
    
    formula = "I((sex == 'Male').astype(int)) ~ smoker + time"
    Optimization terminated successfully.
             Current function value: 0.630824
             Iterations 5
                                      Logit Regression Results                                  
    ============================================================================================
    Dep. Variable:     I(pd.get_dummies(sex)['Female'])   No. Observations:                  244
    Model:                                        Logit   Df Residuals:                      241
    Method:                                         MLE   Df Model:                            2
    Date:                              Wed, 29 Jan 2020   Pseudo R-squ.:                 0.03160
    Time:                                      20:37:22   Log-Likelihood:                -153.92
    converged:                                     True   LL-Null:                       -158.94
    Covariance Type:                          nonrobust   LLR p-value:                  0.006582
    ==================================================================================
                         coef    std err          z      P>|z|      [0.025      0.975]
    ----------------------------------------------------------------------------------
    Intercept          0.0841      0.306      0.275      0.784      -0.516       0.684
    smoker[T.No]      -0.0381      0.282     -0.135      0.892      -0.590       0.514
    time[T.Dinner]    -0.9302      0.294     -3.163      0.002      -1.507      -0.354
    ==================================================================================
    
    
    Optimization terminated successfully.
             Current function value: 0.630824
             Iterations 5
                                      Logit Regression Results                                  
    ============================================================================================
    Dep. Variable:     I(pd.get_dummies(sex)['Female'])   No. Observations:                  244
    Model:                                        Logit   Df Residuals:                      241
    Method:                                         MLE   Df Model:                            2
    Date:                              Wed, 29 Jan 2020   Pseudo R-squ.:                 0.03160
    Time:                                      20:37:08   Log-Likelihood:                -153.92
    converged:                                     True   LL-Null:                       -158.94
    Covariance Type:                          nonrobust   LLR p-value:                  0.006582
    ==================================================================================
                         coef    std err          z      P>|z|      [0.025      0.975]
    ----------------------------------------------------------------------------------
    Intercept          0.0841      0.306      0.275      0.784      -0.516       0.684
    smoker[T.No]      -0.0381      0.282     -0.135      0.892      -0.590       0.514
    time[T.Dinner]    -0.9302      0.294     -3.163      0.002      -1.507      -0.354
    ==================================================================================
    
    
  14. bashtage commented on Jan 30, 2020

    @bashtage
    Member

    PRs with new or modifications of existing notebooks are always welcome!

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions