如何测试多元线性回归中所有可能的迭代和 return 最佳 R 平方和 P 值组合

How to test all possible iterations in a multiple linear regresion and return the best R-Squared and P values combination

我正在尝试获得最佳组合以达到最佳 R 平方和 P 值。在这种情况下,我有 6 列 运行 代码,但我有这个组合的 R 平方和 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()


您要实现的是 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()