Scikit-learn的kmeans聚類


1. 生成隨機的二維數據:

import numpy as np  
x1 = np.array([1, 2, 3, 1, 5, 6, 5, 5, 6, 7, 8, 9, 9])  
x2 = np.array([1, 3, 2, 2, 8, 6, 7, 6, 7, 1, 2, 1, 3])  
x = np.array(list(zip(x1, x2))).reshape(len(x1), 2) #先將x1和x2用zip組合,然后再轉換成list,最后reshape

print (x)

  

2.生成聚類標簽:

from sklearn.cluster import KMeans  
kmeans=KMeans(n_clusters=3)   #n_clusters:number of cluster  
kmeans.fit(x)  
print (kmeans.labels_)

  

3.顯示聚類效果:

import matplotlib.pyplot as plt  
plt.figure(figsize=(5,5))  
colors = ['b', 'g', 'r']  
markers = ['o', 's', 'D']  
for i,l in enumerate(kmeans.labels_):  
     plt.plot(x1[i],x2[i],color=colors[l],marker=markers[l],ls='None')  
plt.show() 

  

參考: https://blog.csdn.net/qq_34264472/article/details/53217748  (此為python2代碼)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM