1. 程式人生 > >機器學習之路:python 特征降維 主成分分析 PCA

機器學習之路:python 特征降維 主成分分析 PCA

repo nts total python learning bsp ota spa 像素

python3 學習api使用

主成分分析方法實現降低維度

使用了網絡上的數據集,我已經下載到了本地,可以去我的git上參考

git:https://github.com/linyi0604/MachineLearning

代碼:

 1 from sklearn.svm import LinearSVC
 2 from sklearn.metrics import classification_report
 3 from sklearn.decomposition import  PCA
 4 import pandas as pd
 5 import numpy as np
 6 ‘‘‘
 7 主成分分析:
8 特征降低維度的方法。 9 提取主要特征成分,有關聯的特征進行運算組合 10 丟棄不顯著的特征成分, 同時可能損失有意義的特征 11 實現降低特征維度 12 api使用: 13 estimator = PCA(n_components=20) 14 pca_x_train = estimator.fit_transform(x_train) 15 pca_x_test = estimator.transform(x_test) 16 17 分別使用支持向量機進行學習降維前後的數據再預測 18 19 該數據集源自網上 https://archive.ics.uci.edu/ml/machine-learning-databases/optdigits/
20 我把他下載到了本地 21 訓練樣本3823條, 測試樣本1797條 22 圖像通過8*8像素矩陣表示共64個維度,1個目標維度表示數字類別 23 24 ‘‘‘ 25 26 # 1 準備數據 27 digits_train = pd.read_csv("./data/optdigits/optdigits.tra", header=None) 28 digits_test = pd.read_csv("./data/optdigits/optdigits.tes", header=None) 29 # 從樣本中抽取出64維度像素特征和1維度目標 30 x_train = digits_train[np.arange(64)]
31 y_train = digits_train[64] 32 x_test = digits_test[np.arange(64)] 33 y_test = digits_test[64] 34 35 # 2 對圖像數據進行降維,64維度降低到20維度 36 estimator = PCA(n_components=20) 37 pca_x_train = estimator.fit_transform(x_train) 38 pca_x_test = estimator.transform(x_test) 39 40 # 3.1 使用默認配置的支持向量機進行學習和預測未降維的數據 41 svc = LinearSVC() 42 # 學習 43 svc.fit(x_train, y_train) 44 # 預測 45 y_predict = svc.predict(x_test) 46 47 # 3.2 使用默認配置的支持向量機學習和預測降維後的數據 48 pca_svc = LinearSVC() 49 # 學習 50 pca_svc.fit(pca_x_train, y_train) 51 pca_y_predict = pca_svc.predict(pca_x_test) 52 53 # 4 模型評估 54 print("原始數據的準確率:", svc.score(x_test, y_test)) 55 print("其他評分:\n", classification_report(y_test, y_predict, target_names=np.arange(10).astype(str))) 56 57 print("降維後的數據準確率:", pca_svc.score(pca_x_test, y_test)) 58 print("其他評分:\n", classification_report(y_test, pca_y_predict, target_names=np.arange(10).astype(str))) 59 60 ‘‘‘ 61 原始數據的準確率: 0.9165275459098498 62 其他評分: 63 precision recall f1-score support 64 65 0 0.98 0.98 0.98 178 66 1 0.73 0.99 0.84 182 67 2 0.98 0.97 0.98 177 68 3 0.96 0.88 0.92 183 69 4 0.94 0.95 0.95 181 70 5 0.91 0.96 0.93 182 71 6 0.99 0.96 0.98 181 72 7 0.98 0.92 0.95 179 73 8 0.84 0.79 0.81 174 74 9 0.94 0.76 0.84 180 75 76 avg / total 0.92 0.92 0.92 1797 77 78 降維後的數據準確率: 0.9220923761825265 79 其他評分: 80 precision recall f1-score support 81 82 0 0.97 0.97 0.97 178 83 1 0.93 0.86 0.89 182 84 2 0.96 0.97 0.96 177 85 3 0.93 0.87 0.90 183 86 4 0.94 0.97 0.96 181 87 5 0.86 0.96 0.91 182 88 6 0.97 0.98 0.98 181 89 7 0.97 0.88 0.92 179 90 8 0.89 0.89 0.89 174 91 9 0.82 0.88 0.85 180 92 93 avg / total 0.92 0.92 0.92 1797 94 ‘‘‘

機器學習之路:python 特征降維 主成分分析 PCA