Repository navigation
Conversation
| m = (np.abs(p - q) - 1) / 2 | ||
| n = (v - p - 1) / 2 | ||
|
|
||
| results = {} |
There was a problem hiding this comment.
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.
| 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] |
There was a problem hiding this comment.
our standard terminology in other models is df_resid instead of error_df
|
|
||
| def test(self, L, M=None): | ||
| """ | ||
| Testing hypothesis L * B * M = 0 |
There was a problem hiding this comment.
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.)
|
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. 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). Overall looks good |
|
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
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. |
|
@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? |
… -*-` on top of file
|
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
data handling including pandas DataFrames is the part where I'm least familiar with the details. It is done in 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: |
|
@josef-pkt the appveyor check keeps saying: Any suggestions on how to fix it? |
|
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. |
|
@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 |
|
@yl565 That needs some adjustments to be consistent with our other models. You can check some of the caveat: I don't understand yet where the
|
|
@josef-pkt, the So in the |
|
All of those are supported by the formulas through patsy for creating the design matrices, e.g.
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. |
|
a bit more background https://github.com/statsmodels/statsmodels/blob/master/statsmodels/base/model.py#L1478 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". |
|
@josef-pkt |
|
Also, how do I squash the commits? Is the following command suffice: roughly (I'm doing half of it usually in git-gui) (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.) |
|
I will go over the PR in a bit. We might want to do one more round of cleaning and cosmetics. |
|
global substitution array-like -> array_like |
josef-pkt
left a comment
There was a problem hiding this comment.
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.
|
|
||
| author: Yichuan Liu | ||
| """ | ||
| from __future__ import print_function, division |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
order of imports
import numpy as np
from scipy import stats
import pandas as pd
and then the statsmodels import from general to specific
| """ | ||
| Canonical correlation analysis using singluar value decomposition | ||
|
|
||
| For matrices x and y, find projections x_cancoef and y_cancoef such that: |
There was a problem hiding this comment.
"For matrices endog y and exog x"
to mention the official api names
| See Parameters. | ||
| exog : array | ||
| See Parameters. | ||
| design_info : patsy.DesignInfo |
| x_cancoeff: array | ||
| The canonical coefficients for exog | ||
| y_cancoeff: array | ||
| The canonical coeefficients for endog |
There was a problem hiding this comment.
cosmetic: list endog before exog to keep our general sequence
| 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 |
There was a problem hiding this comment.
I think, this should go into a References section below Attributes
| raise NotImplementedError | ||
|
|
||
|
|
||
| class MultivariateTestResults(object): |
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
Does this really work? contrast and transform have different number of columns. Does this print a new table?
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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.
|
@josef-pkt The suggested changes has been implemented. Calling ....... 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, |
There was a problem hiding this comment.
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 | ||
| ------- | ||
|
|
There was a problem hiding this comment.
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
|
The last commit looks good, I think MANOVA would be ready for squashing and merge. (e.g. one possibility: fit returns 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. |
|
The Stata function 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:
Does that sound ok? My thinking is the |
|
@josef-pkt Done! Anything else? |
|
I'm not sure about the name Correlation is usually abbreviated with 2 "r"s corr, values doesn't add information to the name. maybe rename to |
| .. [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) |
There was a problem hiding this comment.
I didn't read carefully enough before:
missing and hasconst keywords need to be forwarded to super(...).__init__
| 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) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
here also, all general __init__ keywords need to go to super
|
I didn't see anything else except for the missing keywords in all the After that, I think it's ready for squash rebase and new PR. (If necessary I can do that.) |
PR as discussed in #3274.
Tested with a SAS example and two R examples, produced the same results.
To-do:
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:
test_affine_hypothesis()
It reproduces results from the following R code: