Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 67 additions & 1 deletion statsmodels/base/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
from statsmodels.base.data import handle_data
from statsmodels.tools.data import _is_using_pandas
from statsmodels.tools.tools import recipr, nan_dot
from statsmodels.stats.contrast import ContrastResults, WaldTestResults
from statsmodels.stats.contrast import (ContrastResults, WaldTestResults,
t_test_pairwise)
from statsmodels.tools.decorators import resettable_cache, cache_readonly
import statsmodels.base.wrapper as wrap
from statsmodels.tools.numdiff import approx_fprime
Expand Down Expand Up @@ -1645,6 +1646,71 @@ def wald_test_terms(self, skip_single=False, extra_constraints=None,
res.temp = constraints + combined_constraints + extra_constraints
return res

def t_test_pairwise(self, term_name, method='hs', alpha=0.05,
factor_labels=None):
"""perform pairwise t_test with multiple testing corrected p-values

This uses the formula design_info encoding contrast matrix and should
work for all encodings of a main effect.

Parameters
----------
result : result instance
The results of an estimated model with a categorical main effect.
term_name : str
name of the term for which pairwise comparisons are computed.
Term names for categorical effects are created by patsy and
correspond to the main part of the exog names.
method : str or list of strings
multiple testing p-value correction, default is 'hs',
see stats.multipletesting
alpha : float
significance level for multiple testing reject decision.
factor_labels : None, list of str
Labels for the factor levels used for pairwise labels. If not
provided, then the labels from the formula design_info are used.

Returns
-------
results : instance of a simple Results class
The results are stored as attributes, the main attributes are the
following two. Other attributes are added for debugging purposes
or as background information.

- result_frame : pandas DataFrame with t_test results and multiple
testing corrected p-values.
- contrasts : matrix of constraints of the null hypothesis in the
t_test.

Notes
-----

Status: experimental. Currently only checked for treatment coding with
and without specified reference level.

Currently there are no multiple testing corrected confidence intervals
available.

Examples
--------
>>> res = ols("np.log(Days+1) ~ C(Weight) + C(Duration)", data).fit()
>>> pw = res.t_test_pairwise("C(Weight)")
>>> pw.result_frame
coef std err t P>|t| Conf. Int. Low \
2-1 0.632315 0.230003 2.749157 8.028083e-03 0.171563
3-1 1.302555 0.230003 5.663201 5.331513e-07 0.841803
3-2 0.670240 0.230003 2.914044 5.119126e-03 0.209488

Conf. Int. Upp. pvalue-hs reject-hs
2-1 1.093067 0.010212 True
3-1 1.763307 0.000002 True
3-2 1.130992 0.010212 True

"""
res = t_test_pairwise(self, term_name, method=method, alpha=alpha,
factor_labels=factor_labels)
return res

def conf_int(self, alpha=.05, cols=None, method='default'):
"""
Returns the confidence interval of the fitted parameters.
Expand Down
124 changes: 124 additions & 0 deletions statsmodels/base/tests/test_generic_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -518,5 +518,129 @@ def initialize(cls):
cls.res = mod.fit() # default use_t=True


class CheckPairwise(object):

def test_default(self):
res = self.res

tt = res.t_test(self.constraints)

pw = res.t_test_pairwise(self.term_name)
pw_frame = pw.result_frame
assert_allclose(pw_frame.iloc[:, :6].values,
tt.summary_frame().values)


class TestTTestPairwiseOLS(CheckPairwise):

@classmethod
def setup_class(cls):
from statsmodels.formula.api import ols
import statsmodels.stats.tests.test_anova as ttmod

test = ttmod.TestAnova3()
test.setup_class()
cls.data = test.data.drop([0,1,2])

mod = ols("np.log(Days+1) ~ C(Duration) + C(Weight)", cls.data)
cls.res = mod.fit()
cls.term_name = "C(Weight)"
cls.constraints = ['C(Weight)[T.2]',
'C(Weight)[T.3]',
'C(Weight)[T.3] - C(Weight)[T.2]']


def test_alpha(self):
pw1 = self.res.t_test_pairwise(self.term_name, method='hommel',
factor_labels='A B C'.split())
pw2 = self.res.t_test_pairwise(self.term_name, method='hommel',
alpha=0.01)
assert_allclose(pw1.result_frame.iloc[:, :7].values,
pw2.result_frame.iloc[:, :7].values, rtol=1e-10)
assert_equal(pw1.result_frame.iloc[:, -1].values,
[True]*3)
assert_equal(pw2.result_frame.iloc[:, -1].values,
[False, True, False])

assert_equal(pw1.result_frame.index.values,
np.array(['B-A', 'C-A', 'C-B'], dtype=object))


class TestTTestPairwiseOLS2(CheckPairwise):

@classmethod
def setup_class(cls):
from statsmodels.formula.api import ols
import statsmodels.stats.tests.test_anova as ttmod

test = ttmod.TestAnova3()
test.setup_class()
cls.data = test.data.drop([0,1,2])

mod = ols("np.log(Days+1) ~ C(Weight) + C(Duration)", cls.data)
cls.res = mod.fit()
cls.term_name = "C(Weight)"
cls.constraints = ['C(Weight)[T.2]',
'C(Weight)[T.3]',
'C(Weight)[T.3] - C(Weight)[T.2]']


class TestTTestPairwiseOLS3(CheckPairwise):

@classmethod
def setup_class(cls):
from statsmodels.formula.api import ols
import statsmodels.stats.tests.test_anova as ttmod

test = ttmod.TestAnova3()
test.setup_class()
cls.data = test.data.drop([0,1,2])

mod = ols("np.log(Days+1) ~ C(Weight) + C(Duration) - 1", cls.data)
cls.res = mod.fit()
cls.term_name = "C(Weight)"
cls.constraints = ['C(Weight)[2] - C(Weight)[1]',
'C(Weight)[3] - C(Weight)[1]',
'C(Weight)[3] - C(Weight)[2]']

class TestTTestPairwiseOLS4(CheckPairwise):

@classmethod
def setup_class(cls):
from statsmodels.formula.api import ols
import statsmodels.stats.tests.test_anova as ttmod

test = ttmod.TestAnova3()
test.setup_class()
cls.data = test.data.drop([0,1,2])

mod = ols("np.log(Days+1) ~ C(Weight, Treatment(2)) + C(Duration)", cls.data)
cls.res = mod.fit()
cls.term_name = "C(Weight, Treatment(2))"
cls.constraints = ['-C(Weight, Treatment(2))[T.1]',
'C(Weight, Treatment(2))[T.3] - C(Weight, Treatment(2))[T.1]',
'C(Weight, Treatment(2))[T.3]',]


class TestTTestPairwisePoisson(CheckPairwise):

@classmethod
def setup_class(cls):
from statsmodels.discrete.discrete_model import Poisson
import statsmodels.stats.tests.test_anova as ttmod

test = ttmod.TestAnova3()
test.setup_class()
cls.data = test.data.drop([0,1,2])

mod = Poisson.from_formula("Days ~ C(Duration) + C(Weight)", cls.data)
cls.res = mod.fit(cov_type='HC0')
cls.term_name = "C(Weight)"
cls.constraints = ['C(Weight)[T.2]',
'C(Weight)[T.3]',
'C(Weight)[T.3] - C(Weight)[T.2]']



if __name__ == '__main__':
pass
Loading