需要多少个聚类?

Python 中的聚类分析

Shaumik Daityari

Business Analyst

如何找到合适的 k?

  • 没有用于确定正确聚类数(k)的"绝对"方法
  • 肘部法

Python 中的聚类分析

重新理解失真

  • 失真:点到聚类中心的平方距离之和
  • 聚类数增加时会降低
  • 当聚类数等于样本数时为 0
  • 肘部图:聚类数与失真的折线图

Python 中的聚类分析

肘部法

  • 肘部图:聚类数与失真的关系图
  • 用于指示数据中的聚类数
Python 中的聚类分析

Python 中的肘部法

# Declaring variables for use
distortions = []

num_clusters = range(2, 7)
# Populating distortions for various clusters
for i in num_clusters:
    centroids, distortion = kmeans(df[['scaled_x', 'scaled_y']], i)
    distortions.append(distortion)
# Plotting elbow plot data
elbow_plot_data = pd.DataFrame({'num_clusters': num_clusters,
                                'distortions': distortions})

sns.lineplot(x='num_clusters', y='distortions', 
             data = elbow_plot_data)
plt.show()
Python 中的聚类分析

Python 中的聚类分析

使用肘部法的要点

  • 仅指示最优的 k(聚类数)
  • 并非总能精确定位 k
  • 其他方法:平均轮廓系数、Gap 统计量
Python 中的聚类分析

接下来:练习

Python 中的聚类分析

Preparing Video For Download...