設(shè)計(jì)思路:
1.準(zhǔn)備好初始數(shù)據(jù)
2.pandas庫(kù)導(dǎo)入,初步處理數(shù)據(jù)
3.matplotlib庫(kù)處理數(shù)據(jù),把數(shù)據(jù)畫(huà)成圖
4.從sklearn庫(kù)里調(diào)用K-mean算法,處理數(shù)據(jù),分類
5.對(duì)數(shù)據(jù)再次畫(huà)圖
import pandas as pd# 導(dǎo)入數(shù)據(jù)處理模塊
file = pd.read_csv("cluster_data.csv", header=0)# 導(dǎo)入數(shù)據(jù)文件printfile# 輸出文件
X = file['x']# 定義橫坐標(biāo)數(shù)據(jù)
y = file['y']# 定義縱坐標(biāo)數(shù)據(jù)
from matplotlib import pyplot as plt# 導(dǎo)入繪圖模塊
plt.scatter(X, y)# 繪制散點(diǎn)圖
plt.show()# 顯示圖
from sklearn.cluster import k_means# 導(dǎo)入 K-Means 方法
model = k_means(file, n_clusters =3)# 建立聚類模型
cluster_centers = model[0]# 聚類中心數(shù)組
cluster_labels = model[1]# 聚類標(biāo)簽數(shù)組
plt.scatter(X, y, c=cluster_labels)# 繪制樣本并按聚類標(biāo)簽標(biāo)注顏色
# 繪制聚類中心點(diǎn),標(biāo)記成五角星樣式,以及紅色邊框
for center in cluster_centers:? ?
????? plt.scatter(center[0], center[1], marker="p", edgecolors="red")
????? plt.show()# 顯示圖