scikit_learn學習筆記四——無監(jiān)督學習之聚類與降維

無監(jiān)督學習

  • 發(fā)現(xiàn)數(shù)據(jù)本身的分布特點

數(shù)據(jù)聚類 K-means

預先設定聚類個數(shù)煌往,再不斷更新聚類中心,多輪迭代后力穗,使得所有數(shù)據(jù)點到其所屬聚類中心距離的平方和趨于穩(wěn)定.

#matplotlib inline
import numpy as np
# 從sklearn.cluster中導入KMeans算法包
from sklearn.cluster import KMeans
# 從sklearn.metrics導入silhouette_score用于計算輪廓系數(shù)
from sklearn.metrics import silhouette_score
import matplotlib.pyplot as plt

# 初始化原始數(shù)據(jù)點。
x1 = np.array([1, 2, 3, 1, 5, 6, 5, 5, 6, 7, 8, 9, 7, 9])
x2 = np.array([1, 3, 2, 2, 8, 6, 7, 6, 7, 1, 2, 1, 4, 3])
X = np.array(list(zip(x1, x2))).reshape(len(x1), 2)

plt.figure(figsize=(16, 8))
# 在1號子圖做出原始數(shù)據(jù)點陣的分布。
plt.subplot(2, 3, 1)
plt.xlim([0, 10])
plt.ylim([0, 10])
plt.title('Instances')
plt.scatter(x1, x2)

colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'b']
markers = ['o', 's', 'D', 'v', '^', 'p', '*', '+']

clusters = [2, 3, 4, 5, 8]
subplot_counter = 1
sc_scores = []
for t in clusters:
    subplot_counter += 1
    plt.subplot(2, 3, subplot_counter)
    # 根據(jù)每次不同的 cluster值進行聚類
    kmeans_model = KMeans(n_clusters=t).fit(X)
    for i, l in enumerate(kmeans_model.labels_):
        plt.plot(x1[i], x2[i], color=colors[l], marker=markers[l], ls='None')
    plt.xlim([0, 10])
    plt.ylim([0, 10])
    # 輪廓系數(shù)評估 聚類算法
    sc_score = silhouette_score(X, kmeans_model.labels_, metric='euclidean')
    sc_scores.append(sc_score)

    # 繪制輪廓系數(shù)與不同類簇數(shù)量的直觀顯示圖诞外。
    plt.title('K = %s, silhouette coefficient= %0.03f' %(t, sc_score))

print(sc_scores)
# 繪制輪廓系數(shù)與不同類簇數(shù)量的關系曲線。
plt.figure()
plt.plot(clusters, sc_scores, '*-')
plt.xlabel('Number of Clusters')
plt.ylabel('Silhouette Coefficient Score')

plt.tight_layout()
plt.show()
k-means

optdigits手寫體聚類

#%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# 從sklearn.cluster中導入KMeans模型
from sklearn.cluster import KMeans
# 從sklearn導入度量函數(shù)庫metrics
from sklearn import metrics

# 使用pandas分別讀取訓練數(shù)據(jù)與測試數(shù)據(jù)集
digits_train = pd.read_csv('data/optdigits_train.csv', header=None)
digits_test = pd.read_csv('data/optdigits_test.csv', header=None)


# 從訓練與測試數(shù)據(jù)集上都分離出64維度的像素特征與1維度的數(shù)字目標
X_train = digits_train[np.arange(64)]
y_train = digits_train[64]

X_test = digits_test[np.arange(64)]
y_test = digits_test[64]


# 初始化KMeans模型灾票,并設置聚類中心數(shù)量為10
kmeans = KMeans(n_clusters=10)
kmeans.fit(X_train)

# 逐條判斷每個測試圖像所屬的聚類中心
y_pred = kmeans.predict(X_test)

# 使用ARI進行KMeans聚類性能評估
print(metrics.adjusted_rand_score(y_test, y_pred))

print(digits_train[64].unique())
digits_train.head()
image.png

數(shù)據(jù)降維

對optdigits_train數(shù)據(jù)進行降維處理

