【问题标题】:Trouble Trying to get an Anova Test in Python; (AttributeError: 'Summary' object has no attribute 'model' ) Error尝试在 Python 中进行 Anova 测试时遇到问题; (AttributeError: 'Summary' object has no attribute 'model' ) 错误
【发布时间】:2020-08-07 11:50:47
【问题描述】:

一家医院随机选择的 25 名患者。除了满意度之外,还收集了有关患者年龄和衡量疾病严重程度的指数的数据。 (a) 拟合与患者年龄相关的满意度的线性回归模型。完毕 (b) 回归显着性检验。 (需要获取Anova Table)

  from pandas import DataFrame


import statsmodels.api as sm

from statsmodels.formula.api import ols

Stock_Market = {'Satisfaction': [68,77,96,80,43,44,26,88,75,57,56,88,88,102,88,70,52,43,46,56,59,26,52,83,75],
        'Age': [55,46,30,35,59,61,74,38,27,51,53,41,37,24,42,50,58,60,62,68,70,79,63,39,49],

        'Severity': [50,24,46,48,58,60,65,42,42,50,38,30,31,34,30,48,61,71,62,38,41,66,31,42,40],

        }



df = DataFrame(Stock_Market,columns=['Satisfaction','Age','Severity'])



X = df[['Age','Severity']]

Y = df['Satisfaction']

X = sm.add_constant(X) 
print(X)

model = sm.OLS(Y, X).fit()
predictions = model.predict(X)
print_model = model.summary()
print(print_model)


aov_table = sm.stats.anova_lm(print_model, typ=2)

【问题讨论】:

    标签: python pandas model statistics regression


    【解决方案1】:

    您需要重塑适合 statsmodel 包的数据框

    In [117]: df_melt = pd.melt(df.reset_index(), id_vars=['index'], value_vars=['Satisfaction', 'Age', 'Severity'])
    
    In [118]: df_melt
    Out[118]:
        index      variable  value
    0       0  Satisfaction     68
    1       1  Satisfaction     77
    2       2  Satisfaction     96
    3       3  Satisfaction     80
    4       4  Satisfaction     43
    ..    ...           ...    ...
    70     20      Severity     41
    71     21      Severity     66
    72     22      Severity     31
    73     23      Severity     42
    74     24      Severity     40
    
    [75 rows x 3 columns]
    
    In [120]: df_melt.columns = ['index', 'categories', 'value']
    
    In [121]: model = ols('value ~ C(categories)', data=df_melt).fit()
    
    In [122]: anova_table = sm.stats.anova_lm(model, typ=2)
    
    In [123]: anova_table
    Out[123]:
                         sum_sq    df         F    PR(>F)
    C(categories)   5198.906667   2.0  9.304327  0.000255
    Residual       20115.440000  72.0       NaN       NaN
    

    【讨论】:

      【解决方案2】:

      您的print_model 是来自summary() 的返回。

      使用您的model,即在anova_lm 中从OLS.fit 返回的结果实例。

      标题中的错误信息表明问题所在:

      AttributeError: 'Summary' object has no attribute 'model'

      【讨论】:

        猜你喜欢
        • 2020-11-21
        • 1970-01-01
        • 2021-11-08
        • 1970-01-01
        • 1970-01-01
        • 2021-06-24
        • 1970-01-01
        • 1970-01-01
        • 2014-03-23
        相关资源
        最近更新 更多