Python機器學習及實踐——基礎篇:無監督學習經典模型(特征降維)
特征降維不僅可以重構有效的低維度特征向量,同時也為數據展現提供了可能。在特征降維的方法種,主成分分析(Principal Component Analysis, PCA)是最為經典和實用的特征降維技術,特別是輔助圖像識別方法有突出的表現。
1.主成分分析
線性相關矩陣秩計算樣例
import numpy as np
# 初始化一個2*2的線性相關矩陣
M = np.array([[1, 2], [2, 4]])
# 計算2*2線性相關矩陣的秩
print(np.linalg.matrix_rank(M, tol=None))
PCA的思想是首先把原來的特征空間做了映射,使得新的映射后特征空間數據彼此正交。這樣一來,通過主成分分析就盡可能保留下具備區分性的低維數據特征。
應用案例:手寫體數字圖像識別
顯示手寫體數字圖片經PCA壓縮后的二維空間分布
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@File : PCAdigits.py
@Author: Xinzhe.Pang
@Date : 2019/7/23 20:05
@Desc :
"""
import pandas as pd
import numpy as np
# 從互聯網讀入手寫體圖片識別任務的訓練數據
digits_train = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/optdigits/optdigits.tra',
header=None)
digits_test = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/optdigits/optdigits.tes',
header=None)
# 分割訓練數據的特征向量和標記
X_digits = digits_train[np.arange(64)]
y_digits = digits_train[64]
# 從sklearn.decomposition導入PCA
from sklearn.decomposition import PCA
# 初始化一個可以將高維度特征向量(64維)壓縮到2個維度的PCA
estimator = PCA(n_components=2)
X_pca = estimator.fit_transform(X_digits)
# 顯示10類手寫體數字圖像經過PCA壓縮后的2維空間分布
from matplotlib import pyplot as plt
def plot_pca_scatter():
colors = ['black', 'blue', 'purple', 'yellow', 'white', 'red', 'lime', 'cyan', 'orange', 'gray']
for i in range(len(colors)):
px = X_pca[:, 0][y_digits.as_matrix() == i]
py = X_pca[:, 1][y_digits.as_matrix() == 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()
使用原始像素特征和經PCA壓縮重建的低維特征,在相同配置的支持向量機(分類)模型上分別進行圖像識別。
# 對訓練數據、測試數據進行特征向量(圖片像素)與分類目標的分割。
X_train = digits_train[np.arange(64)]
y_train = digits_train[64]
X_test = digits_test[np.arange(64)]
y_test = digits_test[64]
# 導入基于線性核的支持向量機分類器
from sklearn.svm import LinearSVC
# 使用默認參數的LinearSVC,對原始64維像素特征的訓練數據進行建模,并在測試數據上做出預測
svc = LinearSVC()
svc.fit(X_train, y_train)
y_pred = svc.predict(X_test)
# 使用PCA將64維圖像數據壓縮到20個維度
estimator = PCA(n_components=20)
# 利用訓練特征決定(fit)20個正交維度的方向,并轉化(transform)原訓練特征
pca_X_train = estimator.fit_transform(X_train)
# 對測試特征進行同樣處理
pca_X_test = estimator.transform(X_test)
# 使用默認參數的LinearSVC對壓縮后的20維特征的訓練數據進行建模,并在測試數據上進行預測
pca_svc = LinearSVC()
pca_svc.fit(pca_X_train, y_train)
pca_y_pred = pca_svc.predict(pca_X_test)
原始像素特征與PCA壓縮重建的低維特征,在相同配置的支持向量機(分類)模型上識別性能的差異。
# 從sklearn.matrics導入classification_report用于更加細致的分類性能分析
from sklearn.metrics import classification_report
# 對使用原始圖像高維像素特征訓練的支持向量機分類器的性能做出評估
print(svc.score(X_test, y_test))
print(classification_report(y_test, y_pred, target_names=np.arange(10).astype(str)))
# 對使用PCA壓縮重建的低維圖像特征訓練的支持向量機分類器的性能做出評估
print(pca_svc.score(pca_X_test, y_test))
print(classification_report(y_test, pca_X_test, target_names=np.arange(10).astype(str)))
降維/壓縮問題則是選取數據具有代表性的特征,在保持數據多樣性(Variance)的基礎上,規避掉大量的特征冗余和噪聲,不過這個過程也很有可能會損失一些有用的模式信息。
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
