知道如何使用’statsmodels api’进行基本的普通最小二乘法(OLS)。
但是,我不知道如何从多个自变量中选择合适的自变量。
添加或移除一个自变量会导致P值发生较大变化。
通过移除最大P值来检查的方法效率低且不准确。
您知道如何通过P值选择最优的自变量吗?
回答:
Scikit-Learn和其他类似的API提供了自动选择特征的工具,例如boruta。示例:
# 假设是回归问题# 使用GenericUnivariateSelect保留50%的特征from sklearn.feature_selection import GenericUnivariateSelectfrom sklearn.feature_selection import mutual_info_regression# X = 自变量, y = 因变量X_mutual_information = mutual_info_regression(X, y)selector = GenericUnivariateSelect(score_func=mutual_info_regression, mode='k_best', param=50)X_trans = selector.fit_transform(X, y)print(f"{X.shape[1] - 1} 初始特征。{X_trans.shape[1]} 个被保留")# 使用决策树和SelectFromModelfrom sklearn.tree import DecisionTreeRegressorfrom sklearn.feature_selection import SelectFromModelregressor = DecisionTreeRegressor()selector = SelectFromModel(regressor, threshold='median')X_trans = selector.fit_transform(X, y)print(f"{X.shape[1] - 1} 初始特征。{X_trans.shape[1]} 个被保留")# 使用递归特征消除而不是SelectFromModelfrom sklearn.feature_selection import RFECVselector = RFECV(regressor)X_trans = selector.fit_transform(X, y)print(selector.get_support())
获取这些特征后,您可以尝试使用这些特征进行OLS,看看是否改进了您的算法。
另见boruta以获取更多策略