一、參數(shù)與方法
- scikit-learn中用于進(jìn)行k-means機(jī)器學(xué)習(xí)的類是sklearn.cluster.KMeans价脾,它所涉及的參數(shù)有超過10個(gè)之多廷臼,但是最常用的其實(shí)就是n_clusters 和random_state蝗柔;
- n_clusters表示打算聚類的數(shù)目,默認(rèn)情況下是8情龄;
- random_state表示產(chǎn)生隨機(jī)數(shù)的方法迄汛。默認(rèn)缺省值為None捍壤,此時(shí)隨機(jī)數(shù)產(chǎn)生器是np.random所使用的RandomState實(shí)例“鞍可以自定義一個(gè)RandomState實(shí)例類型作為參數(shù)鹃觉,也可以使用一個(gè)整數(shù)來作為參數(shù),此時(shí)這個(gè)整數(shù)表示產(chǎn)生隨機(jī)數(shù)的種子睹逃,即類編號(hào)盗扇;
- 常用方法
- fit()函數(shù):僅產(chǎn)生聚類中心,即建模沉填。通常利用它疗隶,實(shí)現(xiàn)基于已建立的模型,預(yù)測新元素的分類情況翼闹;
- predict()函數(shù):基于已知的聚類中心斑鼻,為輸入的數(shù)據(jù)加上分類標(biāo)簽;
- fit_predict()函數(shù):計(jì)算聚類中心猎荠,并為輸入的數(shù)據(jù)加上分類標(biāo)簽坚弱;
二、聚類步驟
- 導(dǎo)入包关摇,準(zhǔn)備數(shù)據(jù)
import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
x = np.array([[15, 17], [12,18], [14,15], [13,16], [12,15], [16,12],
[4,6], [5,8], [5,3], [7,4], [7,2], [6,5]])
- 聚類分析前荒叶,需要確定聚類數(shù)目。數(shù)據(jù)量較少時(shí)输虱,可以直接通過觀察數(shù)據(jù)些楣,確定類別,本例中數(shù)據(jù)宪睹,很明顯可以看出戈毒,聚類數(shù)目設(shè)置為2比較合適;數(shù)據(jù)量較多時(shí)横堡,可以按比例隨機(jī)抽樣,畫散點(diǎn)圖來觀察聚類數(shù)目冠桃;當(dāng)數(shù)據(jù)量特別大時(shí)命贴,可以通過誤差平方和的方式,來確定聚類數(shù)據(jù)食听;
- 進(jìn)行k-means聚類胸蛛,使用fit_predit()函數(shù),為數(shù)據(jù)加上聚類標(biāo)簽樱报;
y_pred= KMeans(n_clusters=2).fit_predict(x)
y_pred
array([1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], dtype=int32)
- 可視化聚類效果葬项,一類設(shè)置為紅色,另一類設(shè)置為綠色迹蛤;
plt.figure(figsize=(6, 6))
color = ("red", "green")
colors = np.array(color)[y_pred]
plt.scatter(x[:, 0], x[:, 1], c=colors)
plt.show()
- 基于上面的聚類結(jié)果民珍,通過fit()函數(shù)和predict()函數(shù)襟士,為新增加的2個(gè)元素,預(yù)測分類嚷量;
kmeans = KMeans(n_clusters=2).fit(x)
new_data = np.array([[3, 3], [15, 15]])
# 預(yù)測分類的結(jié)果
new_kmeans = kmeans.predict(new_data)
new_kmeans
array([1, 0], dtype=int32)
三陋桂、圖片處理實(shí)例
- 需求說明
- 本實(shí)例要學(xué)習(xí)的問題是圖像處理中的色彩量化(Color Quantization)問題;
- scikit 在通過圖片的作者共同授權(quán)下蝶溶,嵌入了幾個(gè)樣本 JPG圖片嗜历,方便用戶進(jìn)行算法測試。本示例使用名為
china.jpg
的圖片抖所,經(jīng)統(tǒng)計(jì)其中共有96615種不同的色彩梨州;
- 要求用更少的色彩來展示這張圖片,從而實(shí)現(xiàn)類似圖像壓縮的目的田轧,比如只用64種顏色暴匠;
- 使用K-means聚類方法,將原來的96615種色彩聚合成64個(gè)類涯鲁,然后使用新的64個(gè)色彩中心作為新圖像中所使用的色彩巷查;
- 為了加速聚類過程,其實(shí)抹腿,并不需要讓原來的96615種色彩都參與計(jì)算岛请,可以隨機(jī)從中選取部分(例如1000種)顏色來進(jìn)行計(jì)算;
- 聚類
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.metrics import pairwise_distances_argmin
from sklearn.datasets import load_sample_image
from sklearn.utils import shuffle
n_colors = 64 # 聚類數(shù)目為64
china = load_sample_image('china.jpg')
china = np.array(china, dtype=np.float64) / 255 # 讀取照片像素值警绩,并將其轉(zhuǎn)化到[0, 1]
w, h, d = original_shape = tuple(china.shape)
image_array = china.reshape(w * h, d)
# 隨機(jī)排列崇败,取前1000
image_array_sample = shuffle(image_array, random_state=0)[:1000]
# 聚類,構(gòu)建模型
kmeans = KMeans(n_clusters=n_colors, random_state=0).fit(image_array_sample)
labels = kmeans.predict(image_array)
- 重建圖像
def recreate_image(center_data, labels, w, h):
"""基于模型中心肩祥,構(gòu)建圖片"""
d = center_data.shape[1]
image = np.zeros((w, h, d))
labels_index = 0
for i in range(w):
for j in range(h):
image[i][j] = center_data[labels[labels_index]]
labels_index += 1
return image
ax = plt.axes([0, 0, 2, 2])
plt.axis('off')
plt.title('Quantized image (64 colors, K-Means)')
plt.imshow(recreate_image(kmeans.cluster_centers_, labels, w, h))
-
圖像效果后室,盡管大量減少了色彩使用量,圖像在細(xì)節(jié)上仍然基本保持了原貌混狠,只是壓縮后岸霹,分辨率降低,清晰度變差将饺。