1. 程式人生 > >【scikit-learn】03:將sklearn庫用於非監督性學習 聚類

【scikit-learn】03:將sklearn庫用於非監督性學習 聚類

# -*-coding:utf-8-*-

# ----------------------
#   Author:kevinelstri
#   Datetime:2017.2.16
# ----------------------

# -----------------------
# Unsupervised learning: seeking representations of the data
# http://scikit-learn.org/stable/tutorial/statistical_inference/unsupervised_learning.html
# -----------------------
import numpy as np ''' 非監督性學習 ''' ''' Clustering: grouping observations together 聚類:分組觀察 The problem solved in clustering 聚類中的問題求解 給定一個iris資料集,如果我們知道iris有三種類型,但是沒有一個能夠分開三類的標籤; 此時,可以嘗試使用聚類任務,將觀察到的資料劃分成更好的組就叫做聚類。 ''' ''' K-means clustering : k均值聚類 聚類中存在許多不同的聚類標準和相關演算法,最簡單的聚類演算法就是K均值聚類演算法 '''
from sklearn import cluster, datasets iris = datasets.load_iris() # 載入資料集 x_iris = iris.data # 資料集的資料 y_iris = iris.target # 資料集的標籤 print x_iris print y_iris k_means = cluster.KMeans(n_clusters=3) # k_means分類器,引數n_clusters=3,劃分成3類 print k_means.fit(x_iris) # 分類器直接對資料進行聚類 print k_means.labels_[::10
] # 標籤 print y_iris[::10] print '-------------------------------------------------' ''' Application example: vector quantization :應用案例:向量量化 聚類的一般演算法,特別的,可以作為一種選擇一些典範的壓縮資訊,這個問題被稱為向量量化。 ''' import scipy as sp import matplotlib.pyplot as plt try: face = sp.face(gray=True) except AttributeError: from scipy import misc face = misc.face(gray=True) plt.gray() plt.imshow(face) plt.show() # 顯示原圖 # 把圖片畫素進行聚類 X = face.reshape((-1, 1)) k_means = cluster.KMeans(n_clusters=5, n_init=1) # 構造分類器,引數n_clusters是K值 print k_means.fit(X) # 分類器對資料進行聚類,分類不需要預測 values = k_means.cluster_centers_.squeeze() labels = k_means.labels_ face_compressed = np.choose(labels, values) face_compressed.shape = face.shape print face_compressed # 影象中各個畫素的大小 print face_compressed.shape # 影象大小 plt.gray() plt.imshow(face_compressed) plt.show() # 顯示分類器操作過的影象 ''' Hierarchical agglomerative clustering: Ward 層次凝聚聚類演算法(自下向上) 層次聚類方法是典型的聚類分析方法,目的是建立一個分層的聚類。一般,層次聚類的方法可以分為以下兩種: 自下向上-層次聚類(Agglomerative): 自頂向下-層次聚類(Divisive): ''' ''' 約束連線聚類: ''' import matplotlib.pyplot as plt from sklearn.feature_extraction.image import grid_to_graph from sklearn.cluster import AgglomerativeClustering from sklearn.utils.testing import SkipTest from sklearn.utils.fixes import sp_version from scipy import misc import scipy as sp if sp_version < (0, 12): raise SkipTest("Skipping because SciPy version earlier than 0.12.0 and " "thus does not include the scipy.misc.face() image.") try: face = sp.face(gray=True) except AttributeError: from scipy import misc face = misc.face(gray=True) face = sp.misc.imresize(face, 0.10) / 255. plt.gray() plt.imshow(face) plt.show() ''' Feature agglomeration 特徵群 ''' digits = datasets.load_digits() images = digits.images x = np.reshape(images, (len(images), -1)) connectivity = grid_to_graph(*images[0].shape) agglo = cluster.FeatureAgglomeration(connectivity=connectivity, n_clusters=32) print agglo.fit(x) x_reduced = agglo.transform(x) x_approx = agglo.inverse_transform(x_reduced) images_approx = np.reshape(x_approx, images.shape) ''' Principal component analysis: PCA 降維 ''' x1 = np.random.normal(size=100) x2 = np.random.normal(size=100) x3 = x1 + x2 X = np.c_[x1, x2, x3] from sklearn import decomposition pca = decomposition.PCA() # PCA降維演算法 print pca.fit(X) # 直接對資料進行降維 print pca.explained_variance_ pca.n_components = 2 X_reduced = pca.fit_transform(X) print X_reduced.shape

KMeans案例:

# -*-coding:utf-8-*-
"""
第一部分:匯入包
從sklearn.cluster機器學習聚類包中匯入KMeans聚類
"""

from sklearn.cluster import Birch
from sklearn.cluster import KMeans

"""
第二部分:資料集
X表示二維矩陣資料,籃球運動員比賽資料
總共20行,每行兩列資料
第一列表示球員每分鐘助攻數:assists_per_minute
第二列表示球員每分鐘得分數:points_per_minute
"""

X = [[0.0888, 0.5885],
     [0.1399, 0.8291],
     [0.0747, 0.4974],
     [0.0983, 0.5772],
     [0.1276, 0.5703],
     [0.1671, 0.5835],
     [0.1906, 0.5276],
     [0.1061, 0.5523],
     [0.2446, 0.4007],
     [0.1670, 0.4770],
     [0.2485, 0.4313],
     [0.1227, 0.4909],
     [0.1240, 0.5668],
     [0.1461, 0.5113],
     [0.2315, 0.3788],
     [0.0494, 0.5590],
     [0.1107, 0.4799],
     [0.2521, 0.5735],
     [0.1007, 0.6318],
     [0.1067, 0.4326],
     [0.1956, 0.4280]
     ]

# 輸出資料集
print X

"""
第三部分:KMeans聚類
clf = KMeans(n_clusters=3) 表示類簇數為3,聚成3類資料,clf即賦值為KMeans
y_pred = clf.fit_predict(X) 載入資料集X,並且將聚類的結果賦值給y_pred
"""

clf = KMeans(n_clusters=3)  # 聚類演算法,引數n_clusters=3,聚成3類
y_pred = clf.fit_predict(X)  # 直接對資料進行聚類,聚類不需要進行預測

# 輸出完整Kmeans函式,包括很多省略引數
print clf
# 輸出聚類預測結果,20行資料,每個y_pred對應X一行或一個球員,聚成3類,類標為0、1、2
print y_pred

"""
第四部分:視覺化繪圖
Python匯入Matplotlib包,專門用於繪圖
import matplotlib.pyplot as plt 此處as相當於重新命名,plt用於顯示影象
"""

import numpy as np
import matplotlib.pyplot as plt

# 獲取第一列和第二列資料 使用for迴圈獲取 n[0]表示X第一列
x = [n[0] for n in X]
print x
y = [n[1] for n in X]
print y

# 繪製散點圖 引數:x橫軸 y縱軸 c=y_pred聚類預測結果 marker型別 o表示圓點 *表示星型 x表示點
plt.scatter(x, y, c=y_pred, marker='x')

# 繪製標題
plt.title("Kmeans-Basketball Data")

# 繪製x軸和y軸座標
plt.xlabel("assists_per_minute")
plt.ylabel("points_per_minute")

# 設定右上角圖例
plt.legend(["A", "B", "C"])

# 顯示圖形
plt.show()