Python 用肘部法和K-均值聚类法寻找最优聚类数
我正在编写一个程序,我需要对大约200、300个元素数组的数据集应用K-means聚类。 有人能给我提供一个代码的链接,上面有解释吗- 1.用弯头法求k 2.应用k-均值法求质心阵列 我自己搜索了上述内容,但没有找到任何对代码有明确解释的内容。 另外,我正在谷歌Colab上工作,所以如果有具体的方法,请提出建议Python 用肘部法和K-均值聚类法寻找最优聚类数,python,google-colaboratory,k-means,Python,Google Colaboratory,K Means,我正在编写一个程序,我需要对大约200、300个元素数组的数据集应用K-means聚类。 有人能给我提供一个代码的链接,上面有解释吗- 1.用弯头法求k 2.应用k-均值法求质心阵列 我自己搜索了上述内容,但没有找到任何对代码有明确解释的内容。 另外,我正在谷歌Colab上工作,所以如果有具体的方法,请提出建议 我尝试了下面的代码,但是,我不断得到以下错误- --------------------------------------------------------------------
我尝试了下面的代码,但是,我不断得到以下错误-
---------------------------------------------------------------------------
TypeError回溯(最近一次调用上次)
TypeError:float()参数必须是字符串或数字,而不是“list”
上述异常是以下异常的直接原因:
ValueError回溯(最近一次调用上次)
在()
24
25#步骤1:找到最佳k(簇数)
--->26寻找最佳答案()
27
3帧
/asarray中的usr/local/lib/python3.6/dist-packages/numpy/core//\u asarray.py(a,数据类型,顺序)
83
84 """
--->85返回数组(a,数据类型,副本=False,顺序=order)
86
87
ValueError:使用序列设置数组元素。
假设有12个样本,每个样本具有以下两个特征:
data=np.array([[1,1],[1,2],[2,1.5],[4,5],[5,6],[4,5.5],[5,5],[8,8],[8,8.5],[9,8],[8.5,9],[9,9]])
您可以使用弯头方法找到最佳簇数,簇中心如以下示例所示:
import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
data=np.array([[1,1],[1,2],[2,1.5],[4,5],[5,6],[4,5.5],[5,5],[8,8],[8,8.5],[9,8],[8.5,9],[9,9]])
def find_best_k():
sum_of_squared_distances = []
K=range(1,8) # change 8 in your data
for k in K:
km=KMeans(n_clusters=k)
km=km.fit(data)
sum_of_squared_distances.append(km.inertia_)
plt.plot(K, sum_of_squared_distances, 'bx-')
plt.xlabel('k')
plt.ylabel('sum_of_squared_distances')
plt.title('Elbow method for optimal k')
plt.show()
#The plot looks like an arm, and the elbow on the arm is optimal k.
# step 1: find optimal k (number of clusters)
find_best_k()
def run_kmeans(k,data): # k is the optimal number of clusters
km=KMeans(n_clusters=k)
km=km.fit(data)
centroids = km.cluster_centers_ #get the center of clusters
#print(centroids)
return centroids
def plotresults():
centroids=run_kmeans(3,data)
plt.plot(data[0:3,0],data[0:3,1],'ro',data[3:7,0],data[3:7,1],'bo',data[7:12,0],data[7:12,1],'go')
for i in range(3):
plt.plot(centroids[i,0],centroids[i,1],'k*')
plt.text(centroids[i,0],centroids[i,1], "c"+str(i), fontsize=12)
plotresults()
肘部图:
结果是:
希望这有帮助。作为Roohollah答案的补充:请注意,用于为K-Means找到最佳聚类数的肘部方法纯粹是视觉的,结果可能不明确。因此,您可能希望将其与轮廓分析相结合,例如,在以下文章中: , ,
.在哪里运行代码?我使用的是numpy=1.18.1、sklearn=0.22.1和python=3.7.6的jupyter笔记本。