sklearn學習筆記之Kmeans聚類
阿新 • • 發佈:2019-01-08
先講KMeans的建構函式:
使用前需要匯入
import sklearn.cluster import KMeans
KMeans(n_clusters=8,
init='k-means++',
n_init=10,
max_iter=300,
tol=0.0001,
precompute_distances='auto',
verbose=0,
random_state=None,
copy_x=True,
n_jobs=1,
algorithm='auto'
)
各個引數的意義:
引數的意義:
n_clusters
init
: 初始簇中心的獲取方法n_init
: 獲取初始簇中心的更迭次數max_iter
: 最大迭代次數(因為kmeans演算法的實現需要迭代)tol
: 容忍度,即kmeans執行準則收斂的條件precompute_distances
:是否需要提前計算距離verbose
: 冗長模式(不太懂是啥意思,反正一般不去改預設值)random_state
: 隨機生成簇中心的狀態條件。copy_x
: 對是否修改資料的一個標記,如果True,即複製了就不會修改資料。n_jobs
: 並行設定algorithm
: kmeans的實現演算法,有:'auto'
,'full'
,'elkan'
'full'
表示用EM方式實現
import osimport scipy as sp import numpy as np from scipy.stats import norm from matplotlib import pylab from sklearn.cluster import KMeans xw1 = norm(loc=0.3, scale=.15).rvs(20) yw1 = norm(loc=0.3, scale=.15).rvs(20) xw2 = norm(loc=0.7, scale=.15).rvs(20) yw2 = norm(loc=0.7, scale=.15).rvs(20) xw3 = norm(loc=0.2, scale=.15).rvs(20) yw3 = norm(loc=0.8, scale=.15).rvs(20) x = sp.append(sp.append(xw1, xw2), xw3) y = sp.append(sp.append(yw1, yw2), yw3) km = KMeans(init='random', n_clusters=3, verbose=1, n_init=1, max_iter=6) colors=['red','green','blue'] marker=['o','p','^'] for i in km.labels_: pylab.scatter(x[km.labels_==i],y[km.labels_==i],marker=marker[i],c=colors[i]) pylab.show()
關於KMeans物件的屬性:
labels_:每個點的分類;
cluster_centers_:向量,[n_clusters, n_features]
inertia_:float,每個點到其簇的質心的距離之和。
KMeans物件的方法:
fit(X[,y]): 計算k-means聚類。
fi_predictt(X[,y]): 計算簇質心並給每個樣本預測類別。
fit_transform(X[,y]):計算簇並 transform X to cluster-distance space。
get_params([deep]):取得估計器的引數。
predict(X):給每個樣本估計最接近的簇。
score(X[,y]):Opposite of the value of X on the K-means objective (?)
set_params(**params):為這個估計器手動設定引數。
transform(X[,y]):將X轉換入cluster-distance 空間。