# kmeans聚类选择最优K值python实现

Kmeans算法中K值的确定是很重要的。

①手肘法

python代码：

``````import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import xlrd

# 从Excel中读取数据存入数组
rawData = xlrd.open_workbook('kmeansdata.xlsx')
table = rawData.sheets()[0]
data = []
for i in range(table.nrows):
if i == 0:
continue
else:
data.append(table.row_values(i)[1:])
featureList = ['Age', 'Gender', 'Degree']
mdl = pd.DataFrame.from_records(data, columns=featureList)

# '利用SSE选择k'
SSE = []  # 存放每次结果的误差平方和
for k in range(1, 9):
estimator = KMeans(n_clusters=k)  # 构造聚类器
estimator.fit(np.array(mdl[['Age', 'Gender', 'Degree']]))
SSE.append(estimator.inertia_)
X = range(1, 9)
plt.xlabel('k')
plt.ylabel('SSE')
plt.plot(X, SSE, 'o-')
plt.show()``````

②轮廓系数法

python代码：

``````import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
import matplotlib.pyplot as plt
import xlrd

# 从Excel中读取数据存入数组
rawData = xlrd.open_workbook('kmeansdata.xlsx')
table = rawData.sheets()[0]
data = []
for i in range(table.nrows):
if i == 0:
continue
else:
data.append(table.row_values(i)[1:])
featureList = ['Age', 'Gender', 'Degree']
mdl = pd.DataFrame.from_records(data, columns=featureList)

Scores = []  # 存放轮廓系数
for k in range(2, 9):
estimator = KMeans(n_clusters=k)  # 构造聚类器
estimator.fit(np.array(mdl[['Age', 'Gender', 'Degree']]))
Scores.append(silhouette_score(np.array(mdl[['Age', 'Gender', 'Degree']]), estimator.labels_, metric='euclidean'))
X = range(2, 9)
plt.xlabel('k')
plt.ylabel('轮廓系数')
plt.plot(X, Scores, 'o-')
plt.show()``````

http://www.omegaxyz.com/2018/08/28/python%e5%88%a9%e7%94%a8sklearn%e8%bf%9b%e8%a1%8ckmeans%e8%81%9a%e7%b1%bb/