Skip to content

Results of n-way MANOVA with interactions differ significantly from results from R's stats::manova #8713

Open

Description

@mikrzol

(I'm not sure if this is a bug or a feature request - sorry for false alarm if this was expected!)

I get different results when performing n-way MANOVA with interactions when using this implementation and R.

Let's use data from the file I attached as an example.
metals.csv

In R I would use the following formula:

m_data = read.csv('https://github.com/statsmodels/statsmodels/files/10882245/metals.csv')
metal_manova = manova(cbind(C1, C2) ~ extractants * metals, data=m_data)
summary(metal_manova, test='Wilks')

This yields the following result:

Df Wilks approx F num Df den Df Pr(>F)
extractants 9 0.0039340 164.38 18 198 < 2.2e-16 ***
metals 4 0.0019440 536.58 8 198 < 2.2e-16 ***
extractants:metals 36 0.0005648 112.97 72 198 < 2.2e-16 ***
Residuals 100

Using the following steps:

from statsmodels.multivariate.manova import MANOVA
import pandas as pd
m_df = pd.read_csv('https://github.com/statsmodels/statsmodels/files/10882245/metals.csv')
m_man = MANOVA.from_formula('C1 + C2 ~ extractants * metals', data=m_df)
m_res = m_man.mv_test().summary_frame
m_res[m_res.index.get_level_values(1) == 'Wilks\' lambda']

I get the following result:

Effect Statistic Value Num DF Den DF F Value Pr > F
Intercept Wilks' lambda 0.999777 2 99.0 0.011051 0.989011
extractants Wilks' lambda 0.808417 18 198.0 1.23418 0.236848
metals Wilks' lambda 0.942882 8 198.0 0.738631 0.657287
extractants:metals Wilks' lambda 0.000565 72 198.0 112.965548 0.0

i.e. the F values are completely different in these two implementations (and thus the Pr > F is also different). Why is it the case? The results are the same for statsmodels'and R's implementations when there is no interaction between the independent variables - only the analysis with interactions yield different results. Can I specify some parameters that would make the results the same as in R?

I'm working with version 0.13.5 in WSL2. Python version 3.10.6.

Activity

  1. josef-pkt commented on Mar 3, 2023

    @josef-pkt
    Member

    I don't know what causes those very large differences.

    Here is a long issue on difference between statsmodels and SPSS #6464

    In unbalanced anovas, both encoding of categorical and type of anova can have a large effect on the results. But I'm not really familiar with most of the MANOVA details or variants.

    One guess would be that R stats manova computes a type 1 (?) anova, where the main effects are significant on their own but not when including the interaction effect.

  2. josef-pkt commented on Mar 3, 2023

    @josef-pkt
    Member

    Can you add the R results without interaction effect?

  3. mikrzol commented on Mar 3, 2023

    @mikrzol
    Author

    Sure, it would be:

    m_data = read.csv('https://github.com/statsmodels/statsmodels/files/10882245/metals.csv')
    metal_manova = manova(cbind(C1, C2) ~ extractants + metals, data=m_data)
    summary(metal_manova, test='Wilks')
    Df Wilks approx F num Df den Df Pr(>F)
    extractants 9 0.61729 4.0918 18 270 1.441e-07 ***
    metals 4 0.40943 18.9952 8 270 < 2.2e-16 ***
    Residuals 136

    In statsmodels the results are as follows:

    Effect Statistic Value Num DF Den DF F Value Pr > F
    Intercept Wilks' lambda 0.973636 2 135.0 1.827725 0.164735
    extractants Wilks' lambda 0.617288 18 270.0 4.091826 0.0
    metals Wilks' lambda 0.409431 8 270.0 18.995228 0.0
  4. josef-pkt commented on Mar 3, 2023

    @josef-pkt
    Member

    I don't really understand what's going on. The data looks balance with 3 observations per cell

    If I use Helmert coding, I get very different answers, same as R at floating point precision

    m_man = MANOVA.from_formula('C1 + C2 ~ C(extractants, Helmert) * C(metals, Helmert)', data=m_df)
    m_res = m_man.mv_test().summary_frame
    res = m_res[m_res.index.get_level_values(1) == 'Wilks\' lambda']
    print(res)
                                                                 Value Num DF  \
    Effect                                     Statistic                        
    Intercept                                  Wilks' lambda  0.005816      2   
    C(extractants, Helmert)                    Wilks' lambda  0.003934     18   
    C(metals, Helmert)                         Wilks' lambda  0.001944      8   
    C(extractants, Helmert):C(metals, Helmert) Wilks' lambda  0.000565     72   
    
                                                             Den DF     F Value  \
    Effect                                     Statistic                          
    Intercept                                  Wilks' lambda   99.0  8461.53262   
    C(extractants, Helmert)                    Wilks' lambda  198.0  164.377752   
    C(metals, Helmert)                         Wilks' lambda  198.0  536.584806   
    C(extractants, Helmert):C(metals, Helmert) Wilks' lambda  198.0  112.965548   
    
                                                             Pr > F  
    Effect                                     Statistic             
    Intercept                                  Wilks' lambda    0.0  
    C(extractants, Helmert)                    Wilks' lambda    0.0  
    C(metals, Helmert)                         Wilks' lambda    0.0  
    C(extractants, Helmert):C(metals, Helmert) Wilks' lambda    0.0  
    
    res["Pr > F"].to_numpy()
    array([2.2327275071851898e-111, 1.7172312697863343e-108,
           9.280908812934959e-130, 1.484331159350747e-129], dtype=object)
    
    stat = res["Value"].to_numpy(dtype=float)
    
    stat[1:] - [0.0039340182601693471, 0.0019440456693583979, 0.0005647834453735598]
    array([2.96724451e-15, 1.53501344e-15, 4.54605971e-16])
    
  5. josef-pkt commented on Mar 3, 2023

    @josef-pkt
    Member

    That's it.
    R stats manova uses by default the Helmert encoding.
    I got the same result in R before and after setting the contrast option with helmert.

    With helmert coding the design matrix is orthogonal

    np.max(np.abs(np.corrcoef(m_man.exog[:, 1:].T) - np.eye(m_man.exog.shape[1] - 1)))
    2.220446049250313e-16
    

    I guess we should add explaining Helmert coding to a docstring or docs

  6. mikrzol commented on Mar 6, 2023

    @mikrzol
    Author

    That indeed seems to solve the issue for this data, but I encounter an error when I try to use Helmert contrasts to my actual test data:
    example.csv

    When I use:

    import pandas as pd
    from statsmodels.multivariate.manova import MANOVA
    p_df = pd.read_csv('https://github.com/statsmodels/statsmodels/files/10897687/example.csv', index_col=0)
    formula = 'PC1 + PC2 + PC3 + PC4 ~ C(Genotype, Helmert) * C(Temp, Helmert) * C(Time, Helmert)'
    fit = MANOVA.from_formula(formula, data=p_df)
    fit.mv_test().summary_frame

    the model is created correctly using MANOVA.from_formula, but calling fit.mv_test() results in ValueError: zero-size array to reduction operation maximum which has no identity.

    I don't know what to think here, since I can perform the analysis in R without any issues:

    e_data = read.csv('https://github.com/statsmodels/statsmodels/files/10897687/example.csv', row.names = 1)
    m_e = manova(cbind(PC1, PC2, PC3, PC4) ~ Genotype * Temp * Time, data=e_data)
    m_e$contrasts
    summary(m_e, test='Wilks')

    m_e$contrasts also shows that R uses 'contr.treatment', not 'contr.helmert' in this case. Weird.

  7. josef-pkt commented on Mar 7, 2023

    @josef-pkt
    Member

    using the debugger, I found that it breaks when testing the intercept. I don't know why or why it is doing that

    However it doesn't happen with patsy's standard coding for categorical

    This is what I get if I remove the explicit intercept

    p_df = pd.read_csv('https://github.com/statsmodels/statsmodels/files/10897687/example.csv', index_col=0)
    formula = 'PC1 + PC2 + PC3 + PC4 ~ C(Genotype, Helmert) * C(Temp, Helmert) * C(Time, Helmert) - 1'
    fit = MANOVA.from_formula(formula, data=p_df)
    m_res = fit.mv_test().summary_frame
    pd.set_option('display.width', 1000)
    print(m_res[m_res.index.get_level_values(1) == 'Wilks\' lambda'])
                                                                         Value Num DF    Den DF   F Value    Pr > F
    Effect                                             Statistic                                                   
    C(Genotype, Helmert)                               Wilks' lambda  0.537404     12  55.85228  1.231318  0.285792
    C(Temp, Helmert)                                   Wilks' lambda   0.70032      4      21.0  2.246571  0.098472
    C(Time, Helmert)                                   Wilks' lambda   0.98168      4      21.0  0.097974  0.981956
    C(Genotype, Helmert):C(Temp, Helmert)              Wilks' lambda  0.466618      8      42.0   2.43561  0.029155
    C(Genotype, Helmert):C(Time, Helmert)              Wilks' lambda  0.453839      8      42.0   2.54307  0.023473
    C(Temp, Helmert):C(Time, Helmert)                  Wilks' lambda  0.806734      4      21.0  1.257722  0.317694
    C(Genotype, Helmert):C(Temp, Helmert):C(Time, H... Wilks' lambda  0.378451      8      42.0  3.284039  0.005347
    
  8. josef-pkt commented on Mar 7, 2023

    @josef-pkt
    Member

    The bug happens because all eigenvalues are close to zero (below 1e-8 threshold) and the test matrices are empty when testing the intercept.

    My guess is that for MANOVA we can skip testing the intercept.
    More generally, we need to handle the edge case with empty test matrices, or figure out why all eigenvalues are zero
    (Aside: I don't remember why intermediate results are complex, maybe because of eigenvalues of asymmetric matrix)

    from debugger session using the latest example as test case.

    > ...\statsmodels\statsmodels\multivariate\multivariate_ols.py(360)_multivariate_test()
    -> stat_table = multivariate_stats(eigv2, p, q, df_resid)
    (Pdb) p name
    'Intercept'
    (Pdb) hypo
    ['Intercept', array([[1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]]), None]
    (Pdb) hypotheses
    [['Intercept', array([[1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]]), None], ['C(Genotype, Helmert)', array([[0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
           [0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0.]]), None], ['C(Temp, Helmert)', array([[0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.]]), None], ['C(Time, Helmert)', array([[0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0.]]), None], ['C(Genotype, Helmert):C(Temp, Helmert)', array([[0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0.],
           [0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0.]]), None], ['C(Genotype, Helmert):C(Time, Helmert)', array([[0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.],
           [0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0.]]), None], ['C(Temp, Helmert):C(Time, Helmert)', array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0.]]), None], ['C(Genotype, Helmert):C(Temp, Helmert):C(Time, Helmert)', array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0.],
           [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.]]), None]]
    (Pdb) eigv1
    *** NameError: name 'eigv1' is not defined
    (Pdb) eigv2
    array([-7.48674631e-46-1.36665658e-45j, -7.48674631e-46+1.36665658e-45j,
            0.00000000e+00+0.00000000e+00j,  2.80694850e-29+0.00000000e+00j])
    
  9. josef-pkt commented on Mar 7, 2023

    @josef-pkt
    Member

    This is what I get if I change the code to skip testing the intercept:

    p_df = pd.read_csv('https://github.com/statsmodels/statsmodels/files/10897687/example.csv', index_col=0)
    formula = 'PC1 + PC2 + PC3 + PC4 ~ C(Genotype, Helmert) * C(Temp, Helmert) * C(Time, Helmert)'
    fit = MANOVA.from_formula(formula, data=p_df)
    m_res = fit.mv_test().summary_frame
    pd.set_option('display.width', 1000)
    print(m_res[m_res.index.get_level_values(1) == 'Wilks\' lambda'])
                                                                         Value Num DF Den DF   F Value    Pr > F
    Effect                                             Statistic                                                
    C(Genotype, Helmert)                               Wilks' lambda  0.537404      8   42.0  1.911578  0.083575
    C(Temp, Helmert)                                   Wilks' lambda   0.70032      4   21.0  2.246571  0.098472
    C(Time, Helmert)                                   Wilks' lambda   0.98168      4   21.0  0.097974  0.981956
    C(Genotype, Helmert):C(Temp, Helmert)              Wilks' lambda  0.466618      8   42.0   2.43561  0.029155
    C(Genotype, Helmert):C(Time, Helmert)              Wilks' lambda  0.453839      8   42.0   2.54307  0.023473
    C(Temp, Helmert):C(Time, Helmert)                  Wilks' lambda  0.806734      4   21.0  1.257722  0.317694
    C(Genotype, Helmert):C(Temp, Helmert):C(Time, H... Wilks' lambda  0.378451      8   42.0  3.284039  0.005347
    ```
    
  10. josef-pkt commented on Mar 8, 2023

    @josef-pkt
    Member

    The source of the problem is that endogs in the last example have mean zero. (around 1e-18)

    The estimated intercept are
    array([-2.73761049e-18, 1.00830802e-17, 6.45100293e-18, 5.63785130e-18])

    So all hypothesis test computation are essentially on zeros, so there will not be nonzero eigenvalues.
    (i.e. it's mostly floating point noise, but we ignore eigenvalues below 1e-8 threshold)

    aside:
    params are the first element of the _fittedmod attribute
    params, df_resid, inv_cov, sscpr = mod._fittedmod

  11. mikrzol commented on Mar 9, 2023

    @mikrzol
    Author

    This is what I get if I change the code to skip testing the intercept:

    These results are consistent with what I get with R's MANOVA. Since you marked resolving this issue as a milestone for 0.15, I guess I'll just use rpy2 to implement what I need into the software I'm developing and switch to statsmodels once it gives me the same results. Thanks for helping me!

    Should I close the issue for now or leave it open for you?

  12. josef-pkt commented on Mar 9, 2023

    @josef-pkt
    Member

    leave it open. It will stay open as a FAQ. (After some time I won't remember what the issue between statsmodels and R is.)
    (issue #8722 is for enhancements and refactoring, not for the problem with empty matrices)

    I will fix the exception with the intercept for 0.14, but maybe just with an option to skip the intercept test. I guess we don't skip it by default.
    I don't know what we should return in case of empty test matrices in general, other than raising a more explicit exception.

  13. josef-pkt commented on Apr 5, 2023

    @josef-pkt
    Member

    for the record: my initial unit test example was

    def test_interaction():
        p_df = pd.read_csv('https://github.com/statsmodels/statsmodels/files/10897687/example.csv', index_col=0)
        formula = 'PC1 + PC2 + PC3 + PC4 ~ C(Genotype, Helmert) * C(Temp, Helmert) * C(Time, Helmert)'
        fit = MANOVA.from_formula(formula, data=p_df)
        fit.mv_test(skip_intercept_test=True).summary_frame
    

    I have it replaced with an example with random numbers.

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