gpt4 book ai didi

python - K-Means 不会形成肘部形状

转载 作者:行者123 更新时间:2023-11-30 08:56:30 28 4
gpt4 key购买 nike

我正在尝试在 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()

这是选择簇的惯性图。不是弯头形状,颜值很高。

enter image description here

最佳答案

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

k-prototypes is available in Python 的实现.

但是,如果您仅考虑数值变量,您可以看到具有 k 均值标准的肘部:

k-means on numerical data only

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

关于python - K-Means 不会形成肘部形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58684924/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com