Python機器學習(1):KMeans聚類
阿新 • • 發佈:2017-10-30
ima mea arr src ont array imp rom open
Python進行KMeans聚類是比較簡單的,首先需要import numpy,從sklearn.cluster中import KMeans模塊:
import numpy as np from sklearn.cluster import KMeans
然後讀取txt文件,獲取相應的數據並轉換成numpy array:
X = [] f = open(‘rktj4.txt‘) for v in f: regex = re.compile(‘\s+‘) X.append([float(regex.split(v)[3]), float(regex.split(v)[6])]) X= np.array(X)
設置類的數量,並聚類:
n_clusters = 5
cls = KMeans(n_clusters).fit(X)
完整代碼:
import numpy as np from sklearn.cluster import KMeans import matplotlib.pyplot as plt import re X = [] f = open(‘rktj4.txt‘) for v in f: regex = re.compile(‘\s+‘) X.append([float(regex.split(v)[3]), float(regex.split(v)[6])]) X = np.array(X) n_clusters = 5 cls = KMeans(n_clusters).fit(X) cls.labels_ markers = [‘^‘,‘x‘,‘o‘,‘*‘,‘+‘] for i in range(n_clusters): members = cls.labels_ == i plt.scatter(X[members, 0], X[members, 1], s=60, marker=markers[i], c=‘b‘, alpha=0.5)print plt.title(‘‘) plt.show()
運行結果:
Python機器學習(1):KMeans聚類