Skip to content

[MRG] Add MANOVA class - #3291

Closed
yl565 wants to merge 53 commits into
statsmodels:masterfrom
yl565:manova
Closed

yl565 wants to merge 53 commits into
statsmodels:masterfrom
yl565:manova

Conversation

@yl565

@yl565 yl565 commented Nov 24, 2016 •

Copy link
Copy Markdown
Contributor

PR as discussed in #3274.
Tested with a SAS example and two R examples, produced the same results.

To-do:

  • Core stats computation
  • api
  • automatic create dummy variable and hypothesis testing for categorical type independent variables.
  • Input validation
  • More examples to be tested

references:
[1] https://support.sas.com/documentation/cdl/en/statug/63033/HTML/default/viewer.htm#statug_introreg_sect012.htm)
[2] GLM Algorithms ftp://public.dhe.ibm.com/software/analytics/spss/documentation/statistics/20.0/en/client/Manuals/IBM_SPSS_Statistics_Algorithms.pdf
[3] http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.278.6976&rep=rep1&type=pdf

Unit test in test_MultivariateOLS.py

compare_r_output_dogs_data()

It reproduces results from the following R code:

library(car)
Drug = c('Morphine', 'Morphine', 'Morphine', 'Morphine', 'Morphine', 'placebo', 'placebo', 'placebo', 'placebo', 'placebo', 'Trimethaphan', 'Trimethaphan', 'Trimethaphan', 'Trimethaphan', 'Trimethaphan')
Depleted = c('N', 'N', 'N', 'N', 'Y', 'Y', 'Y', 'N', 'N', 'N', 'N', 'Y', 'Y', 'Y', 'Y')
subject  = c(1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
Histamine0 = c(-3.218876, -3.912023, -2.65926, -1.771957, -2.302585, -2.65926, -2.995732, -3.506558, -3.506558, -2.65926, -2.407946, -2.302585, -2.525729, -2.040221, -2.813411)
Histamine1 = c(-1.609438, -2.813411, 0.336472, -0.562119, -2.407946, -2.65926, -2.65926, -0.478036, 0.04879, -0.18633, 1.141033, -2.407946, -2.407946, -2.302585, -2.995732)
Histamine3 = c(-2.302585, -3.912023, -0.733969, -1.049822, -2.040221, -2.813411, -2.813411, -1.171183, -0.314711, 0.067659, 0.722706, -2.407946, -2.407946, -2.120264, -2.995732)
Histamine5 = c(-2.525729, -3.912023, -1.427116, -1.427116, -1.966113, -2.65926, -2.65926, -1.514128, -0.510826, -0.223144, 0.207014, -2.525729, -2.302585, -2.120264, -2.995732)
data = data.frame(Histamine0, Histamine1, Histamine3, Histamine5)
hismat = as.matrix(data[,1:4])
result = lm(hismat ~ Drug * Depleted)
linearHypothesis(result, c(1, 0, 0, 0, 0, 0)) 
linearHypothesis(result, t(cbind(c(0, 1, 0, 0, 0, 0), c(0, 0, 1, 0, 0, 0))))
linearHypothesis(result, c(0, 0, 0, 1, 0, 0)) 
linearHypothesis(result, t(cbind(c(0, 0, 0, 0, 1, 0), c(0, 0, 0, 0, 0, 1))))
# Or ManRes <- Manova(result, type="III")

test_affine_hypothesis()

It reproduces results from the following R code:

result = lm(hismat ~ Drug*Depleted)
fml = t(cbind(c(0, 1.1, 1.2, 1.3, 1.4, 1.5), c(0, 2.1, 3.2, 3.3, 4.4, 5.5)))
linearHypothesis(result, fml, t(cbind(c(1, 2, 3, 4), c(5, 6, 7, 8))), verbose=TRUE)

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.01%) to 87.982% when pulling 10a039b on yl565:manova into e90b71e on statsmodels:master.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.01%) to 87.982% when pulling 10a039b on yl565:manova into e90b71e on statsmodels:master.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.01%) to 87.985% when pulling 2c198fc on yl565:manova into e90b71e on statsmodels:master.

