机器学习实验(二)

实验二 PCA降维

一、实验目的

  1. 理解和掌握PCA原理

  2. 利用PCA降维,辅助完成一项实战内容。

二、实验原理

对于矩阵A,有一组特征向量v,将这组向量进行正交化单位化,就能得到一组正交单位向量。特征值分解的工作就是就是将矩阵A分解为如下所示三个矩阵的乘积:
Λ = Q − 1 AQ = Q T AQ {\bf \Lambda} = \textbf Q^{-1}\textbf A \textbf Q = \textbf Q^{T}\textbf A\textbf Q Λ=Q1AQ=QTAQ
其中,Q是矩阵A的特征向量组成的矩阵, Λ \Lambda Λ则是一个对角阵,其对角线上的元素就是特征值。

矩阵的主成分就是其协方差矩阵对应的特征向量,按照对应的特征值大小进行排序,最大的特征值就是第一主成分,其次是第二主成分,以此类推。

三、算法流程

输入

样本集 D = { x 1 , x 2 , … … x m } D = \{x_1,x_2,……x_m\} D={x1,x2,xm}

低维空间维数 d t d^t dt

过程

  1. 对所有样本进行中心化: x i ← x i − 1 m ∑ i = 1 m x i x_i \leftarrow x_i - \frac 1m \sum^m_{i = 1} x_i xixim1i=1mxi;
  2. 计算样本的协方差矩阵 XX T \textbf {XX}^T XXT;
  3. 对协方差矩阵 XX T \textbf {XX}^T XXT 做特征值分解;
  4. 取最大的 d t d^t dt 个特征值所对应的特征向量 w 1 , w 2 , … … , w d t w_1,w_2,……,w_{d^t} w1,w2,,wdt.

输出

投影矩阵 W = ( w 1 , w 2 , … … , w d t ) \textbf W = (w_1,w_2,……,w_{d^t}) W=(w1,w2,,wdt).

人脸识别步骤

  1. 利用给定的数据集,执行上述算法,得到投影矩阵 W \textbf W W;

  2. 计算训练集的投影后的矩阵: P = WX \textbf P = \textbf {WX} P=WX;

  3. 加载一个测试图片 T T T,测试图片投影后的矩阵为: TestT = WT \textbf {TestT} = \textbf{WT} TestT=WT;

  4. 计算 T e s t T \bf TestT TestT P P P 中每个样本距离,选出最近的那个即可。

  5. 显示投影前后的两张图片。

四、代码和执行结果展示

编写代码

使用 lfw_people 数据集中的人脸照片作为训练集

from time import time
import logging
import matplotlib.pyplot as plt

from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.datasets import fetch_lfw_people
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.decomposition import PCA
from sklearn.svm import SVC

logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')
lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)
n_samples, h, w = lfw_people.images.shape

X = lfw_people.data
n_features = X.shape[1]

y = lfw_people.target
target_names = lfw_people.target_names
n_classes = target_names.shape[0]

print("Total dataset size:")
print("n_samples: %d" % n_samples)
print("n_features: %d" % n_features)
print("n_classes: %d" % n_classes)

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=42)
n_components = 150

print("Extracting the top %d eigenfaces from %d faces"
      % (n_components, X_train.shape[0]))
t0 = time()
pca = PCA(n_components=n_components, svd_solver='randomized',
          whiten=True).fit(X_train)
eigenfaces = pca.components_.reshape((n_components, h, w))

print("Projecting the input data on the eigenfaces orthonormal basis")
t0 = time()
X_train_pca = pca.transform(X_train)
X_test_pca = pca.transform(X_test)
print("done in %0.3fs" % (time() - t0))
print("Fitting the classifier to the training set")
t0 = time()
param_grid = {'C': [1e3, 5e3, 1e4, 5e4, 1e5],
              'gamma': [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.1], }

clf = GridSearchCV(
    SVC(kernel='rbf', class_weight='balanced'), param_grid)
clf = clf.fit(X_train_pca, y_train)
t0 = time()
y_pred = clf.predict(X_test_pca)

print(classification_report(y_test, y_pred, target_names=target_names))
print(confusion_matrix(y_test, y_pred, labels=range(n_classes)))

def plot_gallery(images, titles, h, w, n_row=3, n_col=4):
    plt.figure(figsize=(1.8 * 2, 2.4 * 1))
    plt.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35)
    for i in range(2):
        plt.subplot(1, 2, i + 1)
        plt.imshow(images[i].reshape((h, w)), cmap=plt.cm.gray)
        plt.title(titles[i], size=12)
        plt.xticks(())
        plt.yticks(())

def title(y_pred, y_test, target_names, i):
    pred_name = target_names[y_pred[i]].rsplit(' ', 1)[-1]
    true_name = target_names[y_test[i]].rsplit(' ', 1)[-1]
    return '%s' % (true_name)

prediction_titles = [title(y_pred, y_test, target_names, i)
                     for i in range(y_pred.shape[0])]

plot_gallery(X_test, prediction_titles, h, w)
plt.show()

样例测试

未完待续

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值