我正在使用包含 39 个属性(38 个独立特征 + 类属性)的数据集来解决分类问题。当我尝试计算相关矩阵时,不考虑类属性。据我所知,它也应该包含在矩阵中。
len(heartdata.columns)
39
由于我的数据帧中的列数为 39,因此相关矩阵的形状应为 (39,39),但我得到的是:
cor = heartdata.corr()
cor.shape
(38, 38)
最佳答案
如果您的特征是分类的,您应该使用LabelEncoding
from sklearn.preprocessing import LabelEncoder
train = train_df
label_encoder = LabelEncoder()
for i in range(len(train.columns)):
column = train_df.columns[i]
train[column] = label_encoder.fit_transform(train_df[column])
print(f"train {column} uniques: {len(train[column].unique())} ")
x = train
y = train_df['gender'].to_frame(name='gender')
然后就可以得到相关矩阵
:
cor = x.corr()
print(cor)
如果您想使用绘图来显示特征之间的相关性,我建议使用heatmap
绘图:
import matplotlib.pyplot as plt
import seaborn as sns
plt.figure(figsize=(10,8),linewidth=10,edgecolor="#04253a" )
sns.heatmap(cor, annot=True, cmap=plt.cm.Reds)
plt.show()
关于python - pandas 中的相关矩阵不考虑某些列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67252076/