MENU

主成成分分析(PCA 降维)

February 1, 2019 • Read: 7033 • 数据挖掘与机器学习阅读设置

什么是主成分分析展开目录

主成分分析是多元线性统计里面的概念,它的英文是 Principal Components Analysis,简称 PCA。主成分分析旨在降低数据的维数,通过保留数据集中的主要成分来简化数据集。简化数据集在很多时候是非常必要的,因为复杂往往就意味着计算资源的大量消耗。通过对数据进行降维,我们就能在不较大影响结果的同时,减少模型学习时间

主成分分析的数学基原理非常简单,通过对协方差矩阵进行特征分解,从而得出主成分(特征向量)与对应的权值(特征值)。然后剔除那些较小特征值(较小权值)对应的特征,从而达到降低数据维数的目的

PCA 方法使用展开目录

介绍一下 scikit-learn 中 PCA 方法的参数定义及简单使用,这是完成 PCA 主成分分析的基础

  • from sklearn.decomposition import PCA
  • model = PCA(n_components = None, copy = True, whiten = False, svd_solver = 'auto')
  • n_components 表示需要保留主成分(特征)的数量
  • copy= 表示针对原始数据降维还是针对原始数据副本降维,False 表示针对原始数据
  • whiten= 白化表示将特征之间的相关性降低,并使得每个特征具有相同的方差
  • svd_solver= 表示奇异值分解 SVD 的方法。有 4 个参数,分别是:autofullarpackrandomized

在使用 PCA 降维时,通常也会使用到 PCA.fit() 方法。.fit()scikit-learn 训练模型的通用方法,但是该方法本身返回的是模型的参数。所以,通常我们会使用 PCA.fit_transform() 方法直接返回降维后的数据结果

  • import numpy as np
  • from sklearn.decomposition import PCA
  • data = np.array([
  • [1,2],
  • [3,4],
  • [5,6],
  • [7,8]
  • ]) # Create 2-dimensional array
  • new_data = PCA(n_components = 1).fit_transform(data) # Reduces dimensions to 1 and returns a value
  • print(data) # Output raw data
  • print(new_data) # Output the data after dimension reduction

输出结果如下:

  • [[1 2]
  • [3 4]
  • [5 6]
  • [7 8]]
  • [[ 4.24264069]
  • [ 1.41421356]
  • [-1.41421356]
  • [-4.24264069]]

手写数字识别聚类展开目录

手写数字数据集可以直接通过 scikit-learn 导入,无需外部下载,先输出前 5 张图像预览一下

  • from sklearn import datasets # Import Dataset package
  • import matplotlib.pyplot as plt
  • %matplotlib inline
  • # Load Datasets
  • digits_data = datasets.load_digits()
  • # Draw a grayscale map of the first five handwritten Numbers in the datasets
  • for index, image in enumerate(digits_data.images[:5]):
  • plt.subplot(2, 5, index + 1)
  • plt.imshow(image, cmap = plt.cm.gray_r, interpolation = 'nearest')
  • plt.show()

输出结果
应该能大致看出,上面的 5 张图像依次为 0、1、2、3、4

首先导入常用的 numpy 数值计算模块和 matplotlib 绘图模块。由于原数据集维度高达 64,所以这里需要进行 PCA 降维

  • from sklearn import decomposition
  • from sklearn.cluster import KMeans
  • # Load datasets
  • digits_data = datasets.load_digits()
  • X = digits_data.data
  • y = digits_data.target
  • # PCA Reduce the data to 2 dimensions
  • model = decomposition.PCA(n_components = 2)
  • reduce_data = model.fit_transform(X)

接下来,将降维后的数据聚为 10 类,并将聚类后的结果,聚类中心点,聚类决策边界绘制出来

  • # create K-Means model & input data
  • model = KMeans(n_clusters = 10)
  • model.fit(reduce_data)
  • # Calculate the decision boundary in the clustering process
  • x_min, x_max = reduce_data[:, 0].min() - 1, reduce_data[:, 0].max() + 1
  • y_min, y_max = reduce_data[:, 1].min() - 1, reduce_data[:, 1].max() + 1
  • xx, yy = np.meshgrid(np.arange(x_min, x_max, .05), np.arange(y_min, y_max, .05))
  • result = model.predict(np.c_[xx.ravel(), yy.ravel()])
  • # Draws the decision boundary
  • result = result.reshape(xx.shape)
  • plt.figure(figsize = (10, 5))
  • plt.contourf(xx, yy, result, cmap = plt.cm.Greys)
  • plt.scatter(reduce_data[:, 0], reduce_data[:, 1], c = y, s = 15)
  • # Draw the cluster center point
  • center = model.cluster_centers_
  • plt.scatter(center[:, 0], center[:, 1], marker = 'p', linewidths = 2,
  • color = 'b', edgecolors = 'w', zorder = 20)
  • # image paramters setting
  • plt.xlim(x_min, x_max)
  • plt.ylim(y_min, y_max)

结果如下图
图中,不同的色块区域代表一类,色块的颜色没有意义,只表示类别。散点代表数据,散点的颜色表示数据原始类别。虽然原始数据已经从 64 维降为 2 维,但某几个数字依旧有明显的成团现象。可以尝试降为 3 维,再进行聚类

Last Modified: December 13, 2021
Archives Tip
QR Code for this page
Tipping QR Code
Leave a Comment

已有 1 条评论
  1. 主成成分分析(PCA 降維) - 艾德資訊

    [...]Via www.wmathor.com[...]