要分成幾群?

Python 中的叢集分析

Shaumik Daityari

Business Analyst

如何找出合適的 k?

  • 沒有找出 k-means 最佳群數(k)的「絕對」方法
  • 肘部法(Elbow method)

Python 中的叢集分析

再談失真

  • 失真(Distortion):點到群中心距離平方和
  • 群數增加時會下降
  • 當群數等於點數時為 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...