Skip to content

BUG/ENH (sandbox) OnewayLS pairwise comparison - effective degrees of freedom #9777

Open

Description

@josef-pkt

I'm looking by chance at sandbox again.

OnewayLS uses total degrees of freedom for pairwise comparison. I guess it should only use the df based on the nobs of the two samples.

====================================================================================
           pair                F-statistic            p-value        df_denom df_num
------------------------------------------------------------------------------------
                     'all'    4.068492123101886 0.007840175583181543    196.0    3.0
(np.int64(0), np.int64(1)) 0.036927253253968687    0.847812182552415    196.0    1.0
(np.int64(0), np.int64(2))    6.968196182952771 0.008964955351128031    196.0    1.0
(np.int64(0), np.int64(3))    4.096066942378929 0.044340633151241954    196.0    1.0
(np.int64(1), np.int64(2))    8.019650607200656 0.005110355405498676    196.0    1.0
(np.int64(1), np.int64(3))    4.910828371602135 0.027839420320478512    196.0    1.0
(np.int64(2), np.int64(3))  0.37928338122289207   0.5387015267355013    196.0    1.0
------------------------------------------------------------------------------------

The tests are Wald F-tests based on the full regression with exog interacted with group dummies.
This would be the same as when a user specifies a continuous-categorical interaction in a oneway setting.
This performs the Wald test on the full model that joins all groups.

I alternatively, we join each pair of groups in an OLS model with continuous-dummy interaction, then df would be based on only the sum of the two nobs_i.

I never managed to figure out the general theory for effective degrees of freedom given the actual design matrix.
I guess I can correct the df specifically in a OnewayLS model, but not generically for OLS and other models when using use_t=True.

AFAIR, in tukey_hsd we use pairwise sum of nobs, similarly to running separate t-tests for each pair.

aside:
Splitting up the sample into groups and testing that the groups have identical regression parameters is similar to diagnostic tests like Chow (?) and somewhat similar to Hosmer-Lemeshow test.
However, in the omnibus test for all groups having the same parameters, the relevant degrees of freedom is correctly based on the total (all groups) sample size.

The problem shows up if we test parameters for only a subset of groups as in multiple testing like pairwise comparisons.
t_test_pairwise of the results class has the same problem when pairs of parameters are based on subsets of samples. (But it will not be affected so much if we have common parameters, i.e. not all exog are interacted with sub-sample groups.)

specific issue for effective, approximate degrees of freedom: #6564
and also #8727