#%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# 從sklearn.decomposition導入PCA 
from sklearn.decomposition import PCA
# 從sklearn.cluster中導入KMeans模型
from sklearn.cluster import KMeans
# 從sklearn導入度量函數(shù)庫metrics
from sklearn import metrics

# 使用pandas分別讀取訓練數(shù)據(jù)與測試數(shù)據(jù)集
digits_train = pd.read_csv('data/optdigits_train.csv', header=None)
digits_test = pd.read_csv('data/optdigits_test.csv', header=None)

# 分割訓練數(shù)據(jù)的特征向量和標記峡谊。
X_digits = digits_train[np.arange(64)]
y_digits = digits_train[64]


# 初始化一個可以將高維度特征向量(64維)壓縮至2個維度的PCA
estimator = PCA(n_components=2)
X_pca = estimator.fit_transform(X_digits)

def plot_pca_scatter():
    colors = ['black', 'blue', 'purple', 'yellow', 'white', 'red', 'lime', 'cyan', 'orange', 'gray']
    plt.figure(figsize=(12, 8))
    for i in range(len(colors)):
        px = X_pca[:, 0][y_digits.values == i]
        py = X_pca[:, 1][y_digits.values == i]
        plt.scatter(px, py, c=colors[i])
    
    plt.legend(np.arange(0,10).astype(str))
    plt.xlabel('First Principal Component')
    plt.ylabel('Second Principal Component')
    plt.show()
    
plot_pca_scatter()

"""
print(X_pca.shape)

from mpl_toolkits.mplot3d import Axes3D 

def plot_pca_scatter():
    colors = ['black', 'blue', 'purple', 'yellow', 'white', 'red', 'lime', 'cyan', 'orange', 'gray']
    fig = plt.figure(figsize=(12, 8))
    ax = Axes3D(fig)
    for i in range(len(colors)):
        px = X_pca[:, 0][y_digits.values == i]
        py = X_pca[:, 1][y_digits.values == i]
        pz = X_pca[:, 2][y_digits.values == i]
        ax.scatter(px, py, pz, c=colors[i])
    
    ax.legend(np.arange(0,10).astype(str))
    ax.set_xlabel('First Principal Component')
    ax.set_ylabel('Second Principal Component')
    ax.set_zlabel('Third Principal Component')
    ax.view_init(elev=10,azim=235)
    plt.show()
    
plot_pca_scatter()
"""

壓縮到2個維度
壓縮到3個維度

降維再進行模型訓練

使用PCA將原64維的圖像數(shù)據(jù)壓縮到20個維度

對壓縮過后的20維特征的訓練數(shù)據(jù)進行建模,并在測試數(shù)據(jù)上做出預測

# 導入基于線性核的支持向量機分類器
from sklearn.svm import LinearSVC
# 從sklearn.metrics導入classification_report用于更加細致的分類性能分析
from sklearn.metrics import classification_report


# 使用pandas分別讀取訓練數(shù)據(jù)與測試數(shù)據(jù)集
digits_train = pd.read_csv('data/optdigits_train.csv', header=None)
digits_test = pd.read_csv('data/optdigits_test.csv', header=None)

# 對訓練數(shù)據(jù)、測試數(shù)據(jù)進行特征向量(圖片像素)與分類目標的分隔
X_train = digits_train[np.arange(64)]
y_train = digits_train[64]
X_test = digits_test[np.arange(64)]
y_test = digits_test[64]

print(X_test.shape)
# 使用默認配置初始化LinearSVC既们,對原始64維像素特征的訓練數(shù)據(jù)進行建模濒析,并在測試數(shù)據(jù)上做出預測,存儲在y_predict中
svc = LinearSVC()
svc.fit(X_train, y_train)
y_predict = svc.predict(X_test)

# 使用PCA將原64維的圖像數(shù)據(jù)壓縮到20個維度
estimator = PCA(n_components=20)

