【问题标题】:K-Means not resulting in elbow shapeK-Means 不会导致弯头形状
【发布时间】:2020-02-29 06:25:20
【问题描述】:

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

为了使用肘法选择理想数量的集群,我对 2 到 22 个集群运行了 KMeans 并绘制了惯性值。但它的形状不像肘部,更像是一条直线。

我做错了吗?

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()

这是选择集群的惯性图。不是肘形,数值很高。

【问题讨论】:

  • 嘿,您对您的数据了解多少?有多棒?我会试试这个数据集,但这可能不是代码问题...
  • 当您进行热编码时,您正在增加数据的维度,如下所示:stats.stackexchange.com/questions/93488/… 这可能有一些问题...

标签: python machine-learning k-means


【解决方案1】:

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

k-prototypes is available in Python 的实现。

但是,如果您只考虑数值变量,您可以看到带有 k-means 标准的肘部:

要了解为什么您看不到任何肘部(在数值和分类数据上都使用 k 均值),您可以查看每个集群的点数。可以观察到,每增加聚类数,新的聚类就形成了一个新的聚类,只有上一步在一个大聚类中的几个点,因此标准只比上一步少了几个。

【讨论】:

    猜你喜欢
    • 2013-10-12
    • 2018-10-04
    • 1970-01-01
    • 2011-06-10
    • 2013-10-14
    • 2013-07-03
    • 2021-07-09
    • 2020-03-03
    • 2021-02-17
    相关资源
    最近更新 更多