K-Means 不会导致肘部形状

K-Means not resulting in elbow shape

我正在尝试在 this link 提供的数据集中使用 k-means,仅使用有关客户端的变量。问题是 8 个变量中有 7 个是分类变量,所以我对它们使用了一个热编码器。

为了使用肘部方法 select 理想数量的簇,我已经 运行 了 2 到 22 个簇的 KMeans 并绘制了 inertia_ 值。但是这个形状一点也不像肘部,它看起来更像是一条直线。

我是不是做错了什么?

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans 
from sklearn import preprocessing
from sklearn.preprocessing import StandardScaler

bank = pd.read_csv('bank-additional-full.csv', sep=';') #available at https://archive.ics.uci.edu/ml/datasets/Bank+Marketing# 

# 1. selecting only informations about the client
cli_vars = ['age', 'job', 'marital', 'education', 'default', 'housing', 'loan']
bank_cli = bank[cli_vars].copy()

#2. applying one hot encoder to categorical variables
X = bank_cli[['job', 'marital', 'education', 'default', 'housing', 'loan']]
le = preprocessing.LabelEncoder()
X_2 = X.apply(le.fit_transform)
X_2.values
enc = preprocessing.OneHotEncoder()
enc.fit(X_2)

one_hot_labels = enc.transform(X_2).toarray()
one_hot_labels.shape #(41188, 33)

#3. concatenating numeric and categorical variables
X = np.concatenate((bank_cli.values[:,0].reshape((41188,1)),one_hot_labels), axis = 1)
X.shape

X = X.astype(float)
X_fit = StandardScaler().fit_transform(X)

X_fit

#4. function to calculate k-means for 2 to 22 clusters
def calcular_cotovelo(data):
    wcss = []
    for i in range(2, 23):
        kmeans = KMeans(init = 'k-means++', n_init= 12, n_clusters = i)
        kmeans.fit(data)
        wcss.append(kmeans.inertia_)
    return wcss

cotovelo = calcular_cotovelo(X_fit)

#5. plot to see the elbow to select the ideal number of clusters
plt.plot(cotovelo)
plt.show()

这是 select 集群的惯性图。不是肘型,颜值很高

K-means 不适用于分类数据。您应该改用 k-prototypes,它结合了 k-modes 和 k-means,并且能够对混合的数值和分类数据进行聚类。

k-prototypes is available in Python.

的实现

但是,如果您只考虑数值变量,您会看到符合 k 均值标准的弯头:

要了解为什么看不到任何弯头(对数值数据和分类数据均使用 k 均值),您可以查看每个聚类的点数。你可以观察到,每次增加簇的数量时,都会形成一个新的簇,其中只有几个点在上一步的大簇中,因此标准只比上一步少了几个。