# 利用訓練特征決定(fit)20個正交維度的方向啥纸,并轉化(transform)原訓練特征
pca_X_train = estimator.fit_transform(X_train)
# 測試特征也按照上述的20個正交維度方向進行轉化(transform)
pca_X_test = estimator.transform(X_test)

# 使用默認配置初始化LinearSVC号杏,對壓縮過后的20維特征的訓練數(shù)據(jù)進行建模,并在測試數(shù)據(jù)上做出預測斯棒,存儲在pca_y_predict中
pca_svc = LinearSVC()
pca_svc.fit(pca_X_train, y_train)
pca_y_predict = pca_svc.predict(pca_X_test)

# 對使用原始圖像高維像素特征訓練的支持向量機分類器的性能作出評估
print(svc.score(X_test, y_test))
print(classification_report(y_test, y_predict, target_names=np.arange(10).astype(str)))

# 對使用PCA壓縮重建的低維圖像特征訓練的支持向量機分類器的性能作出評估
print(pca_svc.score(pca_X_test, y_test))
print(classification_report(y_test, pca_y_predict, target_names=np.arange(10).astype(str)))
image.png
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末盾致,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子名船,更是在濱河造成了極大的恐慌绰上,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,576評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件渠驼,死亡現(xiàn)場離奇詭異蜈块,居然都是意外死亡,警方通過查閱死者的電腦和手機迷扇,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,515評論 3 399
  • 文/潘曉璐 我一進店門百揭,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人蜓席,你說我怎么就攤上這事器一。” “怎么了厨内?”我有些...
    開封第一講書人閱讀 168,017評論 0 360
  • 文/不壞的土叔 我叫張陵祈秕,是天一觀的道長。 經(jīng)常有香客問我雏胃,道長请毛,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,626評論 1 296
  • 正文 為了忘掉前任瞭亮,我火速辦了婚禮方仿,結果婚禮上,老公的妹妹穿的比我還像新娘统翩。我一直安慰自己仙蚜,他們只是感情好,可當我...
    茶點故事閱讀 68,625評論 6 397
  • 文/花漫 我一把揭開白布厂汗。 她就那樣靜靜地躺著委粉,像睡著了一般。 火紅的嫁衣襯著肌膚如雪娶桦。 梳的紋絲不亂的頭發(fā)上艳丛,一...
    開封第一講書人閱讀 52,255評論 1 308
  • 那天匣掸,我揣著相機與錄音趟紊,去河邊找鬼氮双。 笑死,一個胖子當著我的面吹牛霎匈,可吹牛的內容都是我干的戴差。 我是一名探鬼主播,決...
    沈念sama閱讀 40,825評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼铛嘱,長吁一口氣:“原來是場噩夢啊……” “哼暖释!你這毒婦竟也來了?” 一聲冷哼從身側響起墨吓,我...
    開封第一講書人閱讀 39,729評論 0 276
  • 序言:老撾萬榮一對情侶失蹤球匕,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后帖烘,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體亮曹,經(jīng)...
    沈念sama閱讀 46,271評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 38,363評論 3 340
  • 正文 我和宋清朗相戀三年秘症,在試婚紗的時候發(fā)現(xiàn)自己被綠了照卦。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,498評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡乡摹,死狀恐怖役耕,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情聪廉,我是刑警寧澤瞬痘,帶...
    沈念sama閱讀 36,183評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站板熊,受9級特大地震影響框全,放射性物質發(fā)生泄漏。R本人自食惡果不足惜邻邮,卻給世界環(huán)境...
    茶點故事閱讀 41,867評論 3 333
  • 文/蒙蒙 一竣况、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧筒严,春花似錦丹泉、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,338評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至娶视,卻和暖如春晒哄,著一層夾襖步出監(jiān)牢的瞬間睁宰,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,458評論 1 272
  • 我被黑心中介騙來泰國打工寝凌, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留柒傻,地道東北人。 一個月前我還...
    沈念sama閱讀 48,906評論 3 376
  • 正文 我出身青樓较木,卻偏偏與公主長得像红符,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子伐债,可洞房花燭夜當晚...
    茶點故事閱讀 45,507評論 2 359