Skip to content

ENH: standardized coefficients - params table #3857

Open

Description

@josef-pkt

Add beta coefficients (coefficients for standardized data) as a post-estimation results method.

API: return similar to t_test with params table, summary, summary_frame

Most likely this can internally reuse t_test, we just need the linear transformation matrix to standardize.
Alternative would be similar to transformation in models, e.g. fit_constrained and returning a results instance.

Applies to linear model, but I never looked at the interpretation in GLM, discrete. So, I'm not sure whether it would be helpful to add in base instead of regression.

Issue #1131 discusses transformation to improve estimation but here it is just a post-estimation diagnostic.

I wrote this function already a long time ago, but never committed it anywhere. If the design in not orthogonal, then the beta coefficients are not a variance decomposition. I read some papers for importance statistics in that case, but those didn't look very popular.

related topic: SAS has a large number of extra statistics and diagnostics for the linear model.

Activity

  1. josef-pkt commented on Aug 6, 2017

    @josef-pkt
    MemberAuthor

    possible issues:

    • WLS (GLM IRLS related) should we use plain variance or weighted variance.
    • models that are not linear homogenous (scale of exog matters), e.g. penalized estimators: as diagnostic we don't rescale the penalization. E,g, estimator/penalization is on original scale, but beta coefficients are standardized post-estimation.
      (For penalization we also have the opposite case, we keep the parameters on the original scale, but adjust penalization for the variance of exog. I.e. penalize at standardized coefficients but report original coefficients.)

    In those cases we don't have equivalence between results after standardizing endog and exog and the post-estimation beta coefficients, and cannot use that property in unit tests.

  2. josef-pkt commented on Sep 26, 2017

    @josef-pkt
    MemberAuthor

    just a thought "eform" with/as standardized coefficients?

    multiplier in exp mean function or oddsration in logit mean function are normalized for the interpretation of the response, but still depend on the exog scale.
    e.g. standardize/rescale only the exog
    "odds_ratio for one standard deviation change in explanatory variables"?

  3. stevenlis commented on Feb 12, 2019

    @stevenlis

    My current workaround:

    import pandas as pd
    import numpy as np
    from scipy import stats
    import statsmodels.formula.api as smf
    
    # standardizing dataframe
    df_z = df.select_dtypes(include=[np.number]).dropna().apply(stats.zscore)
    
    # fitting regression
    formula = 'y ~ x1 + x2 + x3'
    result = smf.ols(formula, data=df_z).fit()
    
    # checking results
    result.params

    Is there any other easy ways to get the beta coefficients with the current SM api?

  4. josef-pkt commented on Feb 13, 2019

    @josef-pkt
    MemberAuthor

    see my answer to the stackoverflow question https://stackoverflow.com/questions/50842397/how-to-get-standardised-beta-coefficients-for-multiple-linear-regression-using

    There is no need to reestimate the model, (although in corner cases standardizing the exog can improve numerical stability of the computations)

    We can just transform the estimated params by the standard deviation of the exog. results.t_test(transformation) computes the parameter table for the linearly transformed variables.
    
    AFAIR, the following should produce the beta coefficients and corresponding inferential statistics.
    
    Compute standard deviation, but set it to 1 for the constant.
    
    std = model.exog.std()
    std[0] = 1
    Then use results.t_test and look at the params_table. np.diag(std) creates a diagonal matrix that transforms the params.
    
    tt = results.t_test(np.diag(std))
    print(tt.summary()
    tt.summary_frame()
    
  5. josef-pkt commented on Feb 13, 2019

    @josef-pkt
    MemberAuthor

    using std on all exog includes the constant
    If we only want the standardized slope coefficients, then we need to remove the row in np.diag(std) that refers to the constant, i.e. where std=0.
    I'm not sure whether that is needed, i.e. standardized beta for constant is zero, and bse should still be correct (also=0 ? I think, without doing the math or checking an example again).

  6. stevenlis commented on Feb 13, 2019

    @stevenlis

    I tried

    std = smf.ols(formula, data=df).exog.std()

    but it returned a floating number. Am I missing something?

  7. josef-pkt commented on Feb 13, 2019

    @josef-pkt
    MemberAuthor

    Sorry, my mistake, also on the stackoverflow answer. (Problem with typing answers without trying out the code. I did this several years ago, and don't remember where I put my examples.)

    use std(0): we need std along axis=0 to get the std for each column of exog.

    Also, std[0] = 1 in my code assumes that the constant is in the first column, which does not standardize the constant.

  8. stevenlis commented on Feb 13, 2019

    @stevenlis

    Could you try the following code and the results doesn't seem to match with one another.

    #%%
    import pandas as pd
    import seaborn as sns
    import numpy as np
    import statsmodels.formula.api as smf
    from scipy import stats
    #%%
    df = sns.load_dataset('tips')
    df = df[['total_bill', 'tip', 'size']]
    #%%
    #
    formula = 'tip ~ total_bill + size'
    model = smf.ols(formula, data=df)
    results = model.fit()
    #
    std = model.exog.std(axis=0)
    std[0] = 1
    tt = results.t_test(np.diag(std))
    tt.summary()
    #%%
    df_std = df.apply(stats.zscore)
    results = smf.ols(formula, data=df_std).fit()
    results.params

    image

  9. josef-pkt commented on Feb 13, 2019

    @josef-pkt
    MemberAuthor

    AFAIR, the endog is not zscored for the beta coefficients

    using original 'tip'

    df_std = df.apply(stats.zscore)
    df_std['tip'] = df['tip']
    results = smf.ols(formula, data=df_std).fit()
    results.params
    

    then I get

    tt.effect[1:] - results.params[1:]
    
    total_bill    6.661338e-16
    size         -1.665335e-16
    dtype: float64
    

    to get the standardized coefficient if also endog is standardized we can use:

    std = model.exog.std(axis=0)
    std_y = df['tip'].values.std()
    tt = results0.t_test(np.diag(std / std_y)[1:])  # ignore constant
    print(tt.summary(xname=['total_bill', 'size']))
                                 Test for Constraints                             
    ==============================================================================
                     coef    std err          t      P>|t|      [0.025      0.975]
    ------------------------------------------------------------------------------
    total_bill     0.5965      0.059     10.172      0.000       0.481       0.712
    size           0.1324      0.059      2.258      0.025       0.017       0.248
    ==============================================================================
    
  10. josef-pkt commented on Feb 13, 2019

    @josef-pkt
    MemberAuthor

    AFAIR, the endog is not zscored for the beta coefficients

    wikipedia says dependent variable is also z-scored

    so my "AFAIR" is based on not remembering this correctly (or I had a different definition)

    e.g.
    https://www3.nd.edu/~rwilliam/stats1/x92.pdf

  11. josef-pkt commented on Feb 13, 2019

    @josef-pkt
    MemberAuthor

    related issue #1660

    (I remember that I looked at the literature for something similar to beta coefficients in the orthogonal/uncorrelated exog case where we have some interpretation as variance decomposition.
    It didn't sound exciting or generally applicable enough to me to write code for it.)

  12. josef-pkt commented on Feb 13, 2019

    @josef-pkt
    MemberAuthor

    GLM/discrete like Poisson or Binomial:

    • Standardizing exog still makes sense to get effect size or margins in terms of standard deviation of exog.
    • Standardizing endog (count or binary) doesn't make sense.

    i.e. if we want generic beta coefficients, we cannot use linear model properties.

    (Ok, I should read my early comments above instead of coming up with the same thoughts again.)

  13. josef-pkt commented on Feb 13, 2019

    @josef-pkt
    MemberAuthor

    one more comment

    numpy std uses ddof=0 by default, I guess SPSS uses ddof=1.

    (ddof drops out in std_x / std_y)

  14. stevenlis commented on Feb 14, 2019

    @stevenlis

    I no longer use SPSS but Stata sometimes. I actually checked my results using lm.beta in R before posting. I checked Stata and it actually indeed transfer all variable to a z distribution

    From REGRESSION WITH STATA CHAPTER

    In other words, the beta coefficients are the coefficients that you would obtain if the outcome and predictor variables were all transformed standard scores, also called z-scores, before running the regression.

    From Stata's regress doc on page 3

    The beta coefficients are the regression coefficients obtained by first standardizing all variables to have a mean of 0 and a standard deviation

    I think you're right about GLM and I never hear of using beta coef in GLM and Stata doesn't offer that option either. Thus, I think maybe we should only include it in OLS/linear model summary or add an attribute to allow user's access to it in RegressionResults?

  15. stevenlis commented on Feb 14, 2019

    @stevenlis

    I'm not very familiar with this .t_test() method but using the equation in the handout you linked seems working.

    #%%
    import pandas as pd
    import seaborn as sns
    import numpy as np
    import statsmodels.formula.api as smf
    from scipy import stats
    #%%
    df = sns.load_dataset('tips')
    df = df[['total_bill', 'tip', 'size']]
    formula = 'tip ~ total_bill + size'
    model = smf.ols(formula, data=df)
    results = model.fit()
    #%%
    b = np.array(results.params)[1:]
    std_y = model.endog.std(axis=0)
    std_x = model.exog.std(axis=0)[1:]
    beta = b*(std_x/std_y)
    #%%
    df_std = df.apply(stats.zscore)
    results = smf.ols(formula, data=df_std).fit()
    #%%
    print(results.params[1:])
    print(beta)

    Output:

    total_bill    0.596523
    size          0.132390
    dtype: float64
    [0.59652323 0.1323899 ]
    
  16. josef-pkt commented on Feb 14, 2019

    @josef-pkt
    MemberAuthor

    t_test in the results classes does the same thing, it tests linear combination of parameters for each row in the restriction matrix. With a diagonal restriction matrix, each parameter is multiplied by the corresponding diagonal element.

    The main advantage is that t_test can produce the entire params_table including standard errors, pvalue and confidence interval.

  17. josef-pkt commented on Oct 30, 2021

    @josef-pkt
    MemberAuthor

    For WLS and IRLS, we have the choice or option to standardize w.r.t. endog, exog or wendog, wexog.

    In terms of var_weights, I think this correspond to standardizing the original data by var (std) or weighted var (std).
    I guess we can check the definitions in terms of variance decomposition in an orthogonal design with var_weights, e.g. for balanced anova.

  18. added this to the 0.14 milestone on Oct 30, 2021
  19. added a commit that references this issue on Sep 13, 2026
    5659791
  20. Shikhar-Kesharwani commented on Sep 13, 2026

    @Shikhar-Kesharwani

    Implemented in PR #10248. Added RegressionResults.get_beta_coefficients() (and alias beta_coefficients()) returning a structured BetaCoefficientsResults container with standardized beta estimates, standard errors, $t$-values, $p$-values, confidence intervals, and .summary(). Matches direct z-score standardized OLS regression.

  21. Shikhar-Kesharwani commented on Sep 13, 2026

    @Shikhar-Kesharwani

    Dedicated PR opened in #10250 with isolated diff, full test suite, and benchmarks.

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

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions