Skip to content

Post-hoc t-test (and more general methodology question) #5741

Open

Description

@TheChymera

Is your feature request related to a problem? Please describe

A popular statistical output in psychology and biology (and I am sure many other fields which I am less familiar with) is a series of p-values for the levels of an interaction effect of one categorical and one binary variable. Generally the idea is that a treatment is applied to a wide variety of entity categories, and the researcher is interested whether statements can be made which differentiate the effect of the treatment across categories.

Describe the solution you'd like

It would be really cool to have this as a method of the model fit class.

Describe alternatives you've considered

I have hacked this together for a number of scientific articles (1,1.1,2 --- these are self-contained examples, of which at least the first should be reliably reproducible), and while the code is short, afaict efficient, and certainty not spaghetti, it is not very generalizable. If you can walk me through it, I would be happy to try and contribute it.

Additional context

I do have a broader question which might also impact how this feature could be implemented. The way I have handled post-hoc t-tests thus far, is:

  1. Establish that the interaction term is significant in a model which includes both main effects and the interaction term (value ~ binary*categorical).
  2. Set up a second model which expresses the entire binary treatment effect per-category (value ~ categorical + binary:categorical).
  3. Set up an f-contrast of the binary:categorical levels, and ascertain that the significance is the same as obtained under 1. --- I assume it always should be.
  4. Set up t-tests (with fit.t_test()) for all combinations of the binary:categorical levels.
  5. Control for multiple comparisons

This is, however, insufficient. While this tells me in how far I can make meaningful statements about whether binary[T.True]:categorical[T.A] is different than binary[T.True]:categorical[T.B], it doesn't tell me whether a significant interaction effect might actually lead to the vanishing of the main binary treatment effect for that particular categorical variable. I could include additional t-tests for the individual terms, but then the f-contrast becomes an entirely different one than that of the interaction term in the initial model.

I'm unsure how to proceed here, should the t-tests between the interaction effects be pooled together with the t-tests for the significance of each individual interaction effect? Or should they be performed separately, along with separate multiple comparison corrections?