Comment thread statsmodels/multivariate/manova.py Outdated
m = (np.abs(p - q) - 1) / 2
n = (v - p - 1) / 2

results = {}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

using a dict will cause arbitrary order of the rows, doesn't it?
I think we need it deterministic both for consistency and for unit testing.

Comment thread statsmodels/multivariate/manova.py Outdated
X = np.concatenate([np.ones([n_sample, 1]), X], axis=1)

# Calculate the matrices necessary for hypothesis testing
self.error_df_ = X.shape[0] - X.shape[1]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

our standard terminology in other models is df_resid instead of error_df

Comment thread statsmodels/multivariate/manova.py Outdated

def test(self, L, M=None):
"""
Testing hypothesis L * B * M = 0

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

L and M are not informative names, I have see many different letters used for this in various articles.
They can be used internally as shorthand notation in the formulas, but it would be good to have better names in the signature. (I have currently no suggestion.)

@josef-pkt

Copy link
Copy Markdown
Member

some preliminary design comments

The main class should not keep any attributes that depend on options that can be changed, i.e. results that depend on the restriction matrices L and M. It is better to use a Results class for those cases, e.g. the model fit return an instance of a results class and result.t_test returns a ContrastResults instance.
I'm not sure where the split might be to avoid overkill and to much indirection.

The test method looks useful for a wider range of application and it would be good to have it reusable, either as separate private function or possibly as a method to a class from which we can inherit it. A separate function might be simpler for implementation.

After the basic methods are finished, I think we can delegate most data and formula handling to existing functions (or follow the same pattern for the special case here of 2 arbitrary design matrices).
I think this would also allow users to specify L and M by strings as currently available in t_test and wald_test.

Overall looks good
Thanks for the contribution

@josef-pkt

Copy link
Copy Markdown
Member

as background to some possible extensions and code reusability

I have some vague ideas how we can reuse the work you do on the MANOVA tests so it applies to more models

  • outleir robust MANOVA: I have been reading up on outlier robust multivariate methods recently. AFAIK, standard MANOVA is relatively robust to small deviations from normal distributions but not to heavy tailed distributions or outliers. One way to get around this would be to replace the core calculation for the multivariate regression and the residual covariance by robust estimators. Everything else could remain as you will have it with maybe smaller changes/additions.

  • a test_manova method for other multivariate models: I think the same pattern for tests with L and M restriction matrices could be added to other models that have a multivariate endog.

The main purpose of a PR like this is to provide the specific functionality, but if we can keep code reusability in mind in the design, then it would reduce future code duplication and refactoring.

@yl565

yl565 commented Nov 24, 2016

Copy link
Copy Markdown
Contributor Author

@josef-pkt Thanks for your comments. I would love to improve the reusability of my code. I'm trying to implement dummy variable coding and possibly support specify L and M by strings as you mentioned. Any tips on which existing methods I can use?

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.02%) to 87.987% when pulling d5d618f on yl565:manova into e90b71e on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member

most of the categorical coding will be available through patsy. You need to add mainly what is specific to MANOVA and the delation to the data handling and patsy.

without checking the details:

We have from_formula as basic model method in statsmodels.base.model.Model.from_formula. You need two design matrices. Maybe the from_formula method of MixedLM can be used as recipe.
from_formula then delegates to patsy to create the design matrices including categorical encoding.

statsmodels.base.model.LikelihoodModelResults.t_test and .wald_test use the variable names and patsy to create the linear restriction matrix, with
LC = DesignInfo(names).linear_constraint(r_matrix)
Note, in general we allow for affine constraints R beta = q, you only need the linear constraint part LC.coeffs, but you need it twice, separately for L and M.

data handling including pandas DataFrames is the part where I'm least familiar with the details. It is done in statsmodels.base.model.Model.__init__, in something like self.data = self._handle_data....
Usually we just inherit from it and it works, in some cases we need to specifically handle extra arrays.
It should work with multivariate endog. but I'm not sure everything is wired up correctly. This will be the first model where we have really different endog columns.
You can try to call super __init__ at the beginning of your MANOVA.__init__ and see if you get the correct endog and exog with associated names if both are pandas DataFrames.

Usually we or I need to browse around in existing code to see whether inheritance works or to look for "recipes", existing solutions, that can be adjusted for the specific case.

And once we have enough information about specific cases, we can try to incorporate it into the generic code, so it will be easier in future for implementing similar models. For example, here we might want to put all the specific code into a Multivariate base class if there is enough common structure to make this useful.

A comment on workflow:
Feature creep in a PR can sometimes become dangerous in terms of finishing up, review and merging. (I'm very prone to this.) It sometimes better to merge at a good point and add additional bells and whistles (like full formula support) in a follow-up PR. The main problem is when there are problems showing up in these extensions that are holding up a merge because it is not clear how the problems can be resolved, but they are not necessary for the basic functionality.
(Reviewing, unit testing and finishing up the last 10% of a PR is still quite a lot of work when the PR has several thousand lines of code.)

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.01%) to 87.986% when pulling 7a34d1c on yl565:manova into e90b71e on statsmodels:master.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.01%) to 87.987% when pulling cebe428 on yl565:manova into e90b71e on statsmodels:master.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.01%) to 87.987% when pulling cebe428 on yl565:manova into e90b71e on statsmodels:master.

@yl565

yl565 commented Nov 24, 2016

Copy link
Copy Markdown
Contributor Author

@josef-pkt the appveyor check keeps saying:

======================================================================
ERROR: statsmodels.tools.tests.test_grouputils.TestIndexGrouping.test_transform_slices
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Py\lib\site-packages\nose\case.py", line 198, in runTest
    self.test(*self.arg)
  File "C:\projects\statsmodels\statsmodels\tools\tests\test_grouputils.py", line 108, in test_transform_slices
    level=0)
  File "C:\projects\statsmodels\statsmodels\tools\grouputils.py", line 489, in transform_slices
    self.get_slices(level=level)
  File "C:\projects\statsmodels\statsmodels\tools\grouputils.py", line 406, in get_slices
    groups.sort()
  File "C:\Py\lib\site-packages\pandas\indexes\base.py", line 1733, in sort
    raise TypeError("cannot sort an Index object in-place, use "
TypeError: cannot sort an Index object in-place, use sort_values instead

Any suggestions on how to fix it?

@josef-pkt

Copy link
Copy Markdown
Member

It's unrelated to this PR, and is waiting for someone to hit the merge button on a PR.

A test that fails only on the oldest version on TravisCI can also be ignored, we still need to increase the minimum version on Travis for master and future releases.

@yl565

yl565 commented Nov 24, 2016

Copy link
Copy Markdown
Contributor Author

@josef-pkt Here is the api of the main MANOVA class I'm thinking about. What's your opinion?

class MANOVA(object):
    """
    Multivariate analysis of variance

    option 1: specify `X` and `formula`
        The effect of each term on right hand side of `formula` will be tested.

    option 2: specify 'X', `Y`, `effect`
        For variables in X, automatically include in the model the main effect 
        and/or interaction terms as specified in `effect` and testing them.

    Parameters
    ----------
    X : array-like (n_sample by m_x_vars) or DataFrame
        Independent variables (IV). Variables in columns, observations in rows.
        For DataFrame, string columns will be treated as categorical variables.

    Y : array-like (n_sample by m_y_vars)
        Dependent variables (DV). Variables in columns, observations in rows.

    formula : string, default to None
        Model formula.

    effect : tuple, default to (0, 1) (only main effects and intercept)
        Specifies which terms will be included in the model automatically.
        Values:
        0 - intercept
        1 - main effects
        2 - two-way interactions
        3 - three-way interactions
        etc.
     """
    def __init__(self, X, Y=None, formula=None, effect=(0, 1)):
        if formula is None:
            if not effect:
                raise ValueError('No term included. Model is null!')
            X, Y, H, intercept = self.from_XY(X, Y, effect)
        else:
            X, Y, H, intercept = self.from_formula(X, formula)

        n_sample, m_x_vars = X.shape
        n_sample1, m_y_vars = Y.shape
        self.n_sample_ = n_sample
        self.m_x_vars_ = m_x_vars
        self.m_y_vars_ = m_y_vars
        out = fit_manova(X, Y, intercept)
        self.reg_coeffs, self.df_resid, self.inv_cov_, self.YYBXXB_ = out
        self.stats = self.test(H)

    def from_XY(self, X, Y, effect):
        raise NotImplementedError

    def from_formula(self, X, formula):
        raise NotImplementedError

    def test(self, H):
        """
        Testing the genernal hypothesis L * B * M = 0
        for each tuple (name, L, M) in H

@josef-pkt

Copy link
Copy Markdown
Member

@yl565 That needs some adjustments to be consistent with our other models. You can check some of the model.__init__ signatures.

caveat: I don't understand yet where the effect comes in. I'm not so familiar with MANOVA and I'm thinking mostly in terms of multivariate linear regression.

  • instead of model(x, y) our minimal signature is model(endog, exog) where endog=y and exog=x.
    endog is always required, exog can be None in some models. and sequence is opposite of scikit-learn.

  • we decided to keep the array/dataframe interface and the formula interface separate. We had the discussion of merging them as in your example, but decided that it's not worth the complication. If you look into statsmodels.formula.api you see lowercase model names with are just the from_formula methods of the models, as a shortcut for users. i.e. manova = MANOVA.from_formula. So users can do manova(y, x, ...) So, base on your structure in the example, IIUC, MANOVA__init__` would correspond exclusively to your from_XY

@yl565

yl565 commented Nov 25, 2016

Copy link
Copy Markdown
Contributor Author

@josef-pkt, the effect input is for conveniently automatic generating model terms. Each value in it specify a level of term to be included in the model to be fitted:
Values:
0 - intercept
1 - main effects: x1, x2, etc.
2 - two-way interactions: x1 * x2, x1 * x3, etc.
3 - three-way interactions: x1 * x2 * x3, x1 * x2 * x4, etc.
Examples: For X=[x1, x2, x3], Y=[y1, y2, y3]
effect = (0), y1 y2 y3 ~ 1
effect = (1), y1 y2 y3 ~ x1 + x2 + x3
effect = (0, 1), y1 y2 y3 ~ 1 + x1 + x2 + x3
effect = (2), y1 y2 y3 ~ x1 * x2 + x1 * x3 + x2 * x3
effect = (0, 1, 2), y1 y2 y3 ~ 1 + x1 + x2 + x3 + x1 * x2 + x1 * x3 + x2 * x3
effect = (3), y1 y2 y3 ~ x1 * x2 * x3

So in the MANOVA.__init__ i'm planning. endog_new, exog_new will be generated from endog, exog and effect for fitting and testing a model

@josef-pkt

Copy link
Copy Markdown
Member

All of those are supported by the formulas through patsy for creating the design matrices, e.g.

...from_formula("y1 + y2 + y3 ~ x1 * x2 + x1 * x3 + x2 * x3", dataframe, ...)

What we haven't used yet is if we need additional information or we want to force users to provide a specific encoding, i.e. if we need information that the design_info doesn't provide or we want to restrict which type of formulas are allowed for additional statistical processing.

example: the multivariate regression analog would be fully supported through formulas and the resulting design matrices.
If you need something special for one-way or two-way MANOVA, then we would need something extra, but not if we can just get those as special cases from the general formula setup.
e.g. along these lines
http://statsmodels.sourceforge.net/devel/example_formulas.html

@josef-pkt

Copy link
Copy Markdown
Member

a bit more background

https://github.com/statsmodels/statsmodels/blob/master/statsmodels/base/model.py#L1478
which was based on https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/anova.py#L271
Both make tests (in the univariate case) for terms that can span multiple column like interaction terms or categorical variables. However, it is mechanical and the null hypothesis is that the parameters corresponding to those columns are zero. Those methods don't know what it means, i.e. whether something is an interaction or main effect or something arbitrary, and if it's for a categorical variable it doesn't know anything about what effect coding was used.

The latest version of patsy provides more information about categorical encoding, but we haven't made any of these methods smarter.

So executing hypothesis tests either "mechanically" or completely based on a user provided restriction matrices is relatively straightforward. But we don't have an example yet, where we create a smart restriction matrix based on a user defined formula. (There are open issues for these extensions.)

So, depending on what features you want to implement, it's possible to stick just with the formula handling for all categoricals, or alternatively to provide the additional support for the MANOVA usage of "effects".

@yl565

yl565 commented Dec 18, 2016

Copy link
Copy Markdown
Contributor Author

@josef-pkt hypotheses in mv_test now can accept a tuple of length 2: (name, L). Please let me know if there is any other changes you want me to make. Also, how do I squash the commits? Is the following command suffice:
git checkout -b squashed_manova
git rebase -i master

@josef-pkt

Copy link
Copy Markdown
Member

Also, how do I squash the commits? Is the following command suffice:
git checkout -b squashed_manova
git rebase -i master

roughly (I'm doing half of it usually in git-gui)
Make sure that you are on the correct new branch before rebase.
Also, I prefer qualifiers in name as postfix, so the alphabetical sorting is more informative, i.e. manova_squashed or manova_rebased
I usually fetch remote and rebase on remote master, because my local master is usually not up-to-date
git rebase -i remotes\origin\master
(my origin points to statsmodels remote)
and then edit the interactive rebase text file

(I like git-gui because it automatically gives me more information that I can check to make sure that I'm not in the wrong branch, wrong commits, wrong remote, ..., and I don't have to memorize as many commands and options.)

@josef-pkt

Copy link
Copy Markdown
Member

I will go over the PR in a bit. We might want to do one more round of cleaning and cosmetics.

@josef-pkt

Copy link
Copy Markdown
Member

@josef-pkt josef-pkt left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I stop here.
A few mostly minor changes.

I went over MANOVA which looks pretty good. I only spot checked multivariate_ols, and it will be easier to do any refactoring there when it will get the missing parts.

Comment thread statsmodels/multivariate/cancorr.py Outdated

author: Yichuan Liu
"""
from __future__ import print_function, division

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

imported print_function is never used
(no prints in code)

applies to all modules

from scipy import stats
import pandas as pd
from statsmodels.iolib import summary2
from .multivariate_ols import multivariate_stats

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

order of imports

import numpy as np
from scipy import stats
import pandas as pd

and then the statsmodels import from general to specific

Comment thread statsmodels/multivariate/cancorr.py Outdated
"""
Canonical correlation analysis using singluar value decomposition

For matrices x and y, find projections x_cancoef and y_cancoef such that:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"For matrices endog y and exog x"
to mention the official api names

Comment thread statsmodels/multivariate/cancorr.py Outdated
See Parameters.
exog : array
See Parameters.
design_info : patsy.DesignInfo

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

obsolete not used anymore

x_cancoeff: array
The canonical coefficients for exog
y_cancoeff: array
The canonical coeefficients for endog

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cosmetic: list endog before exog to keep our general sequence

Comment thread statsmodels/multivariate/manova.py Outdated
by the user (models specified using a formula include an intercept by
default)

.. [1] ftp://public.dhe.ibm.com/software/analytics/spss/documentation/statistics/20.0/en/client/Manuals/IBM_SPSS_Statistics_Algorithms.pdf

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think, this should go into a References section below Attributes

raise NotImplementedError


class MultivariateTestResults(object):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

needs a docstring, so users can check the explanation for the results.

df.index.set_names(['Effect', 'Statistic'], inplace=True)
return df

def summary(self, contrast_L=False, transform_M=False):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the names of the keywords are confusing, maybe prefix with "show"
show_contrast_L=False, show_transform_M=False

My first impression when reading this was that I need to provide the L and M matrices.

summ.add_dict({key:' contrast L='})
df = pd.DataFrame(self.results[key]['contrast_L'],
columns=self.exog_names)
summ.add_df(df)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this really work? contrast and transform have different number of columns. Does this print a new table?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need smoke test for the summary methods. i.e. just call them in an example which just checks that we don't get an exception.

k_xvar = len(exog_names)
k_yvar = len(endog_names)
results = {}
for i in hypotheses:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in general I try to avoid one letter names if it goes over several lines, e.g.
for hypo in hypotheses
hypo is still short but more informative and doesn't sound too close, hypothesis and hypotheses, otherwise I often use singular/plural names.

@yl565

yl565 commented Dec 19, 2016

Copy link
Copy Markdown
Contributor Author

@josef-pkt The suggested changes has been implemented. Calling print(MultivariateTestResults.summary(show_contrast_L=True, show_transform_M=True, show_constant_C=True)) will show the following:

.......                                                   Multivariate linear model
===============================================================================================================================
                                                                                                                               
--------------------------------------------------------------------------------------------------------------------------------------------
                       test1                        Value               Num DF               Den DF              F Value              Pr > F
--------------------------------------------------------------------------------------------------------------------------------------------
                      Wilks’ lambda               0.0269              8.0000              12.0000               7.6441              0.0010
                     Pillai’s trace               1.4277              8.0000              14.0000               4.3657              0.0080
               Hotelling-Lawley trace              19.2678              8.0000               6.6316              13.7940              0.0016
                Roy’s greatest root              18.3470              4.0000               7.0000              32.1072              0.0001
-------------------------------------------------------------------------------------------------------------------------------
test1                                     contrast L=                                                                          
-------------------------------------------------------------------------------------------------------------------------------
  Intercept Drug[T.Trimethaphan] Drug[T.placebo] Depleted[T.Y] Drug[T.Trimethaphan]:Depleted[T.Y] Drug[T.placebo]:Depleted[T.Y]
-------------------------------------------------------------------------------------------------------------------------------
0    0.0000               1.2000          1.1000        1.3000                             1.5000                        1.4000
1    0.0000               3.2000          2.1000        3.3000                             5.5000                        4.4000
-------------------------------------------------------------------------------------------------------------------------------
test1                                      transform M=                                                                        
------------------------------------------------------------------------------------------------------------------------------------------------------------
                                            0                                   1                                   2                                   3   
------------------------------------------------------------------------------------------------------------------------------------------------------------
Histamine0                                1.0000                              0.0000                              0.0000                              0.0000
Histamine1                                0.0000                              1.0000                              0.0000                              0.0000
Histamine3                                0.0000                              0.0000                              1.0000                              0.0000
Histamine5                                0.0000                              0.0000                              0.0000                              1.0000
-------------------------------------------------------------------------------------------------------------------------------
test1                                     constant C=                                                                          
---------------------------------------------------------------------------------------------------------------------------------------------------------------
                                      0                                      1                                      2                                      3   
---------------------------------------------------------------------------------------------------------------------------------------------------------------
0                                   1.0000                                 2.0000                                 3.0000                                 4.0000
1                                   5.0000                                 6.0000                                 7.0000                                 8.0000
===============================================================================================================================

[19.2678, 8.0000, 6.6316, 13.7940, 0.0016],
[18.3470, 4.0000, 7.0000, 32.1072, 0.0001]]
assert_array_almost_equal(r0['test1']['stat'].values, a, decimal=4)
print(r0.summary(show_contrast_L=True, show_transform_M=True,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove the print, It's noise in the test output and we don't do visual inspection of test results.
The r0.summary(,,,) will cause a test error if it raises an exception.
We have almost no unit tests for the content of summary because it is difficult to test.


Returns
-------

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't realize that this doesn't have a return.

I think this needs to return something instead of attaching all the results.

maybe not, CanCorrResults itself looks like a TestResults instance

@josef-pkt

Copy link
Copy Markdown
Member

The last commit looks good, I think MANOVA would be ready for squashing and merge.
However, I'm not sure about the structure of CanCorr. The code itself is good, but maybe it needs to be wired together in a different way.

(e.g. one possibility: fit returns self or fit is called automatically in __init__, and the F-test moves as method to CanCorr class and returns a CanCorrTestResults instance or something like that)
The name for the F-test might need a qualifier like independence, or maybe it will need some arguments, e.g. if we want to test a different hypothesis. On the other hand, those can be added later without backwards compatibility problems with the current hypothesis as default.

I'm not familiar with use cases for CanCorr except as foundation for several hypothesis tests.

I will look at cancorr again, and check what's available for it in Stata.

@josef-pkt

Copy link
Copy Markdown
Member

The Stata function canon provides immediately the test for the correlation, it looks analogous to your f_test. However, I ran into canonical correlation in two different contexts that don't test the same hypothesis. So, I still want to keep it more flexible.

AFAICS, cancorr.fit doesn't have much computation that would be redundant. (It's also possible to move something into lazily evaluated cached properties if necessary in future.)

So my suggestion for CanCorr:

  • rename fit _> _fit and call it in __init__, no return just attach to self (which is already done)
  • move f_test to Cancorr, maybe rename to corr_test for correlation test. (?)
  • rename CanCorrResults -> CanCorrTestResults, returned by f_test/corr_test, needs only minor adjustments. It could hold on to the CanCorr model instance if that is needed for some attributes.

Does that sound ok?

My thinking is the CanCorr.__init__ computes and attaches the basic results, and we extend it with additional methods as needed in future.

@yl565

yl565 commented Dec 19, 2016

Copy link
Copy Markdown
Contributor Author

@josef-pkt Done! Anything else?

@josef-pkt

Copy link
Copy Markdown
Member

I'm not sure about the name cor_values

Correlation is usually abbreviated with 2 "r"s corr, values doesn't add information to the name.
Are these the canonical correlations?

maybe rename to cancorr ? might be more informative than corr or correlation
(Stata has ccorr but I don't like their habit of abbreviating the first part of names to one letter, it makes for some silly names sometimes.)

Comment thread statsmodels/multivariate/cancorr.py Outdated
.. [3] http://www.mathematica-journal.com/2014/06/canonical-correlation-analysis/
"""
def __init__(self, endog, exog, tolerance=1e-8, missing='none', hasconst=None, **kwargs):
super(CanCorr, self).__init__(endog, exog, **kwargs)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't read carefully enough before:
missing and hasconst keywords need to be forwarded to super(...).__init__

Comment thread statsmodels/multivariate/manova.py Outdated
if len(endog.shape) == 1 or endog.shape[1] == 1:
raise ValueError('There must be more than one dependent variable'
' to fit MANOVA!')
super(MANOVA, self).__init__(endog, exog, **kwargs)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same problem here, missing and hasconst keywords need to be in the super call

if len(endog.shape) == 1 or endog.shape[1] == 1:
raise ValueError('There must be more than one dependent variable'
' to fit multivariate OLS!')
super(_MultivariateOLS, self).__init__(endog, exog, **kwargs)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

here also, all general __init__ keywords need to go to super

@josef-pkt

Copy link
Copy Markdown
Member

I didn't see anything else except for the missing keywords in all the __init__ super calls.

After that, I think it's ready for squash rebase and new PR. (If necessary I can do that.)

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.05%) to 88.026% when pulling 29373b6 on yl565:manova into e90b71e on statsmodels:master.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants