【问题标题】:Does 'statsmodels' or another Python package offer an equivalent to R's 'step' function?“statsmodels”或其他 Python 包是否提供与 R 的“step”功能等效的功能?
【发布时间】:2014-04-21 03:19:55
【问题描述】:

R 的 step 功能是否有 statsmodels 或其他 Python 等效项,用于使用 AIC 选择基于公式的模型?

【问题讨论】:

    标签: r pandas linear-regression statsmodels model-fitting


    【解决方案1】:

    我真的怀疑你在做和我一样的在线课程——下面的内容可以让你得到正确的答案。如果手头的任务计算量不是很大(并且不在课程中),那么我们可以回避 step 函数的所有智能细节,只尝试预测变量的所有子集。

    对于每个子集,我们可以将AIC 计算为ACI = 2*nvars - 2*result.llf
    然后我们只需要找到一个具有最小 AIC 的子集:

    import itertools
    import numpy as np
    import pandas as pd
    import statsmodels.api as sm
    AICs = {}
    for k in range(1,len(predictorcols)+1):
        for variables in itertools.combinations(predictorcols, k):
            predictors = train[list(variables)]
            predictors['Intercept'] = 1
            res = sm.OLS(target, predictors).fit()
            AICs[variables] = 2*(k+1) - 2*res.llf
    pd.Series(AICs).idxmin()
    

    【讨论】:

    • 好方法。最后,我只是在 R 中完成,并将模型复制到 Python 中。
    【解决方案2】:

    第一个答案对我不起作用,但下面的答案对我有用。大量抄袭 Kostya。

    AICs = {}
    for k in range(1,len(predictorcols)+1):
        for variables in itertools.combinations(predictorcols, k):
            predictors = list(variables)
            i = True
            independent =''
            for p in predictors:
                if i:
                    independent = p
                    i=False
                else:
                    independent+='+ {}'.format(p)
            regresion = '$DependentVariable$ ~ {}'.format(independent)
            res = sm.ols(regresion, data=train).fit()
            AICs[variables] = 2*(k+1) - 2*res.llf
    pd.Series(AICs).idxmin()
    

    【讨论】:

      猜你喜欢
      • 2020-09-07
      • 1970-01-01
      • 2012-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      相关资源
      最近更新 更多