【问题标题】:Converting a simple regression to a logarithmic scale with patsy, statsmodels使用 patsy、statsmodels 将简单回归转换为对数刻度
【发布时间】:2020-04-22 12:18:06
【问题描述】:

我在学习在线计量经济学课程并学习统计模型。

我从讲师那里知​​道,这种回归在对数尺度上会更合适,但我不知道如何或在哪里转换我的数据/公式。

我正在使用 Python、Pandas、Statsmodels 和 Patsy

这是我将数据转换为 dmatrices 的地方:

    y, X = dmatrices('PRICE ~ QUANTITY', data=df, return_type='dataframe')

这是我在 statsmodels 中运行回归的地方:

    mod = sm.OLS(y, X)      # Describe model

    res = mod.fit()         # Fit Model

    print(res.summary())    # Summarize model

我得到一个非常低的 r 平方,但模型确实运行。我只是想弄清楚如何转换为对数刻度。课程中给出的示例,他将 X 轴和 Y 轴都转换为对数刻度

编辑:我使用它来工作:

    df2['Quantity'] = np.log(df['QUANTITY'])
    df2['Price'] = np.log(df['PRICE'])

有没有办法在 1 行代码中完成,如果我需要在另一个问题中对更多变量执行此操作,甚至可以使用循环?

【问题讨论】:

  • df2_log = np.log(df2[['x','y',z]])

标签: python linear-regression statsmodels logarithm patsy


【解决方案1】:

一个简单的循环,也可以更改名称以包含“日志”,可以是

columns = ['QUANTITY', 'PRICE', 'aaa']
for col in columns:
    df2["log-" + col] = np.log(df[col])

也可以在公式中使用np.log,但 statsmodels 在这种情况下不提供更多支持,它会在每次运行回归或公式时计算日志,而不是为相关列计算一次数据框。

【讨论】:

    猜你喜欢
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    • 2018-06-12
    • 1970-01-01
    相关资源
    最近更新 更多