Skip to content

SUMM: post-estimation support for categoricals with formulas #2687

Open

Description

@josef-pkt

patsy has added full categorical infor in design_info see #2292
http://patsy.readthedocs.org/en/latest/API-reference.html#patsy.DesignInfo.factor_infos
and term_codings

>>> rr = patsy.dmatrix('x', {'x': ' a b c d e f'.split()})

>>> rr.design_info
DesignInfo(['Intercept', 'x[T.b]', 'x[T.c]', 'x[T.d]', 'x[T.e]', 'x[T.f]'], 

factor_infos={EvalFactor('x'): FactorInfo(factor=EvalFactor('x'), type='categorical'
, state=<factor state>, categories=('a', 'b', 'c', 'd', 'e', 'f'))}, 

term_codings=OrderedDict([(Term([]), [SubtermInfo(factors=(), contrast_matrices={}, 
um_columns=1)]), (Term([EvalFactor('x')]), [SubtermInfo(factors=(EvalFactor('x'),), 
contrast_matrices={EvalFactor('x'): ContrastMatrix(array([[ 0.,  0.,  0.,  0.,  0.
],
       [ 1.,  0.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  0.,  1.,  0.],
       [ 0.,  0.,  0.,  0.,  1.]]), ['[T.b]', '[T.c]', '[T.d]', '[T.e]', '[T.f]'
])}, num_columns=5)])]))

and (dropping magic methods):

>>> dir(rr.design_info)
[ '_repr_pretty_', 'builder', 'column_name_indexes', 'column_names', 'describe', 
'design_info', 'factor_infos', 'from_array', 'linear_constraint', 'slice', 'subset', 
'term_codings', 'term_name_slices', 'term_names', 'term_slices', 'terms']

It looks like we have all information to support

  • pairwise wald/t test, and other premade contrasts (which ?)
  • margins for categorical explanatory variables and (issue ?)
  • predictive means LSMeans/predict_at LSMeans, Contrasts in SAS, Stata #2167
  • stepwise regression, and LR and score tests for categorical terms

Related: something similar for stateful transforms, and multicolumn transformation (np.vander) are not yet available.

Activity

  1. josef-pkt commented on Mar 13, 2018

    @josef-pkt
    MemberAuthor

    prototype without seat belts for pairwise comparison
    https://gist.github.com/josef-pkt/612e91be58f8c9cd2ab12c3a21c55426
    function in cell In [26], based on example in #4323

    contains three parts

    • build contrast matrix based on design_info
    • add multiple comparison correction to t_test results
    • dispatch function to call the above two parts

    current limitation:

    • minimal returns, need to return results classes
    • no error checking if formula design_info corresponds to a reference encoding case
    • missing numpy alternative where we just provide index of columns for pairwise (or other) multiple comparison, i.e. when we do not a formula (maybe similar to wald_test_terms)
    • only for main effect, no interactions, AFAICS (based on the interpretation of design info)
    def _get_pairs_labels(k_level, level_names):
        idx_pairs_all = np.triu_indices(k_level, 1)
    
    def contrast_pairs(k_params, k_level, idx_start, level_names=None):
        """create pairwise contrast for reference coding
        """
        k_level_m1 = k_level - 1
        idx_pairs = np.triu_indices(k_level_m1, 1)
    
        k = len(idx_pairs[0])
        c_pairs = np.zeros((k, k_level_m1))
        c_pairs[np.arange(k), idx_pairs[0]] = 1
        c_pairs[np.arange(k), idx_pairs[1]] = -1
        c_reference = np.eye(k_level_m1)
        c = np.concatenate((c_reference, c_pairs), axis=0)
        k_all = c.shape[0]
    
        contrasts = np.zeros((k_all, k_params))
        contrasts[:, idx_start : idx_start + k_level_m1] = c
    
        return contrasts
    
    
    def t_test_multi(result, contrasts, method='hs', ci_method=None):
        tt = result.t_test(contrasts)
        #print(tt.summary())
        res_df = tt.summary_frame()
        
        if type(method) is not list:
            method = [method]
        for meth in method:
            mt = multipletests(tt.pvalue, method=meth)
            res_df['pvalue-%s' % meth] = mt[1]
            res_df['reject-%s' % meth] = mt[0]
        return res_df
    
    
    
    def get_pairwise(result, term_name, method='hs', ignore=False):
        """get pairwise t_test
        
        Warning: This assumes reference coding without checking
        """
        
        desinfo = result.model.data.design_info
        term_idx = desinfo.term_names.index(term_name)
        term = desinfo.terms[term_idx]
        start_idx = desinfo.term_slices[term].start
        if len(term.factors) > 1 and not ignore:
            raise ValueError('interaction effects not yet supported')
        factor = term.factors[0]
        cat = desinfo.factor_infos[factor].categories
        k_level = len(cat)
        k_params = len(result.params)
        contrasts = contrast_pairs(k_params, k_level, idx_start, level_names=cat)
        res_df = t_test_multi(result, contrasts, method=method, ci_method=None)
        return res_df
        
    

    usage:
    get_pairwise(results, 'C(DETERGENT)', method=['hs', 'fdr_bh'], ignore=False)
    currently returns dataframe based on summary_frame() in t_test results

  2. josef-pkt commented on Mar 21, 2018

    @josef-pkt
    MemberAuthor

    the code in the previous comment has been generalized in #4365 and LikelihoodModelResults will get a new t_test_pairwise method.

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