K-means類聚算法(K-means clustering)是一種原理簡單、功能強大且應用普遍的無監督機器學習技術。無監督機器學習技術是指無需標籤便可從數據集中作推理,獲得推理結果。html
K-means類聚算法的目標是將數據集中的數據根據類似性分類,類別數爲k,每類會有一個聚類中心(centroid)。數據間的類似性一般用「歐幾里得距離(Euclidean Distance)」來定義,固然也能夠設計其它的度量方式。python
K-means算法的可視化,請參考:stanford.edu/class/engr1…算法
K-means算法能夠直接調用sklearn的KMeans類來實現,範例代碼以下:markdown
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
df = pd.DataFrame({"x": [25, 34, 22, 27, 33, 33, 31, 22, 35, 34, 67, 54, 57, 43, 50, 57, 59, 52, 65, 47, 49, 48, 35, 33, 44, 45, 38, 43, 51, 46],
"y": [79, 51, 53, 78, 59, 74, 73, 57, 69, 75, 51, 32, 40, 47, 53, 36, 35, 59, 59, 50, 25, 20, 14, 12, 20, 5, 29, 27, 8, 7]})
kmeans = KMeans(n_clusters=3).fit(df)
centroids = kmeans.cluster_centers_
# 打印類聚中心
print(type(centroids), centroids)
# 可視化類聚結果
fig, ax = plt.subplots()
ax.scatter(df['x'],df['y'],c=kmeans.labels_.astype(float),s=50, alpha=0.5)
ax.scatter(centroids[:, 0], centroids[:, 1], c='red', s=50)
plt.show()
複製代碼