Activity

  1. josef-pkt commented on May 18, 2019

    @josef-pkt
    Member

    I didn't try to figure out exactly what you mean.

    We have an interaction plot function based on data, and it would be very useful to have something similar as post-estimation result for models.

    The closest this that we have right now is t_test_pairwise which does all pairwise comparisons as a Wald t_test for the parameters of an estimated model.
    I uses the formula information in design_info to create the contrasts/restriction matrix for all pairwise comparisons.
    Something similar could be applied to comparing the interaction effects, between continuous and discrete, or to other similar automatically constructed contrasts.
    I don't know what information is in the design_info for this case.

    related wald_test_terms is a bit similar but just for zero/no-effect contrasts which either uses formula information or string matching on column names to identify which columns have parameters equal to zero under the Null hypothesis.

    Where do you have the code that you already have?

  2. josef-pkt commented on May 18, 2019

    @josef-pkt
    Member

    it doesn't tell me whether a significant interaction effect might actually lead to the vanishing of the main binary treatment effect for that particular categorical variable. I could include additional t-tests for the individual terms, but then the f-contrast becomes an entirely different one than that of the interaction term in the initial model.

    I'm not sure about this part.
    Sounds like you want to test the main effect under the presence of the interaction effect. There is no problems doing this as a Wald t-test, but many (R) statisticians argue against doing that.

    For example, if you include only the interaction terms like binary[T.True]:categorical[T.B] and other T.x and the binary[T.False]:categorical[T.B] minus reference term or (minus constant) but no main effect, then the joint hypothesis that all those terms that contain binary[T.True] are zero would be a test for the Null that the binary has no effect if we allow for arbitrary effect of the categorical variable.
    The joint test that all terms that contain categorical[T.x] are equal to the value of the reference category (or zero) would test that categorical has no effect allowing for arbitrary effect of the binary variable.
    If we restrict to the specific case of binary * categorical, then it should be possible to construct tests for all interesting hypothesis as Wald tests from the full model.

    (I just realized that in my quick reading for the previous comment, I assumed categorical*continuous interaction)

    Aside: I'm not a big fan of sequential testing, like type 2 Anova, because the maintained hypotheses changes for each test and it is not really clear what the underlying assumptions for the different tests are. (AFAIK, historically they were just special cases or computation shortcuts when it is possible to construct interaction effects in an orthogonal way.)

  3. TheChymera commented on May 18, 2019

    @TheChymera
    Author

    Sorry for being verbose and confusing, as usual :D

    I have compiled for you a working example even more minimal than those linked above; here it is:

    import itertools
    import numpy as np
    import pandas as pd
    import statsmodels.api as sm
    import statsmodels.formula.api as smf
    import random
    from statsmodels.stats.multitest import multipletests
    
    data = {
    	'Value'	    : [i/1000 for i in random.sample(range(1,1000), 60)],
    	'Treatment' : [True]*30+[False]*30,
    	'Type'	    : (['A']*10+['B']*10+['C']*10)*2,
    	}
    
    df = pd.DataFrame(data)
    df.loc[df['Treatment'],'Value'] = df.loc[df['Treatment'],'Value']+1
    df.loc[df['Type']=='B','Value'] = df.loc[df['Type']=='B','Value']+1
    df.loc[df['Type']=='C','Value'] = df.loc[df['Type']=='C','Value']+2
    df.loc[(df['Treatment']) & (df['Type']=='B'),'Value'] = df.loc[(df['Treatment']) & (df['Type']=='B'),'Value']+1
    df.loc[(df['Treatment']) & (df['Type']=='C'),'Value'] = df.loc[(df['Treatment']) & (df['Type']=='C'),'Value']-1
    #print(df)
    
    formula = 'Value ~ Treatment*Type'
    model = smf.ols(formula, df)
    fit = model.fit()
    summary = fit.summary()
    anova_summary = sm.stats.anova_lm(fit, typ=3)
    
    # Print output
    print(anova_summary)
    print(summary)
    
    formula = 'Value ~ Type + Treatment:Type'
    model = smf.ols(formula, df)
    fit = model.fit()
    summary_ = fit.summary()
    levels = [
    	'Treatment[T.True]:Type[A]',
    	'Treatment[T.True]:Type[B]',
    	'Treatment[T.True]:Type[C]',
    	]
    comparisons = [[a,b] for a, b in itertools.combinations(levels,2)]
    f_contrast = ['{} - {}'.format(a[0],a[1]) for a in comparisons]
    comparisons += levels
    f_contrast += levels
    f_contrast = ','.join(f_contrast)
    f = fit.f_test(f_contrast)
    
    contrasts = []
    for comparison in comparisons:
    	if isinstance(comparison, str):
    		contrast = [1 if i == comparison else 0 for i in fit.params.index.to_list()]
    		contrasts.append(contrast)
    	else:
    		contrast = [int(i in comparison) for i in levels]
    		contrast = [1 if i in comparison else 0 for i in fit.params.index.to_list()]
    		second = False
    		for ix, i in enumerate(contrast):
    			if i==1 and second:
    				break
    			elif i == 1:
    				second=True
    		contrast[ix] = -1
    		contrasts.append(contrast)
    
    t_tests = fit.t_test(np.array(contrasts))
    
    legend=''
    g, corrected_pvalues, _, _ = multipletests(t_tests.pvalue, alpha=0.05, method='fdr_bh')
    for ix, p in enumerate(corrected_pvalues):
    	legend += 'c{} = {}:\n\tBenjamini-Hochberg corrected p={}\n'.format(ix,comparisons[ix],p)
    
    print(legend)
    

    Outputting:

                       sum_sq    df           F        PR(>F)
    Intercept        2.716494   1.0   28.422548  1.961656e-06
    Treatment        4.303136   1.0   45.023505  1.218188e-08
    Type            21.686404   2.0  113.451891  4.608681e-20
    Treatment:Type  11.351309   2.0   59.384096  2.307328e-14
    Residual         5.161068  54.0         NaN           NaN
                                OLS Regression Results                            
    ==============================================================================
    Dep. Variable:                  Value   R-squared:                       0.916
    Model:                            OLS   Adj. R-squared:                  0.908
    Method:                 Least Squares   F-statistic:                     118.1
    Date:                Sat, 18 May 2019   Prob (F-statistic):           8.38e-28
    Time:                        05:45:24   Log-Likelihood:                -11.540
    No. Observations:                  60   AIC:                             35.08
    Df Residuals:                      54   BIC:                             47.65
    Df Model:                           5                                         
    Covariance Type:            nonrobust                                         
    ===============================================================================================
                                      coef    std err          t      P>|t|      [0.025      0.975]
    -----------------------------------------------------------------------------------------------
    Intercept                       0.5212      0.098      5.331      0.000       0.325       0.717
    Treatment[T.True]               0.9277      0.138      6.710      0.000       0.651       1.205
    Type[T.B]                       1.0479      0.138      7.579      0.000       0.771       1.325
    Type[T.C]                       2.0826      0.138     15.063      0.000       1.805       2.360
    Treatment[T.True]:Type[T.B]     1.0527      0.196      5.384      0.000       0.661       1.445
    Treatment[T.True]:Type[T.C]    -1.0781      0.196     -5.514      0.000      -1.470      -0.686
    ==============================================================================
    Omnibus:                       15.425   Durbin-Watson:                   2.192
    Prob(Omnibus):                  0.000   Jarque-Bera (JB):                3.591
    Skew:                          -0.015   Prob(JB):                        0.166
    Kurtosis:                       1.802   Cond. No.                         9.77
    ==============================================================================
    
    Warnings:
    [1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
    /usr/lib64/python3.6/site-packages/statsmodels/base/model.py:1532: ValueWarning: covariance of constraints does not have full rank. The number of constraints is 6, but rank is 3
      'rank is %d' % (J, J_), ValueWarning)
    c0 = ['Treatment[T.True]:Type[A]', 'Treatment[T.True]:Type[B]']:
    	Benjamini-Hochberg corrected p=1.946410921158389e-06
    c1 = ['Treatment[T.True]:Type[A]', 'Treatment[T.True]:Type[C]']:
    	Benjamini-Hochberg corrected p=1.5194993704713466e-06
    c2 = ['Treatment[T.True]:Type[B]', 'Treatment[T.True]:Type[C]']:
    	Benjamini-Hochberg corrected p=8.959216182955645e-15
    c3 = Treatment[T.True]:Type[A]:
    	Benjamini-Hochberg corrected p=2.436376659733578e-08
    c4 = Treatment[T.True]:Type[B]:
    	Benjamini-Hochberg corrected p=2.938308267442889e-19
    c5 = Treatment[T.True]:Type[C]:
    	Benjamini-Hochberg corrected p=0.2815029516082111
    

    This is the way I am currently going about the task. The idea is, looking to describe how the Treatment and the Type effects interact, that I want to be able to make comparisons between both all of the pairwise combinations of the levels and the levels as they stand compared to zero. Particularly, given how the data is set up in this case (and this is quite important to note if it happens IRL): while there is a significant Treatment main effect, it vanishes for Treatment[T.True]:Type[C].

    So:

    • would you say this is methodologically acceptable?
    • does it make sense to apply multiple comparison correction for the sum of all of these comparisons?
    • is there a way to do it in statsmodels with less boilerplate than I am currently using?
  4. josef-pkt commented on May 18, 2019

    @josef-pkt
    Member

    sorry, I didn't see that you had several links in the first message, I only got the nature article
    I will look also at those.
    For the first two points at the end: I have to think about it. I don't see anything obviously strange

    is there a way to do it in statsmodels with less boilerplate than I am currently using?

    my guess is that there is currently no much simpler, less boiler plate version, but the point would be to add (semi-)automatic support for it. That's what t_test_pairwise, and wald_test_terms, try to do.

    I'm pretty sure supporting this directly in statsmodels would be useful, we should support more commonly used "special" cases.

  5. josef-pkt commented on May 19, 2019

    @josef-pkt
    Member

    aside:
    The restrictions for the t- or f-test can be defined as strings if you have the param names, e.g.

    restrictions = [" = ".join(i) if isinstance(i, list) else i for i in comparisons]
    fit.t_test(restrictions)
    
    >>> restrictions
    ['Treatment[T.True]:Type[A] = Treatment[T.True]:Type[B]', 
    'Treatment[T.True]:Type[A] = Treatment[T.True]:Type[C]', 
    'Treatment[T.True]:Type[B] = Treatment[T.True]:Type[C]', 
    'Treatment[T.True]:Type[A]', 'Treatment[T.True]:Type[B]', 'Treatment[T.True]:Type[C]']
    

    This uses patsy to convert string null hypothesis into the contrast/restriction matrix

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions