【问题标题】:How to test all possible iterations in a multiple linear regresion and return the best R-Squared and P values combination如何在多元线性回归中测试所有可能的迭代并返回最佳 R 平方和 P 值组合
【发布时间】:2021-06-15 19:58:50
【问题描述】:

我正在尝试获得最佳组合以达到最佳 R 平方和 P 值。在这种情况下,我有 6 列来运行代码,但我只有这个组合的 R-Squared 和 P 值([col0, col1, col2, col3, col4, col5] vs [col6])。我想测试所有可能的组合,例如:

[col0] 与 [col6]

[col0 + col1] 与 [col6]

[col0 + col1 + col2] 与 [col6]...

有什么办法可以自动完成吗?所以我不必运行所有可能的组合。

import statsmodels.api as sm
from sklearn import linear_model

X = df_norm[["col0", 
"col1", 
"col2", 
"col3", 
"col4", 
"col5"]]

y = df_norm["col6"]

import statsmodels.api as sm
# with statsmodels
X = sm.add_constant(X)
 
model = sm.OLS(y, X).fit()

print_model = model.summary()


【问题讨论】:

  • 我认为你可以从sklearn中提取R-squared和P-value的值。当您提取值时,根据您的选择运行 50 或 100 次迭代。然后,比较 r-squared 的先前值和 value,如果它们大于当前值。最后,将其保存在 pickle 上,然后根据您的模拟加载具有最高值的 pickle。
  • 在我的真实数据库中,我有 230 列。你能给我一个进行迭代的代码示例吗?
  • 如果您有 230 列,您不想遍历所有可能的组合。总共有 2**230 个组合。你应该想出一个更好的过滤器。

标签: python linear-regression correlation statsmodels


【解决方案1】:

您要实现的是iterools documentation 中显示的powerset 函数:

from itertools import chain, combinations

def powerset(iterable):
    #"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

然后您可以遍历列的每个子集并根据需要处理结果。你的循环会是这样的:

for subset in powerset(X.columns):
    if len(subset) > 0:
        model = sm.OLS(y, X[list(subset)]).fit()

【讨论】:

  • 我必须将此数字更改为我的列名吗? "powerset([1,2,3]) --> () (1,) (​​2,) (3,) (1,2) (1,3) (2,3) (1,2,3) " 使用我的代码,它返回给我:ValueError: 零大小数组到没有标识的最大缩减操作
  • 不,这只是一个评论。
  • 从 sklearn 导入熊猫 import linear_model X = df_norm[["col0", "col1", "col2", "col3", "col4", "col5",]] y = df_norm[" col6"] 来自 itertools 导入链,组合 def powerset(iterable): "powerset([1,2,3]) --> () (1,) (​​2,) (3,) (1,2) (1 ,3) (2,3) (1,2,3)" s = list(iterable) return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) import statsmodels.api as sm # with statsmodels X = sm.add_constant(X) # 为 powerset(X.columns) 中的子集添加一个常数: model = sm.OLS(y, X[list(subset)]).fit() print(print_model )
  • 我运行了该代码 /\ 并返回了我:ValueError: 零大小数组到没有标识的最大缩减操作
  • 已编辑 - 但请尝试自己进行基本调试。错误是不言自明的。
猜你喜欢
  • 2011-08-01
  • 2021-03-05
  • 2019-09-11
  • 1970-01-01
  • 2014-05-27
  • 2019-09-03
  • 2021-02-27
相关资源
最近更新 更多