我正在尝试获取有关自变量的相关性的信息。
我的数据集有很多变量,因此热图不是解决方案,非常难以读取。
目前,我已经制作了一个仅返回高度相关变量的函数。我想以指示相关特征对的方式对其进行更改。
以下是其他说明:
def find_correlated_features(df, threshold, target_variable):
df_1 = df.drop(target_variable)
#corr_matrix has in index and columns names of variables
corr_matrix = df_1.corr().abs()
# I'm taking only half of this matrix to prevent doubling results
half_of_matrix = corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k = 1).astype(np.bool))
# This prints list of columns which are correlated
to_drop = [column for column in half_of_matrix.columns if any(half_of_matrix[column] > threshold)]
return to_drop
最好的方法是返回带有column_1的pandas数据帧;column_2; corr_coef仅超过阈值的变量。
像这样:
output = {'feature name 1': column_name,
'feature name 2': index,
'correlation coef': corr_coef}
output_list.append(output)
return pd.DataFrame(output_list).sort_values('corr_coef', ascending=False)
编辑后:
在OP注释和@ user6386471回答之后,我再次阅读了该问题,我认为对相关矩阵进行简单的重组就可以了,而无需循环。喜欢half_of_matrix.stack().reset_index()
加过滤器。看到:
def find_correlated_features(df, threshold, target_variable):
# remove target column
df = df.drop(columns=target_variable).copy()
# Get correlation matrix
corr_matrix = df.corr().abs()
# Take half of the matrix to prevent doubling results
corr_matrix = corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k = 1).astype(np.bool))
# Restructure correlation matrix to dataframe
df = corr_matrix.stack().reset_index()
df.columns = ['feature1', 'feature2', 'corr_coef']
# Apply filter and sort coefficients
df = df[df.corr_coef >= threshold].sort_values('corr_coef', ascending=False)
return df
原始答案:
您可以轻松创建Series
系数大于阈值的a,如下所示:
s = df.corr().loc[target_col]
s[s.abs() >= threshold]
这里df
是你的数据框,target_col
您的目标列,并且threshold
,你知道,阈值。
例:
import pandas as pd
import seaborn as sns
df = sns.load_dataset('iris')
print(df.shape)
# -> (150, 5)
print(df.head())
sepal_length sepal_width petal_length petal_width species
0 5.1 3.5 1.4 0.2 setosa
1 4.9 3.0 1.4 0.2 setosa
2 4.7 3.2 1.3 0.2 setosa
3 4.6 3.1 1.5 0.2 setosa
4 5.0 3.6 1.4 0.2 setosa
def find_correlated_features(df, threshold, target_variable):
s = df.corr().loc[target_variable].drop(target_variable)
return s[s.abs() >= threshold]
find_correlated_features(df, .7, 'sepal_length')
输出:
petal_length 0.871754
petal_width 0.817941
Name: sepal_length, dtype: float64
您可以使用.to_frame()
后跟.T
输出来获取熊猫数据框。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句