Skip to content

statsmodels.formula.api.ols() Orthogonalization #3910

Open

Description

@TheChymera

Hello, I am running an ANOVA via the following code structure:

ols = statsmodels.formula.api.ols(model, data)
anova = statsmodels.api.stats.anova_lm(ols, typ=2)

I noticed that depending on the order in which factors are listed in model, variance (and consequently the F-score) is distributed differently along the factors.

Supposing that my data looks like:

value , factor1 , factor2
    9 ,       A ,       L
    8 ,       A ,       L
    9 ,       A ,       M
    9 ,       A ,       M
    1 ,       B ,       N
    2 ,       B ,       N
    2 ,       B ,       O
    1 ,       B ,       O

What will happen to the shared variance between factor1 and factor2? Will it all be ascribed to the first factor listed in the expression? Does the model orthgonalize the second listed factor to the first, or do I have to do that manually? Would the above data warrant a multicollinearity warning?

Activity

  1. josef-pkt commented on Sep 8, 2017

    @josef-pkt
    Member

    That's a property of type 2 ANOVA and the main reason I don't like it at all, and many statisticians don't "like" it either.
    Suppose we have factors A and B. Type 2 allocated in the fixed given sequence, constant -> constant + A -> constant + A + B. B includes only the contribution that is not already in constant + A.
    The variance and F-test for the interaction terms also depends on the coding (dummy, contrast or other coding).

    Only if the design matrix is orthogonal, then the order doesn't matter in type 2.

    Type 3 ANOVA does not depend on the ordering and drops one term at the time starting always from the full model similar to Wald test.

    Another possibility is to start from the smallest model and each term to it, in separate models that have one term more than the smallest model. This would be similar to a score-test where we start with the restricted model and check addition of different terms.

  2. josef-pkt commented on Sep 8, 2017

    @josef-pkt
    Member

    as cross-check:
    If we have 3 models results: results0 with constant, resultsA with y~A and resultsAB with y~A+B, then

    then the reported statistics for A and B in type 2 ANOVA should correspond to:
    resultA.compare_ftest(results0)
    resultAB.compare_ftest(resultsA)

    (I never checked whether this gives numerically identical answers, AFAIR)

  3. josef-pkt commented on Sep 8, 2017

    @josef-pkt
    Member

    I made this into a FAQ issue, and we can keep it open. AFAICS, we don't have an issue for it.

  4. TheChymera commented on Sep 8, 2017

    @TheChymera
    Author

    Type 3 ANOVA does not depend on the ordering and drops one term at the time starting always from the full model similar to Wald test.

    I'm not sure I understand the distinction between the ANOVA types. Looking here it seems like the type 2 already looks at the unique variance, and it's only type 1 which makes the first factor swallow everything up that it can. Is the page incorrect, or am I misunderstanding it?

    Also, I specify no interaction term for my model. What happens then to the anova types (1 and 3 ) which are looking for an interaction term?

  5. josef-pkt commented on Sep 8, 2017

    @josef-pkt
    Member

    Can you compare in your example anova type 2 with the compare_ftest case I had above?

    (Either something is strange with the definition or I have a misunderstanding in what I remember.)

    If there are only two factors, no other variables and no interaction terms, then in the linked definition type 2 and type 3 would be the same A versus A + B, and B versus (A + B). In that case it would be the partial effect of 1 factor if the other factor is already included.

  6. TheChymera commented on Sep 9, 2017

    @TheChymera
    Author

    Ok, so you are right, in that anova_lm type 2 and 3 will give me the same results if using the same model. Type 1 will make the first factor swallow up more of the variance.

    Regarding your example code, I get:

    AttributeError: 'DataFrame' object has no attribute 'compare_ftest'
    

    Not least of all, my use case is a bit more complicated, as I am actually trying to look at the main effects of three factors. Should I then (in your example) start with the third factor, or just with the constant?

    Alternatively, you could try and have a look at this locally. I have a full working example (well, it doesn't work as of the latest commit - but only due to that AttributeError I am now triggering) in this file, up to this line.

    Supposing you already have statsmodels, matplotlib, and seaborn, you could just git clone [email protected]:IBT-FMI/SAMRI.git and run it. The data is also distributed with the package and the example function knows where to find it.

  7. josef-pkt commented on Sep 9, 2017

    @josef-pkt
    Member

    compare_ftest is a method of the OLSResults.
    I meant replicating with explicitly estimating the models

    e.g. for a three factor model with only main effects, anova_lm should correspond to something like this (I didn't try the code snippet yet.)

    from statsmodels.formula.api import ols
    resA_B = ols('y ~ A + B', data=data).fit()
    resA_C = ols('y ~ A + C', data=data).fit()
    resB_C = ols('y ~ B + C', data=data).fit()
    resA_B_C = ols('y ~ A + B + C', data=data).fit()
    

    then type 3, and most likely type 2 should correspond to

    effectA = resA_B_C.compare_f_test(res_B_C) 
    effectB = resA_B_C.compare_f_test(res_A_C)
    effectC = resA_B_C.compare_f_test(res_A_B)
    

    I started to look at the anova_lm unit tests for an example, but don't have time yet to try it out.
    (Most likely I will try later today, because I'm supposed to know this but obviously don't, and I never went through all the test cases.)

    The anova test file statsmodels.stats.tests.test_anova also has the corresponding R code in comments for several of the test cases.

  8. josef-pkt commented on Sep 9, 2017

    @josef-pkt
    Member

    corrected spelling, missing underline compare_f_test

    here is a very quickly written notebook
    https://gist.github.com/josef-pkt/8cf9cdf30e4c726a2bb7478678e4e9b2

    anova type 2, type 3 and compare_f_test in wald style (starting from full model) look the same.

  9. TheChymera commented on Sep 9, 2017

    @TheChymera
    Author

    Ok, so the results (F,p,df) of the type 2 and 3 anova_lm are the same as compare_f_test.

    One thing that's different, is that the type 3 anova_lm suddenly shows an intercept. How so?

    Also, in the expression np.log(Days+1) ~ C(Duration) + C(Weight) + C(id2), is the +1 simply meant to avoid 0 evaluating to -Inf or is it like taking the intercept (I understand that is commonly denoted as -1) and moving it to the other side of the equation?

  10. TheChymera commented on Sep 9, 2017

    @TheChymera
    Author

    However, neither type 2 nor type 3 are robust to changing the factor order - which was my original question :-/ So what can I do to get an order-independent analysis of variance?

  11. josef-pkt commented on Sep 9, 2017

    @josef-pkt
    Member

    given that type 2 versus type 3 is partially out of the way, my second part in the initial comment was

    The variance and F-test for the interaction terms also depends on the coding (dummy, contrast or other coding).

    If you also get differences in the main effects, then I need to check the computational details. Likelihood ratio type tests are invariant to the encoding, Wald test depend on encoding because or if the underlying normalization/ factor encoding to avoid singular design affects the null hypothesis.

    the simple F-test using SSR seems to be invariant to changing the factor order

    res_all2 = ols('np.log(Days+1) ~ C(Weight) + C(id2) + C(Duration)',
                            data=data).fit()
    print(res_all2.compare_f_test(res_wi))
    print(res_all2.compare_f_test(res_di))
    print(res_all2.compare_f_test(res_dw))
    

    but based on a quick look, also type 2 and type 3 anova_lm produce the same numbers, just listed in a different sequence. (The design matrix in the test case shouldn't be orthogonal because it is not balanced after dropping some observations.)

    Does one of your examples produce different numbers depending on the sequence in the formula, or just a reordering of the rows?

  12. TheChymera commented on Sep 17, 2017

    @TheChymera
    Author

    Sorry for the delay, I put together an example you should eb able to copy/paste directly into ipython:

    In [1]: import pandas as pd
    
    In [2]: import statsmodels.api as sm
    /usr/lib64/python3.4/importlib/_bootstrap.py:321: FutureWarning: The pandas.core.datetools module is deprecated and will be removed in a future version. Please use the pandas.tseries module instead.
      return f(*args, **kwds)
    
    In [3]: import statsmodels.formula.api as smf
    
    In [4]: df = pd.DataFrame.from_csv("http://chymera.eu/debug/statsmodels/multilevel.csv")
    
    In [5]: model1="similarity ~ C(trial) + C(sub) + C(ses) -1"
    
    In [6]: model2="similarity ~ C(sub) + C(trial) + C(ses) -1"
    
    In [7]: print(sm.stats.anova_lm(smf.ols(model1, data=df).fit(), typ=2))
                sum_sq    df            F        PR(>F)
    C(trial)  0.748690   2.0  3320.213755  7.831732e-38
    C(sub)    0.407726  10.0   361.628015  5.752846e-30
    C(ses)    0.000695   4.0     1.542109  2.136548e-01
    Residual  0.003608  32.0          NaN           NaN
    
    In [8]: print(sm.stats.anova_lm(smf.ols(model2, data=df).fit(), typ=2))
                sum_sq    df             F        PR(>F)
    C(sub)    1.348362  11.0   1087.195305  6.620421e-38
    C(trial)  1.319749   1.0  11705.370840  1.305561e-42
    C(ses)    0.000695   4.0      1.542109  2.136548e-01
    Residual  0.003608  32.0           NaN           NaN
    
    In [9]: print(sm.stats.anova_lm(smf.ols(model1, data=df).fit(), typ=3))
                sum_sq    df            F        PR(>F)
    C(trial)  0.748690   2.0  3320.213755  7.831732e-38
    C(sub)    0.407726  10.0   361.628015  5.752846e-30
    C(ses)    0.000695   4.0     1.542109  2.136548e-01
    Residual  0.003608  32.0          NaN           NaN
    
    In [10]: print(sm.stats.anova_lm(smf.ols(model2, data=df).fit(), typ=3))
                sum_sq    df             F        PR(>F)
    C(sub)    1.348362  11.0   1087.195305  6.620421e-38
    C(trial)  1.319749   1.0  11705.370840  1.305561e-42
    C(ses)    0.000695   4.0      1.542109  2.136548e-01
    Residual  0.003608  32.0           NaN           NaN
    

    As you can see, switching the independent variable order in the model changes the ANOVa result - in precisely the same fashion both for type 2 and 3.

  13. josef-pkt commented on Sep 17, 2017

    @josef-pkt
    Member

    Note, ses has the same effect/pvalue in all 4 cases.

    AFAICS, in this case the problem is that the "-1" in the formula forces that the constant is included in the first categorical. In the first case "trial" includes the effect of the constant, because without trial, there is no constant in the regression. The same for "sub" in the second case.

    When I include the constant as separate term, then the effects are identical across all 4 versions except for reordering. The categorical effects are relative to a model that includes the constant and the other categoricals.

    model1="similarity ~ C(trial) + C(sub) + C(ses)" # -1"
    model2="similarity ~ C(sub) + C(trial) + C(ses)" # -1"
    

    as before, I still don't know why typ=2 skips listing the intercept in the table, even though it is explicitly included and it is included in the typ 3 table.

  14. josef-pkt commented on Sep 18, 2017

    @josef-pkt
    Member

    I have no idea if the results make sense in this case with a factor that is a superset of another factor. (I don't know what this situation is called, nested in patsy does not seem to fit.)

    AFAICS, C(trial) is redundant when C(sub) is already included because trials are supersets of sub
    (I tried with and without -1)

    In [59]:
    model1_m1 ="similarity ~ C(trial) + C(sub) + C(ses) - 1"
    res_m1 = smf.ols(model1_m1, data=df).fit()
    model1_wot ="similarity ~ C(sub) + C(ses)"  # without trial
    res_wot = smf.ols(model1_wot, data=df).fit()
    print(res_m1.compare_f_test(res_wot))
    
    (-inf, nan, 0.0)
    m:\josef_new\eclipse_ws\statsmodels\statsmodels_py34_pr\statsmodels\regression\linear_model.py:1904: RuntimeWarning: divide by zero encountered in double_scalars
      f_value = (ssr_restr - ssr_full) / df_diff / ssr_full * df_full
    
    In [56]:
    print(res_m1.compare_lm_test(res_wot))
    ---------------------------------------------------------------------------
    ValueError                                Traceback (most recent call last)
    <ipython-input-56-5c231509f013> in <module>()
    ----> 1 print(res_m1.compare_lm_test(res_wot))
    
    m:\josef_new\eclipse_ws\statsmodels\statsmodels_py34_pr\statsmodels\regression\linear_model.py in compare_lm_test(self, restricted, demean, use_lr)
       1808 
       1809         if not self._is_nested(restricted):
    -> 1810             raise ValueError("Restricted model is not nested by full model.")
       1811 
       1812         wresid = restricted.wresid
    
    ValueError: Restricted model is not nested by full model.
    

    I'm getting a "singular" warning when printing summary. And the two models have the same design rank , df_resid and the same ssr, llf.

    [2] The smallest eigenvalue is 3.08e-31. This might indicate that there are
    strong multicollinearity problems or that the design matrix is singular.
    
    In [73]:
    res_m1.ssr, res_m1.df_resid, res_m1.llf, res_m1.model.exog.shape[1]
    Out[73]:
    (0.0036079139824626901, 32.0, 155.96705724896671, 16)
    
    In [74]:
    res_wot.ssr, res_wot.df_resid, res_wot.llf, res_wot.model.exog.shape[1]
    Out[74]:
    (0.0036079139824626897, 32.0, 155.96705724896671, 15)
    
    

    I don't know what anova_lm is doing in this singular case.

  15. TheChymera commented on Sep 20, 2017

    @TheChymera
    Author

    Just to recap, the order issue is resolved:

    In [1]: import pandas as pd
    
    In [2]: import statsmodels.api as sm
    
    In [3]: import statsmodels.formula.api as smf
    
    In [4]: df = pd.DataFrame.from_csv("http://chymera.eu/debug/statsmodels/multilevel.csv")
    
    In [5]: model1="similarity ~ C(trial) + C(sub) + C(ses) -1"
    
    In [6]: model2="similarity ~ C(sub) + C(trial) + C(ses) -1"
    
    In [7]: model3="similarity ~ C(trial) + C(sub) + C(ses)"
    
    In [8]: model4="similarity ~ C(sub) + C(trial) + C(ses)"
    
    In [9]: print(sm.stats.anova_lm(smf.ols(model1, data=df).fit(), typ=3))
                sum_sq    df            F        PR(>F)
    C(trial)  0.748690   2.0  3320.213755  7.831732e-38
    C(sub)    0.407726  10.0   361.628015  5.752846e-30
    C(ses)    0.000695   4.0     1.542109  2.136548e-01
    Residual  0.003608  32.0          NaN           NaN
    
    In [10]: print(sm.stats.anova_lm(smf.ols(model2, data=df).fit(), typ=3))
                sum_sq    df             F        PR(>F)
    C(sub)    1.348362  11.0   1087.195305  6.620421e-38
    C(trial)  1.319749   1.0  11705.370840  1.305561e-42
    C(ses)    0.000695   4.0      1.542109  2.136548e-01
    Residual  0.003608  32.0           NaN           NaN
    
    In [11]: print(sm.stats.anova_lm(smf.ols(model3, data=df).fit(), typ=3))
                 sum_sq    df            F        PR(>F)
    Intercept  0.535864   1.0  4752.786815  2.248754e-36
    C(trial)   0.255327   1.0  2264.594940  2.843731e-31
    C(sub)     0.005015  10.0     4.447924  5.826734e-04
    C(ses)     0.000695   4.0     1.542109  2.136548e-01
    Residual   0.003608  32.0          NaN           NaN
    
    In [12]: print(sm.stats.anova_lm(smf.ols(model4, data=df).fit(), typ=3))
                 sum_sq    df            F        PR(>F)
    Intercept  0.535864   1.0  4752.786815  2.248754e-36
    C(sub)     0.005015  10.0     4.447924  5.826734e-04
    C(trial)   0.255327   1.0  2264.594940  2.843731e-31
    C(ses)     0.000695   4.0     1.542109  2.136548e-01
    Residual   0.003608  32.0          NaN           NaN
    

    AFAICS, in this case the problem is that the "-1" in the formula forces that the constant is included in the first categorical.

    To me that seems unintuitive, I actually included the constant in the model because I was trying to get values assigned to all categorical variable values. (without it, in the summary, one categorical variable value is missing for each categorical variable).

    I have no idea if the results make sense in this case with a factor that is a superset of another factor.

    The question which I hoped to answer with ANOVA (and which I believe to be answering based on the values) is “how much more variance, in excess of the trial variance do the subjects explain?”. It seems (in the context of my study) reasonable that the subjects have a significant effect, though not nearly as significant as the trial type.

    I'm getting a "singular" warning when printing summary.

    I do as well --- in how far is that an issue, would it invalidate the conclusions I drew above? I tried to grasp what a singular design matrix is in this context, but I am afraid I do not understand how the notion relates to my model design.

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

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions