如何利用PCA(Principal component analysis)来简化数据

本博文的的内容为以下:

  • 降维技术
  • 主成分分析(PCA)
  • 对半导体数据进行降维处理

降维(dimensionality reduction)的目标就是对输入的数目进行消减,由此剔除数据中的噪声并提高机器学习方法的性能。

本博文是涉及降维主题的两章中的第一章。在降维中,我们对数据进行了预处理。之后,采用 其他机器学习技术对其进行处理。本博文一开始对降维技术进行了综述,然后集中介绍一种应用非 常普遍的称为主成分分析的技术。最后,我们就通过一个数据集的例子来展示PCA的工作过程。 经过PCA处理之后,该数据集就从590个特征降低到了6个特征。

13.1 降维技术

数据显示并非大规模特征下的唯一难题,对数据进行简化还有如下一系列的原因:

  • 使用数据集合更容易使用。
  • 降低很多算法的计算开销
  • 去除噪声
  • 使得结果易懂

在已标注和未标注的数据上都有降维技术。我们主要考虑未标注数据上的降维技术,该技术同时也可以应用于已标注的数据。

第一种降维的方法称为主成分分析(Principal Component Analysis,PCA)

在PCA中,数据 从原来的坐标系转换到了新的坐标系,新坐标系的选择是由数据本身决定的。第一个新坐标轴选 择的是原始数据中方差最大的方向,第二个新坐标轴的选择和第一个坐标轴正交且具有最大方差 的方向。该过程一直重复,重复次数为原始数据中特征的数目。

另外一种降维技术是因子分析(Factor Analysis)。在因子分析中,我们假设在观察数据的生 成中有一些观察不到的隐变量(latent variable)。假设观察数据是这些隐变量和某些噪声的线性 组合。那么隐变量的数据可能比观察数据的数目少,也就是说通过找到隐变量就可以实现数据的 降维。因子分析已经应用于社会科学、金融和其他领域中了。

还有一种降维技术就是独立成分分析(Independent Component Analysis,ICA)。ICA假设数 据是从N个数据源生成的,这一点和因子分析有些类似。假设数据为多个数据源的混合观察结果, 这些数据源之间在统计上是相互独立的,而在PCA中只假设数据是不相关的。同因子分析一样, 如果数据源的数目少于观察数据的数目,则可以实现降维过程。

在上述3种降维技术中,PCA的应用目前最为广泛,因此本博文主要关注PCA。

13.2 PCA (Principal component analysis)

 13.2.1移动坐标轴 (Moving the coordinate axes)

在PCA中,我们对 数据的坐标进行了旋转,该旋转的过程取决于数据的本身。第一条坐标轴旋转到覆盖数据的最大方差位置,即图中的直线B。数据的最大方差给出了数据的最重要的信息。

 通过PCA (主成分析法) 进行降维处理,就可以同时获得SVM和决策树的优点:

  • 得到了和决策树一样简单的分类器,同时分类间隔和SVM一样好。
  • 另外,数据通过比SVM简单得多的方法进行采用规则进行区分。

 我们只需要一维信息即可,因为另一维信息只是对分类缺乏贡献的噪声数据。 在二维平面下,这一点看上去微不足道,但是如果在高维空间下则意义重大。

接下来就可以通过代码来实现PCA过程。前 面我曾提到的第一个主成分就是从数据差异性最大(即方差最大)的方向提取出来的,第二个主 成分则来自于数据差异性次大的方向,并且该方向与第一个主成分方向正交。通过数据集的协方 差矩阵及其特征值分析,我们就可以求得这些主成分的值。

13.2.2 在NumPy中实现PCA

将数据转换成前N个主成分的伪代码大致如下:

  • 去除平均值
  • 计算协方差矩阵
  • 计算协方差矩阵的特征值和特征向量
  • 将特征值从大到小排序
  • 保留最上面的N个特征向量
  • 将数据转换到上述N个特征向量构建的新空间中

The code for The PCA algorithm:

import numpy as np

# The function loadDataSet() is slightly different,because it use two list comprehensions to create the matrix.
def loadDataSet(fileName, delim='\t'):
    fr = open(fileName)
    stringArr = [line.strip().split(delim) for line in fr.readlines()]
    datArr = [list(map(float,line)) for line in stringArr]
    return np.mat(datArr)
# the pca function takes two arguments : the dataset which we'll perform PCA and 
# the second optional argument,topNfeat, which is the top N features to use.
def pca(dataMat, topNfeat=9999999):
    meanVals = np.mean(dataMat, axis=0)  # calculate the mean of the original dataset and remove it.
    meanRemoved = dataMat - meanVals # Remove mean
    covMat = np.cov(meanRemoved,rowvar=0) # compute the covariance matrix and calculate the eigenvalues.
    eigVals,eigVects = np.linalg.eig(np.mat(covMat))
    eigValInd = np.argsort(eigVals) # use argsort() to get the order of the eigenValues
    eigValInd = eigValInd[:-(topNfeat+1):-1] # Sort top N smallest to largest
    redEigVects = eigVects[:,eigValInd] # Transform data into new dimensions
    lowDDataMat = meanRemoved * redEigVects
    reconMat = (lowDDataMat * redEigVects.T) + meanVals
    return lowDDataMat,reconMat

def replaceNanWithMean(): 
    datMat = loadDataSet('secom.data', ' ')
    numFeat = np.shape(datMat)[1]
    for i in range(numFeat):
        meanVal = np.mean(datMat[np.nonzero(~np.isnan(datMat[:,i].A))[0],i]) #values that are not NaN (a number)
        datMat[np.nonzero(np.isnan(datMat[:,i].A))[0],i] = meanVal  #set NaN values to mean
    return datMat

 

 The reconstructed data should overlap the original data because no features are removed.

 13.3 示例: 利用PCA对半导体制造数据降维

一些工程上的通用解决方案是通过早期测试和频繁测试来发现有缺陷的产品,但仍然有一些 存在瑕疵的产品通过了测试。如果机器学习技术能够用于进一步减少错误,那么它就会为制造商 节省大量的资金。

该数据包含很多的缺失值。这些缺失值是以NaN(Not a Number的缩写)标识的。

def replaceNanWithMean():
    datMat = loadDataSet('secom.data')
    numFeat = np.shape(datMat)[1]
    for i in range(numFeat):
        meanVal = np.mean(datMat[np.nonzero(~np.isnan(datMat[:,i].A))[0],i]) # find mean of non-NaN values
        datMat[np.nonzero(np.isnan(datMat[:,i].A))[0],i] = meanVal # Set NaN values to mean
    return datMat

 

 The source code from pca.py as below:

import numpy as np

# The function loadDataSet() is slightly different,because it use two list comprehensions to create the matrix.
def loadDataSet(fileName, delim='\t'):
    fr = open(fileName)
    stringArr = [line.strip().split(delim) for line in fr.readlines()]
    datArr = [list(map(float,line)) for line in stringArr]
    return np.mat(datArr)
# the pca function takes two arguments : the dataset which we'll perform PCA and 
# the second optional argument,topNfeat, which is the top N features to use.
def pca(dataMat, topNfeat=9999999):
    meanVals = np.mean(dataMat, axis=0)  # calculate the mean of the original dataset and remove it.
    meanRemoved = dataMat - meanVals # Remove mean
    covMat = np.cov(meanRemoved,rowvar=0) # compute the covariance matrix and calculate the eigenvalues.
    eigVals,eigVects = np.linalg.eig(np.mat(covMat))
    eigValInd = np.argsort(eigVals) # use argsort() to get the order of the eigenValues
    eigValInd = eigValInd[:-(topNfeat+1):-1] # Sort top N smallest to largest
    redEigVects = eigVects[:,eigValInd] # Transform data into new dimensions
    lowDDataMat = meanRemoved * redEigVects
    reconMat = (lowDDataMat * redEigVects.T) + meanVals
    return lowDDataMat,reconMat

def replaceNanWithMean(): 
    datMat = loadDataSet('secom.data', ' ')
    numFeat = np.shape(datMat)[1]
    for i in range(numFeat):
        meanVal = np.mean(datMat[np.nonzero(~np.isnan(datMat[:,i].A))[0],i]) #values that are not NaN (a number)
        datMat[np.nonzero(np.isnan(datMat[:,i].A))[0],i] = meanVal  #set NaN values to mean
    return datMat

def replaceNanWithMean():
    datMat = loadDataSet('secom.data')
    numFeat = np.shape(datMat)[1]
    for i in range(numFeat):
        meanVal = np.mean(datMat[np.nonzero(~np.isnan(datMat[:,i].A))[0],i]) # find mean of non-NaN values
        datMat[np.nonzero(np.isnan(datMat[:,i].A))[0],i] = meanVal # Set NaN values to mean
    return datMat

 13.4 Summary

Dimensionality reduction techniques allow us to make data easier to use and often remove noise to make other machine learning tasks more accurate. It’s often a preprocessing step that can be done to clean up data before applying it to some other algorithm. A number of techniques can be used to reduce the dimensionality of our data. Among these, independent component analysis, factor analysis, and principal component analysis are popular methods. The most widely used method is principal component analysis.

Principal component analysis allows the data to identify the important features. It does this by rotating the axes to align with the largest variance in the data. Other axes are chosen orthogonal to the first axis in the direction of largest variance. Eigenvalue analysis on the covariance matrix can be used to give us a set of orthogonal axes. The PCA algorithm in this chapter loads the entire dataset into memory. If this isn’t possible, other methods for finding the eigenvalues can be used. A good paper for an online method of finding the PCA is “Incremental Eigenanalysis for Classification.”2 The singular value decomposition, which is the subject of the next chapter, can also be used for eigenvalue analysis.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值