Activity

  1. josef-pkt commented on Apr 1, 2026

    @josef-pkt
    MemberAuthor

    There is already a way to override df_resid in the wald test
    res.lsjoint._results.df_resid_inference = 190 works, but it has to be a scalar, Vector df raises an exception during formatting results.

    df_resid_inference is an attribute that is never assigned in the results class.

    Based on a code search, the only use of df_resid_inference is to adjust df if cov_type is one of ['cluster', 'hac-panel', 'hac-groupsum'] to make df correspond to number of groups.

    For the case of adjusting df_resid (df_denom) for individual wald test, using an attribute is not clean.

    wald_test has df_constraints as keyword parameter, but not df_resid/df_denom. f_test does not have df_constraints.

  2. Whatsonyourmind commented on Apr 3, 2026

    @Whatsonyourmind

    The degrees of freedom question here has a clean theoretical answer that depends on the variance assumption.

    Case 1: Homogeneous variances (pooled estimate)
    The current behavior (df_denom=196, using the full model residual df) is statistically correct under the assumption of equal group variances. The full-model MSE pools all groups' residuals into one variance estimate, which is more efficient (more df → tighter standard errors → more power). This is the Scheffé approach.

    The tradeoff: you get a better variance estimate, but if the homogeneity assumption is violated, the pooled estimate is biased and your pairwise tests have incorrect size.

    Case 2: Heterogeneous variances (per-pair df)
    If group variances differ, each pairwise comparison should use only the two groups being compared. The appropriate df comes from Welch-Satterthwaite:

    df_ws = (s1²/n1 + s2²/n2)² / ((s1²/n1)²/(n1-1) + (s2²/n2)²/(n2-1))
    

    This gives a non-integer df that is more conservative but correct under heteroscedasticity.

    What R does: pairwise.t.test() has pool.sd=TRUE/FALSE controlling exactly this choice. When pool.sd=TRUE, it uses the pooled variance and full-model df (your current behavior). When pool.sd=FALSE, it uses per-pair Welch df.

    Suggested implementation: A df_method parameter with options "pooled" (current behavior, default for backward compatibility) and "welch" (per-pair Satterthwaite df). The vector df issue you mention with df_resid_inference would need to be resolved for the Welch case since each pair gets a different df.

    For the existing _results.df_resid_inference path, one approach: store a dict mapping pair tuples to their Welch df, and have the formatting code look up the pair-specific df when rendering pairwise results.

  3. josef-pkt commented on Apr 3, 2026

    @josef-pkt
    MemberAuthor

    @Whatsonyourmind Thanks for the comments.

    The problem here is more difficult than a two way mean comparison.

    OnewayLS is for a one-way setting with usually more than two groups for regression coefficients and not just for comparing means.

    oneway

    For one-way pairwise comparison of means we use Tukey-Kramer or Games-Howell, but I don't remember, and didn't see in a quick look at the code, what the degrees of freedom assumption is.
    https://www.statsmodels.org/dev/generated/statsmodels.stats.multicomp.pairwise_tukeyhsd.html

    In the case on OnewayLS, we compare and test equality of all regression coefficients across groups.
    Each group has model y_k = beta_k * x_k + noise, where k are the groups.
    The omnibus test is that all beta_k are the same. The pairwise test compares beta_i and beta_j for all i, j pairs.
    The pairwise test is done in the overall joint regression and not in a model that includes only the pairs. (sum(n_k) versus n_i + n_j)

    This would be independent of the variance assumption. Correcting total or pairwise df_resid for Satterthwaite's unequal variance assumption would be a separate, additional step.

    In my original simulated example, I had 5 observations with 3 regressors per group i.e. df_k=2.
    So the choice of df makes a large difference when group sizes are small and there are many groups.

    If we have only 2 groups, then sum(n_k) and n_i + n_j are the same.

  4. Whatsonyourmind commented on Apr 3, 2026

    @Whatsonyourmind

    @josef-pkt Thank you for the clarification — I oversimplified by framing this as a mean comparison. You are right that pairwise comparison of regression coefficients across multiple groups is a harder problem because the contrast structure is richer.

    For the degree-of-freedom question in OnewayLS with regression coefficients: the crux is whether to use the full-model residual df (pooling across all groups) or a contrast-specific df that accounts for potentially unequal within-group variance structures. With regression coefficients (as opposed to means), the Satterthwaite-type approximation becomes messier because each group's coefficient variance depends on both the residual variance and the design matrix ((X'X)^{-1} differs per group).

    The df_resid_inference attribute override you mentioned is a reasonable escape hatch for the scalar case. For vector df (one per pairwise contrast), would it make sense to extend wald_test to accept a per-contrast df_denom array? The signature change would be small, and it would let users plug in Satterthwaite-approximated df without monkey-patching the results object.

  5. josef-pkt commented on Apr 3, 2026

    @josef-pkt
    MemberAuthor

    after running an R example for pairwise.t.test (and a brief look at their code), I understand the comment a bit better.

    The R function makes the df depend on the variance assumption, df is based on total nobs of pool.sd is true and delegates to the pairwise t.test if variance is not pooled.

    This looks a bit inconsistent to me. The variance assumption should only affect the estimated and used standard deviation.
    We usually don't make nobs used in df_resid depend on the variance assumptions.

    So, the relevant comparison should be between

    • separate pairwise tests with df based on nobs_i and nobs_j with or without heteroscedasticity correction
    • contrast tests in joint model with df base on sum(nobs_k) with or without heteroscedasticity correction

    In the second case with unequal variance assumption we could use Satterthwaite correction for the full sample, or just heteroscedasticity robust standard errors. However, Satterthwaite correction for the full sample would spill over variances across group pairs through the df computation.

    My intuition is that we should use the pairwise nobs for df computation independently of the variance assumption, and of whether we compute all pairwise models or a single joint model.

    example from the R docstring

    I compare the original example with one after dropping the first group
    If pool.sd = FALSE, then the p-values for included pairs stay the same in the two cases.
    If we pool.sd, then small p-values increase by a large factor. This is partially based on the different variance estimates, but more strongly because of the different nobs/df assumptions, AFAICS.

    > Month <- factor(Month, labels = month.abb[5:9])
    > Month2 <- factor(Month[32:153], labels = month.abb[6:9])
    
    > pairwise.t.test(Ozone, Month, p.adjust.method="none", pool.sd = FALSE)
    
            Pairwise comparisons using t tests with non-pooled SD 
    
    data:  Ozone and Month 
    
        May     Jun     Jul     Aug    
    Jun 0.44610 -       -       -      
    Jul 2.6e-05 0.00218 -       -      
    Aug 0.00022 0.00427 0.93260 -      
    Sep 0.21580 0.79366 0.00074 0.00287
    
    P value adjustment method: none 
    
    > pairwise.t.test(Ozone[32:153], Month2, p.adjust.method="none", pool.sd = FALSE)
    
            Pairwise comparisons using t tests with non-pooled SD 
    
    data:  Ozone[32:153] and Month2 
    
        Jun     Jul     Aug    
    Jul 0.00218 -       -      
    Aug 0.00427 0.93260 -      
    Sep 0.79366 0.00074 0.00287
    
    P value adjustment method: none 
    
    > pairwise.t.test(Ozone, Month, p.adjust.method="none")
    
            Pairwise comparisons using t tests with pooled SD 
    
    data:  Ozone and Month 
    
        May     Jun     Jul     Aug    
    Jun 0.60877 -       -       -      
    Jul 2.9e-05 0.01023 -       -      
    Aug 1.9e-05 0.00831 0.91744 -      
    Sep 0.32545 0.85838 0.00070 0.00048
    
    P value adjustment method: none 
    
    > pairwise.t.test(Ozone[32:153], Month2, p.adjust.method="none")
    
            Pairwise comparisons using t tests with pooled SD 
    
    data:  Ozone[32:153] and Month2 
    
        Jun    Jul    Aug   
    Jul 0.0157 -      -     
    Aug 0.0131 0.9222 -     
    Sep 0.8664 0.0015 0.0011
    
    P value adjustment method: none 
    > 
    
  6. Whatsonyourmind commented on Apr 3, 2026

    @Whatsonyourmind

    @josef-pkt That R comparison is illuminating. I agree the variance assumption should only affect the estimated standard deviation, not the effective sample size used for df — conflating the two is conceptually inconsistent.

    Your framing of the two clean cases is the right decomposition:

    1. Separate pairwise tests with df from (n_i, n_j) — correct when groups are treated as independent sub-models, with or without Welch-Satterthwaite for heteroscedasticity
    2. Contrast in joint model with df from sum(n_k) — correct when borrowing strength across all groups, with HC standard errors or full-sample Satterthwaite correction

    The spill-over problem you identify with full-sample Satterthwaite is real: the correction for the (i, j) contrast would be influenced by the variance structure of groups k that are not involved in that contrast. That is technically correct if you believe the joint model, but it makes the test less transparent.

    For the joint-model case, HC standard errors (HC3 in particular for the small-group robustness) seem like the cleaner path — they do not require estimating effective degrees of freedom at all, just a sandwich covariance estimator. The df_denom would remain sum(n_k) - p, and the heteroscedasticity correction enters through the standard error rather than the degrees of freedom.

  7. amethystani commented on Apr 22, 2026

    @amethystani
    Contributor

    I have opened a fix for this: #9796

    For each pair (i, j), I subset the data to those two groups and fit a dedicated 2-group model with design matrix [X | D*X] where D is a dummy for the second group. The f-test contrast [0…0 | I_k] then uses df_denom = nobs_i + nobs_j - 2*k, which is the correct value. The overall all test is unchanged.

    Five tests added in a new test_onewaygls.py covering exact df values, monotonicity vs full-model df, p-value validity, and the het=True path.

    @josef-pkt — would appreciate your review since you described the correct fix direction in the issue.

  8. added
    type-possible-bug
    on Sep 28, 2026
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

    comp-regressioncomp-statstype-possible-bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions