【发布时间】:2021-12-30 06:06:12
【问题描述】:
我有一个包含 12 个分类变量的数据集,我已经对其执行了 k 模式聚类,总共形成了 3 个聚类。我想查看每个变量对聚类的贡献。
【问题讨论】:
我有一个包含 12 个分类变量的数据集,我已经对其执行了 k 模式聚类,总共形成了 3 个聚类。我想查看每个变量对聚类的贡献。
【问题讨论】:
如果分类变量确实对聚类有用,那么您应该能够看到分类标签和 kmode 预测标签之间的关联。我们可以尝试使用卡方检验来检验这种关联。
使用来自kmodes soybean 的示例数据集:
from kmodes.kmodes import KModes
import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/nicodv/kmodes/master/examples/soybean.csv",header=None)
X = df.iloc[:,:-1]
X = X.loc[:,X.var() > 0]
X.columns = ['feature{}'.format(i) for i in X.columns]
y = df.iloc[:,-1]
X.iloc[:5,:5]
feature0 feature1 feature2 feature3 feature4
0 4 0 2 1 1
1 5 0 2 1 0
2 3 0 2 1 0
3 6 0 2 1 0
4 4 0 2 1 0
适合 kmmodes:
km = KModes(n_clusters=4).fit(X)
对于每一列,使用预测标签执行卡方检验:
from scipy.stats import chi2_contingency
def chi_test(ds,labels):
ct = pd.crosstab(ds,labels)
return chi2_contingency(ct)
res = X.apply(lambda x:chi_test(x,km.labels_)[:-1]).T
res.columns = ["chi2","p","df"]
我们可以按pvalue对结果进行排序:
res.sort_values("p")
chi2 p df
feature20 107.823529 4.076092e-19 9.0
feature21 105.750000 1.075367e-18 9.0
feature6 71.515314 7.676489e-12 9.0
feature2 53.702317 8.470441e-10 6.0
feature3 51.052191 2.891285e-09 6.0
feature27 47.000000 3.475607e-10 3.0
feature26 47.000000 3.475607e-10 3.0
feature25 47.000000 3.475607e-10 3.0
feature22 47.000000 3.475607e-10 3.0
feature34 43.191379 2.241181e-09 3.0
feature0 42.703296 8.811983e-04 18.0
feature11 41.186842 5.968910e-09 3.0
feature1 40.573818 8.052002e-09 3.0
feature23 31.292825 7.375288e-07 3.0
feature24 20.702381 1.213722e-04 3.0
feature7 11.779102 8.179472e-03 3.0
feature9 6.907064 3.295275e-01 6.0
feature4 6.582880 8.645061e-02 3.0
feature5 4.361413 8.860574e-01 9.0
feature19 3.128446 3.722421e-01 3.0
feature8 0.437745 9.323395e-01 3.0
排名第一的feature20 几乎可以区分您的标签:
pd.crosstab(km.labels_,X['feature20'])
feature20 0 1 2 3
row_0
0 0 8 9 0
1 0 0 0 10
2 10 0 0 0
3 0 10 0 0
与排名较低的feature5相比:
feature5 0 1 2 3
row_0
0 2 5 4 6
1 0 4 3 3
2 2 3 2 3
3 3 2 2 3
【讨论】: