資源簡介
上述代碼是利用python內置的k-means聚類算法對鳶尾花數據的聚類效果展示,注意在運行該代碼時需要采用pip或者其他方式為自己的python安裝sklearn以及iris擴展包,其中X = iris.data[:]表示我們采用了鳶尾花數據的四個特征進行聚類,如果僅僅采用后兩個(效果最佳)則應該修改代碼為X = iris.data[2:]

代碼片段和文件信息
#!/usr/bin/python
#?-*-?coding:?UTF-8?-*-
#############K-means-鳶尾花聚類############
import?matplotlib.pyplot?as?plt
import?numpy?as?np
from?sklearn.cluster?import?KMeans
from?sklearn?import?datasets
from?sklearn.datasets?import?load_iris
iris?=?load_iris()
X?=?iris.data[:]?##表示我們只取特征空間中的后兩個維度
#print(X)
print(X.shape)
#繪制數據分布圖
plt.scatter(X[:?0]?X[:?1]?c?=?“red“?marker=‘o‘?label=‘see‘)
plt.xlabel(‘petal?length‘)
plt.ylabel(‘petal?width‘)
plt.legend(loc=2)
plt.show()
estimator?=?KMeans(n_clusters=3)#構造聚類器
estimator.fit(X)#聚類
label_pred?=?estimator.labels_?#獲取聚類標簽
#繪制k-means結果
x0?=?X[label_pred?==?0]
x1?=?X[label_pred?==?1]
x2?=?X[label_pred?==?2]
plt.scatter(x0[:?0]?x0[:?1]?c?=?“red“?marker=‘o‘?label=‘label0‘)
plt.scatter(x1[:?0]?x1[:?1]?c?=?“green“?marker=‘*‘?label=‘label1‘)
plt.scatter(x2[:?0]?x2[:?1]?c?=?“blue“?marker=‘+‘?label=‘label2‘)
plt.xlabel(‘petal?length‘)
plt.ylabel(‘petal?width‘)
plt.legend(loc=2)
plt.show()
?屬性????????????大小?????日期????時間???名稱
-----------?---------??----------?-----??----
?????文件????????1084??2018-09-10?11:21??K-means_yuanweihua.py
評論
共有 條評論