Skip to main content
 首页 » 编程设计

python之回归汇总输出 : Order of categories

2025年05月04日10txw1958

这个问题是关于GLM的结果打印方式,也就是系数打印的顺序。我所说的“顺序”并不是指该术语的任何统计意义。

以下代码确定了一个线性模型:

from pandas import * 
import statsmodels.api as sm 
import patsy as patsy 
 
df = read_csv("http://vincentarelbundock.github.io/Rdatasets/csv/ggplot2/diamonds.csv") 
 
y, X = patsy.dmatrices( 'price ~  cut', data = df ) 
 
sm.GLM( y, X, family= sm.families.Gaussian()  ).fit().summary() 

... 并生成以下输出,其中类别已排序:

(一般)、良好、理想、优质、非常好

==================================================================================== 
                       coef    std err          z      P>|z|      [95.0% Conf. Int.] 
------------------------------------------------------------------------------------ 
Intercept         4358.7578     98.788     44.122      0.000      4165.137  4552.379 
cut[T.Good]       -429.8933    113.849     -3.776      0.000      -653.034  -206.753 
cut[T.Ideal]      -901.2158    102.412     -8.800      0.000     -1101.939  -700.493 
cut[T.Premium]     225.4999    104.395      2.160      0.031        20.889   430.111 
cut[T.Very Good]  -376.9979    105.164     -3.585      0.000      -583.116  -170.880 
==================================================================================== 

我正在尝试做的事情:

我希望它们的顺序如下:

(一般)、好、非常好、优质、理想

我正在尝试做的事情在 R 中看起来像这样:

df = read.table( file = "http://vincentarelbundock.github.io/Rdatasets/csv/ggplot2/diamonds.csv", 
            sep = ",",  header = TRUE) 
 
 
df$cut = factor( df$cut, levels = c("Fair", "Good", "Very Good", "Premium", "Ideal")) 
 
glm( price ~ cut, data = df, family = gaussian  ) 

注意输出中的排序遵循因​​子排序:

(一般)、好、非常好、优质、理想

Call:  glm(formula = price ~ cut, family = gaussian, data = df) 
 
Coefficients: 
 (Intercept)       cutGood  cutVery Good    cutPremium      cutIdeal   
      4358.8        -429.9        -377.0         225.5        -901.2 

我如何在 Python 中执行此操作?

请您参考如下方法:

这是一个已知问题。我相信 PR 会受到欢迎。也许在这里继续对话?

https://github.com/pydata/patsy/issues/27