我试图分离数据集的哪些特性(即Pandas DataFrame的列)用于线性回归,并且我希望选择那些不具有强相关性的特征(假设自变量需要彼此不相关,因此我们希望删除任何似乎具有强相关性的特性)。
我已经分离出了与目标变量相关的特性的初始列表,如下所示:
# get the absolute correlations for the target variable
correlations_target = abs(df.corr()[target_variable_name])
# filter out those that are below our threshold
correlated_features = correlations_target[correlations_target >= correlation_threshold]
# drop the target variable's column
correlated_features.drop(target_variable_name, inplace=True)
# get the column names for later use
correlated_feature_variable_names = correlated_features.index现在,我想介绍每一个相关的特性变量,并确保它们都没有强相关性,如果它们有,那么删除与目标变量相关性最弱的一个。这是我为这个做的:
# the collection of feature variable names we'll drop due to their being correlated to other features
correlated_feature_variable_names_to_drop = []
# loop over the feature combinations
for name_1 in correlated_feature_variable_names:
for name_2 in correlated_feature_variable_names:
# only look at correlations between separate feature variables
if name_1 != name_2:
# drop one of the feature variables if there's a strong correlation
if abs(df[[name_1, name_2]].corr()[name_1][name_2]) > 0.6:
# only worry about it if neither of the variables have been added to the drop list
if (name_1 not in correlated_feature_variable_names_to_drop) and \
(name_2 not in correlated_feature_variable_names_to_drop):
# drop the one which has the least correlation to the target variable
if correlated_features[name_1] >= correlated_features[name_2]:
correlated_feature_variable_names_to_drop.append(name_2)
else:
correlated_feature_variable_names_to_drop.append(name_1)
# drop the variables we've found that qualify
correlated_features.drop(correlated_feature_variable_names_to_drop, inplace=True)
# get the remaining variables' column names for later use
filtered_feature_variable_names = correlated_features.index过滤后的特征集将用作简单回归模型的输入。例如:
# fit a simple ordinary least squares model to the features
X = df[filtered_feature_variable_names]
y = df[target_variable_name]
estimate = sm.OLS(y, np.asarray(X)).fit()
# display the regression results
estimate.summary()因为这是我第一次尝试这种方法,所以我不确定这是否是正确的方法,如果是的话,可能有一种比上面使用的循环方法更聪明、更有效(或者说是"Pythonic")的方法来执行过滤。
发布于 2020-02-29 05:42:49
首先,我要说,我可能在这里遗漏了你的意图的一部分,因为你写的东西,虽然代码很清楚,但是是通用的。我很难确定这是术语还是别的什么。
我认为你的意图是寻找和过滤那些彼此高度相关但被用来解释第三件事的东西。例如,年龄和天数实际上是描述相同的事情(时间)。其中任何一种,但不是两者,都可以描述与第三种事物的关系,如树的直径。这里的概念是共线性的,你想要减少它是完全正确的。
这就是探索性数据分析的来源。像相关矩阵热图这样的快速可视化将是很好的第一步。
但是,当您进行回归时,您要寻找的是实际上是相关的但不是共线的东西。我知道您打算将其输入到一个简单的回归模型中,但在这种情况下,您可能会考虑使用sklearn的套索或山脊回归工具。
使用sklearn还有一个额外的原因:您的示例可能与我给出的示例(与天相关的年份)不同,后者恰好是完全相关的。在你的例子中,摆脱其中一个可能是去除一些预测信息。这两种模型都将规范数据,两者都有自动特征选择的好处。脊处理具有多重共线性的数据。另一方面,如果你有稀疏的数据,拉索更好。
最后一点:虽然更大的社区也是如此,但我认为您的问题可能在Stack Exchange的数据科学社区中得到更好的答案。
https://stackoverflow.com/questions/60461257
复制相似问题