机器学习-特征抽取-核主成分法-Kernel Principal Component(KPCA)

Section I: Brief Introduction on KPCA

Performing a nonlinear mapping via Kernel PCA that transforms the data onto a higher-dimensional space. Then, a standard PCA in this higher-dimensional space to project the data back onto a lower-dimensional space where the samples can be separated by a linear classifier (under the condition that the samples can be separated by density in the input space). However, one downside of this approach is that it is computationally very expensive, and this is where kernel trick is adopted here. The key point lies in that using kernel function, the similarity between two-dimensional feature vectors can be still computed in the original feature space.

FROM
Sebastian Raschka, Vahid Mirjalili. Python机器学习第二版. 南京:东南大学出版社,2018.

Section II: Call KPCA in Sklearn

第一部分:代码

import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
from PCA.visualize import plot_decision_regions

#Section 1: Prepare data
plt.rcParams['figure.dpi']=200
plt.rcParams['savefig.dpi']=200
font = {'family': 'Times New Roman',
        'weight': 'light'}
plt.rc("font", **font)

#Section 2: Load data and split it into train/test dataset
from sklearn.datasets import make_moons

X,y=make_moons(n_samples=100,random_state=12)
plt.scatter(X[y==0,0],X[y==0,1],color='red',marker='^',alpha=0.5,label='Triangle')
plt.scatter(X[y==1,0],X[y==1,1],color='blue',marker='o',alpha=0.5,label='Circle')
plt.legend(loc='best')
plt.xlabel("Feature X")
plt.ylabel('Feature Y')
plt.title("Original Moon Distribution")
plt.savefig('./fig1.png')
plt.show()

#Section 3: Kernal princial component analysis via Sklearn
from sklearn.decomposition import KernelPCA
kpca=KernelPCA(n_components=2,kernel='rbf',gamma=15)
X_kpca=kpca.fit_transform(X)
plt.scatter(X_kpca[y==0,0],X_kpca[y==0,1],color='red',marker='^',alpha=0.5,label='Triangle')
plt.scatter(X_kpca[y==1,0],X_kpca[y==1,1],color='blue',marker='o',alpha=0.5,label='Circle')
plt.legend(loc='best')
plt.title("Moon Distribution After KPCA Adopted")
plt.xlabel("After Transformed,Feature X")
plt.ylabel('After Transformed,Feature Y')
plt.savefig('./fig2.png')
plt.show()

第二部分:结果

下图分别为原始Moon的特征分布和采用KPCA后,Moon的特征分布。对比可以得知,采用KPCA将原始空间映射到可划分的高维空间后,进而采取主成分法降维后,所获取的两位特征,显然可以将该问题转变为线性可分的问题。
在这里插入图片描述
在这里插入图片描述
参考文献
Sebastian Raschka, Vahid Mirjalili. Python机器学习第二版. 南京:东南大学出版社,2018.

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
核主元分析KPCA的降维特征提取以及故障检测应用-KPCA_v2.zip 本帖最后由 iqiukp 于 2018-11-9 15:02 编辑      核主元分析(Kernel principal component analysis ,KPCA)在降维、特征提取以及故障检测中的应用。主要功能有:(1)训练数据和测试数据的非线性主元提取(降维、特征提取) (2)SPE和T2统计量及其控制限的计算 (3)故障检测 参考文献: Lee J M, Yoo C K, Choi S W, et al. Nonlinear process monitoring using kernel principal component analysis[J]. Chemical engineering science, 2004, 59: 223-234. 1. KPCA的建模过程(故障检测): (1)获取训练数据(工业过程数据需要进行标准化处理) (2)计算核矩阵 (3)核矩阵中心化 (4)特征值分解 (5)特征向量的标准化处理 (6)主元个数的选取 (7)计算非线性主成分(即降维结果或者特征提取结果) (8)SPE和T2统计量的控制限计算 function model = kpca_train % DESCRIPTION % Kernel principal component analysis % %       mappedX = kpca_train % % INPUT %   X            Training samples %                N: number of samples %                d: number of features %   options      Parameters setting % % OUTPUT %   model        KPCA model % % % Created on 9th November, 2018, by Kepeng Qiu. % number of training samples L = size; % Compute the kernel matrix K = computeKM; % Centralize the kernel matrix unit = ones/L; K_c = K-unit*K-K*unit unit*K*unit; % Solve the eigenvalue problem [V,D] = eigs; lambda = diag; % Normalize the eigenvalue V_s = V ./ sqrt'; % Compute the numbers of principal component % Extract the nonlinear component if options.type == 1 % fault detection     dims = find) >= 0.85,1, 'first'); else     dims = options.dims; end mappedX  = K_c* V_s ; % Store the results model.mappedX =  mappedX ; model.V_s = V_s; model.lambda = lambda; model.K_c = K_c; model.L = L; model.dims = dims; model.X = X; model.K = K; model.unit = unit; model.sigma = options.sigma; % Compute the threshold model.beta = options.beta;% corresponding probabilities [SPE_limit,T2_limit] = comtupeLimit; model.SPE_limit = SPE_limit; model.T2_limit = T2_limit; end复制代码2. KPCA的测试过程: (1)获取测试数据(工业过程数据需要利用训练数据的均值和标准差进行标准化处理) (2)计算核矩阵 (3)核矩阵中心化 (4)计算非线性主成分(即降维结果或者特征提取结果) (5)SPE和T2统计量的计算 function [SPE,T2,mappedY] = kpca_test % DESCRIPTION % Compute the T2 statistic, SPE statistic,and the nonlinear component of Y % %       [SPE,T2,mappedY] = kpca_test % % INPUT %   model       KPCA model %   Y           test data % % OUTPUT %   SPE         the SPE statistic %   T2          the T2 statistic %   mappedY     the nonlinear component of Y % % Created on 9th November, 2018, by Kepeng Qiu. % Compute Hotelling's T2 statistic % T2 = diag)*model.mappedX'); % the number of test samples L = size; % Compute the kernel matrix Kt = computeKM; % Centralize the kernel matrix unit = ones/model.L; Kt_c = Kt-unit*model.K-Kt*model.unit unit*model.K*model.unit; % Extract the nonlinear component mappedY = Kt_c*model.V_s; % Compute Hotelling's T2 statistic T2 = diag)*mappedY'); % Compute the squared prediction error SPE = sum.^2,2)-sum; end复制代码 3. demo1: 降维、特征提取 源代码 % Demo1: dimensionality reduction or feature extraction % ---------------------------------------------------------------------% clc clear all close all addpath) % 4 circles load circledata % X = circledata; for i = 1:4     scatter:250*i,1),X:250*i,2))     hold on end % Parameters setting options.sigma = 5;   % kernel width options.dims  = 2;   % output dimension options.type  = 0;   % 0:dimensionality reduction or feature extraction                      % 1:fault detection options.beta  = 0.9; % corresponding probabilities options.cpc  = 0.85; % Principal contribution rate % Train KPCA model model = kpca_train; figure for i = 1:4     scatter:250*i,1), ...         model.mappedX:250*i,2))     hold on end 复制代码(2)结果 (分别为原图和特征提取后的图) demo1-1.png demo1-2.png 4. demo2: 故障检测(需要调节核宽度、主元贡献率和置信度等参数来提高故障检测效果) (1)源代码 % Demo2: Fault detection % X: training samples % Y: test samples % Improve the performance of fault detection by adjusting parameters % 1. options.sigma = 16;   % kernel width % 2. options.beta          % corresponding probabilities % 3. options.cpc  ;        % principal contribution rate % ---------------------------------------------------------------------% clc clear all close all addpath) % X = rand; Y = rand; Y = rand 3; Y = rand*3; % Normalization % mu = mean; % st = std; % X = zscore; % Y = bsxfun,st); % Parameters setting options.sigma = 16;   % kernel width options.dims  = 2;   % output dimension options.type  = 1;   % 0:dimensionality reduction or feature extraction                      % 1:fault detection options.beta  = 0.9; % corresponding probabilities options.cpc  = 0.85; % principal contribution rate % Train KPCA model model = kpca_train; % Test a new sample Y [SPE,T2,mappedY] = kpca_test; % Plot the result plotResult; plotResult; 复制代码(2)结果(分别是SPE统计量和T2统计量的结果图) demo2-1.png demo2-2.png    附件是基于KPCA的降维、特征提取和故障检测程序源代码。如有错误的地方请指出,谢谢。 Kernel Principal Component Analysis .zip KPCA
核主元分析KPCA的降维特征提取以及故障检测应用-Kernel Principal Component Analysis .zip 本帖最后由 iqiukp 于 2018-11-9 15:02 编辑      核主元分析(Kernel principal component analysis ,KPCA)在降维、特征提取以及故障检测中的应用。主要功能有:(1)训练数据和测试数据的非线性主元提取(降维、特征提取) (2)SPE和T2统计量及其控制限的计算 (3)故障检测 参考文献: Lee J M, Yoo C K, Choi S W, et al. Nonlinear process monitoring using kernel principal component analysis[J]. Chemical engineering science, 2004, 59: 223-234. 1. KPCA的建模过程(故障检测): (1)获取训练数据(工业过程数据需要进行标准化处理) (2)计算核矩阵 (3)核矩阵中心化 (4)特征值分解 (5)特征向量的标准化处理 (6)主元个数的选取 (7)计算非线性主成分(即降维结果或者特征提取结果) (8)SPE和T2统计量的控制限计算 function model = kpca_train % DESCRIPTION % Kernel principal component analysis % %       mappedX = kpca_train % % INPUT %   X            Training samples %                N: number of samples %                d: number of features %   options      Parameters setting % % OUTPUT %   model        KPCA model % % % Created on 9th November, 2018, by Kepeng Qiu. % number of training samples L = size; % Compute the kernel matrix K = computeKM; % Centralize the kernel matrix unit = ones/L; K_c = K-unit*K-K*unit unit*K*unit; % Solve the eigenvalue problem [V,D] = eigs; lambda = diag; % Normalize the eigenvalue V_s = V ./ sqrt'; % Compute the numbers of principal component % Extract the nonlinear component if options.type == 1 % fault detection     dims = find) >= 0.85,1, 'first'); else     dims = options.dims; end mappedX  = K_c* V_s ; % Store the results model.mappedX =  mappedX ; model.V_s = V_s; model.lambda = lambda; model.K_c = K_c; model.L = L; model.dims = dims; model.X = X; model.K = K; model.unit = unit; model.sigma = options.sigma; % Compute the threshold model.beta = options.beta;% corresponding probabilities [SPE_limit,T2_limit] = comtupeLimit; model.SPE_limit = SPE_limit; model.T2_limit = T2_limit; end复制代码2. KPCA的测试过程: (1)获取测试数据(工业过程数据需要利用训练数据的均值和标准差进行标准化处理) (2)计算核矩阵 (3)核矩阵中心化 (4)计算非线性主成分(即降维结果或者特征提取结果) (5)SPE和T2统计量的计算 function [SPE,T2,mappedY] = kpca_test % DESCRIPTION % Compute the T2 statistic, SPE statistic,and the nonlinear component of Y % %       [SPE,T2,mappedY] = kpca_test % % INPUT %   model       KPCA model %   Y           test data % % OUTPUT %   SPE         the SPE statistic %   T2          the T2 statistic %   mappedY     the nonlinear component of Y % % Created on 9th November, 2018, by Kepeng Qiu. % Compute Hotelling's T2 statistic % T2 = diag)*model.mappedX'); % the number of test samples L = size; % Compute the kernel matrix Kt = computeKM; % Centralize the kernel matrix unit = ones/model.L; Kt_c = Kt-unit*model.K-Kt*model.unit unit*model.K*model.unit; % Extract the nonlinear component mappedY = Kt_c*model.V_s; % Compute Hotelling's T2 statistic T2 = diag)*mappedY'); % Compute the squared prediction error SPE = sum.^2,2)-sum; end复制代码 3. demo1: 降维、特征提取 源代码 % Demo1: dimensionality reduction or feature extraction % ---------------------------------------------------------------------% clc clear all close all addpath) % 4 circles load circledata % X = circledata; for i = 1:4     scatter:250*i,1),X:250*i,2))     hold on end % Parameters setting options.sigma = 5;   % kernel width options.dims  = 2;   % output dimension options.type  = 0;   % 0:dimensionality reduction or feature extraction                      % 1:fault detection options.beta  = 0.9; % corresponding probabilities options.cpc  = 0.85; % Principal contribution rate % Train KPCA model model = kpca_train; figure for i = 1:4     scatter:250*i,1), ...         model.mappedX:250*i,2))     hold on end 复制代码(2)结果 (分别为原图和特征提取后的图) demo1-1.png demo1-2.png 4. demo2: 故障检测(需要调节核宽度、主元贡献率和置信度等参数来提高故障检测效果) (1)源代码 % Demo2: Fault detection % X: training samples % Y: test samples % Improve the performance of fault detection by adjusting parameters % 1. options.sigma = 16;   % kernel width % 2. options.beta          % corresponding probabilities % 3. options.cpc  ;        % principal contribution rate % ---------------------------------------------------------------------% clc clear all close all addpath) % X = rand; Y = rand; Y = rand 3; Y = rand*3; % Normalization % mu = mean; % st = std; % X = zscore; % Y = bsxfun,st); % Parameters setting options.sigma = 16;   % kernel width options.dims  = 2;   % output dimension options.type  = 1;   % 0:dimensionality reduction or feature extraction                      % 1:fault detection options.beta  = 0.9; % corresponding probabilities options.cpc  = 0.85; % principal contribution rate % Train KPCA model model = kpca_train; % Test a new sample Y [SPE,T2,mappedY] = kpca_test; % Plot the result plotResult; plotResult; 复制代码(2)结果(分别是SPE统计量和T2统计量的结果图) demo2-1.png demo2-2.png    附件是基于KPCA的降维、特征提取和故障检测程序源代码。如有错误的地方请指出,谢谢。 Kernel Principal Component Analysis .zip KPCA

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值