PCA 实现:

参考博客:https://blog.csdn.net/u013719780/article/details/78352262

from __future__ import print_function
from sklearn import datasets
import matplotlib.pyplot as plt
import matplotlib.cm as cmx
import matplotlib.colors as colors
import numpy as np
# matplotlib inline def shuffle_data(X, y, seed=None):
if seed:
np.random.seed(seed) idx = np.arange(X.shape[0])
np.random.shuffle(idx) return X[idx], y[idx] # 正规化数据集 X
def normalize(X, axis=-1, p=2):
lp_norm = np.atleast_1d(np.linalg.norm(X, p, axis))
lp_norm[lp_norm == 0] = 1
return X / np.expand_dims(lp_norm, axis) # 标准化数据集 X
def standardize(X):
X_std = np.zeros(X.shape)
mean = X.mean(axis=0)
std = X.std(axis=0) # 做除法运算时请永远记住分母不能等于0的情形
# X_std = (X - X.mean(axis=0)) / X.std(axis=0)
for col in range(np.shape(X)[1]):
if std[col]:
X_std[:, col] = (X_std[:, col] - mean[col]) / std[col] return X_std # 划分数据集为训练集和测试集
def train_test_split(X, y, test_size=0.2, shuffle=True, seed=None):
if shuffle:
X, y = shuffle_data(X, y, seed) n_train_samples = int(X.shape[0] * (1-test_size))
x_train, x_test = X[:n_train_samples], X[n_train_samples:]
y_train, y_test = y[:n_train_samples], y[n_train_samples:] return x_train, x_test, y_train, y_test # 计算矩阵X的协方差矩阵
def calculate_covariance_matrix(X, Y=np.empty((0,0))):
if not Y.any():
Y = X
n_samples = np.shape(X)[0]
covariance_matrix = (1 / (n_samples-1)) * (X - X.mean(axis=0)).T.dot(Y - Y.mean(axis=0)) return np.array(covariance_matrix, dtype=float) # 计算数据集X每列的方差
def calculate_variance(X):
n_samples = np.shape(X)[0]
variance = (1 / n_samples) * np.diag((X - X.mean(axis=0)).T.dot(X - X.mean(axis=0)))
return variance # 计算数据集X每列的标准差
def calculate_std_dev(X):
std_dev = np.sqrt(calculate_variance(X))
return std_dev # 计算相关系数矩阵
def calculate_correlation_matrix(X, Y=np.empty([0])):
# 先计算协方差矩阵
covariance_matrix = calculate_covariance_matrix(X, Y)
# 计算X, Y的标准差
std_dev_X = np.expand_dims(calculate_std_dev(X), 1)
std_dev_y = np.expand_dims(calculate_std_dev(Y), 1)
correlation_matrix = np.divide(covariance_matrix, std_dev_X.dot(std_dev_y.T)) return np.array(correlation_matrix, dtype=float) class PCA():
"""
主成份分析算法PCA,非监督学习算法.
"""
def __init__(self):
self.eigen_values = None
self.eigen_vectors = None
self.k = 2 def transform(self, X):
"""
将原始数据集X通过PCA进行降维
"""
covariance = calculate_covariance_matrix(X) # 求解特征值和特征向量
self.eigen_values, self.eigen_vectors = np.linalg.eig(covariance) # 将特征值从大到小进行排序,注意特征向量是按列排的,即self.eigen_vectors第k列是self.eigen_values中第k个特征值对应的特征向量
idx = self.eigen_values.argsort()[::-1]
eigenvalues = self.eigen_values[idx][:self.k]
eigenvectors = self.eigen_vectors[:, idx][:, :self.k] # 将原始数据集X映射到低维空间
X_transformed = X.dot(eigenvectors) return X_transformed def main():
# Load the dataset
data = datasets.load_iris()
X = data.data
y = data.target # 将数据集X映射到低维空间
X_trans = PCA().transform(X) x1 = X_trans[:, 0]
x2 = X_trans[:, 1] print(X[0:2]) cmap = plt.get_cmap('viridis')
colors = [cmap(i) for i in np.linspace(0, 1, len(np.unique(y)))] class_distr = []
# Plot the different class distributions
for i, l in enumerate(np.unique(y)):
_x1 = x1[y == l]
_x2 = x2[y == l]
_y = y[y == l]
class_distr.append(plt.scatter(_x1, _x2, color=colors[i])) # Add a legend
plt.legend(class_distr, y, loc=1) # Axis labels
plt.xlabel('Principal Component 1')
plt.ylabel('Principal Component 2')
plt.show() if __name__ == "__main__":
main()

  

kPCA

1、核主成份分析 Kernel Principle Component Analysis:

1)现实世界中,并不是所有数据都是线性可分的
2)通过LDA,PCA将其转化为线性问题并不是好的方法

3)线性可分 VS 非线性可分

2、引入核主成份分析:

可以通过kPCA将非线性数据映射到高维空间,在高维空间下使用标准PCA将其映射到另一个低维空间

3、原理:
定义非线性映射函数,该函数可以对原始特征进行非线性组合,以将原始的d维数据集映射到更高维的k维特征空间。

1)多项式核
2)双曲正切核
3)径向基核(RBF),高斯核函数

基于RBF核的kPCA算法流程:

Python 代码:

from scipy.spatial.distance import pdist, squareform
from scipy import exp
from numpy.linalg import eigh
import numpy as np def rbf_kernel_pca(X, gamma, n_components):
"""
RBF kernel PCA implementation. Parameters
------------
X: {NumPy ndarray}, shape = [n_samples, n_features] gamma: float
Tuning parameter of the RBF kernel n_components: int
Number of principal components to return Returns
------------
X_pc: {NumPy ndarray}, shape = [n_samples, k_features]
Projected dataset """
# Calculate pairwise squared Euclidean distances
# in the MxN dimensional dataset.
sq_dists = pdist(X, 'sqeuclidean') # Convert pairwise distances into a square matrix.
mat_sq_dists = squareform(sq_dists) # Compute the symmetric kernel matrix.
K = exp(-gamma * mat_sq_dists) # Center the kernel matrix.
N = K.shape[0]
one_n = np.ones((N, N)) / N
K = K - one_n.dot(K) - K.dot(one_n) + one_n.dot(K).dot(one_n) # Obtaining eigenpairs from the centered kernel matrix
# numpy.linalg.eigh returns them in sorted order
eigvals, eigvecs = eigh(K) # Collect the top k eigenvectors (projected samples)
X_pc = np.column_stack((eigvecs[:, -i]
for i in range(1, n_components + 1))) return X_pc import matplotlib.pyplot as plt
from sklearn.datasets import make_moons X, y = make_moons(n_samples=100, random_state=123) plt.scatter(X[y == 0, 0], X[y == 0, 1], color='red', marker='^', alpha=0.5)
plt.scatter(X[y == 1, 0], X[y == 1, 1], color='blue', marker='o', alpha=0.5) plt.tight_layout()
# plt.savefig('./figures/half_moon_1.png', dpi=300)
plt.show() # 直接用PCA
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler scikit_pca = PCA(n_components=2)
X_spca = scikit_pca.fit_transform(X) fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(7, 3)) ax[0].scatter(X_spca[y == 0, 0], X_spca[y == 0, 1],
color='red', marker='^', alpha=0.5)
ax[0].scatter(X_spca[y == 1, 0], X_spca[y == 1, 1],
color='blue', marker='o', alpha=0.5) ax[1].scatter(X_spca[y == 0, 0], np.zeros((50, 1)) + 0.02,
color='red', marker='^', alpha=0.5)
ax[1].scatter(X_spca[y == 1, 0], np.zeros((50, 1)) - 0.02,
color='blue', marker='o', alpha=0.5) ax[0].set_xlabel('PC1')
ax[0].set_ylabel('PC2')
ax[1].set_ylim([-1, 1])
ax[1].set_yticks([])
ax[1].set_xlabel('PC1') plt.tight_layout()
# plt.savefig('./figures/half_moon_2.png', dpi=300)
plt.show() # KPCA from matplotlib.ticker import FormatStrFormatter X_kpca = rbf_kernel_pca(X, gamma=15, n_components=2) fig, ax = plt.subplots(nrows=1,ncols=2, figsize=(7,3))
ax[0].scatter(X_kpca[y==0, 0], X_kpca[y==0, 1],
color='red', marker='^', alpha=0.5)
ax[0].scatter(X_kpca[y==1, 0], X_kpca[y==1, 1],
color='blue', marker='o', alpha=0.5) ax[1].scatter(X_kpca[y==0, 0], np.zeros((50,1))+0.02,
color='red', marker='^', alpha=0.5)
ax[1].scatter(X_kpca[y==1, 0], np.zeros((50,1))-0.02,
color='blue', marker='o', alpha=0.5) ax[0].set_xlabel('PC1')
ax[0].set_ylabel('PC2')
ax[1].set_ylim([-1, 1])
ax[1].set_yticks([])
ax[1].set_xlabel('PC1')
ax[0].xaxis.set_major_formatter(FormatStrFormatter('%0.1f'))
ax[1].xaxis.set_major_formatter(FormatStrFormatter('%0.1f')) plt.tight_layout()
# plt.savefig('./figures/half_moon_3.png', dpi=300)
plt.show() #sklearn kpca from sklearn.decomposition import KernelPCA X, y = make_moons(n_samples=100, random_state=123)
scikit_kpca = KernelPCA(n_components=2, kernel='rbf', gamma=15)
X_skernpca = scikit_kpca.fit_transform(X) plt.scatter(X_skernpca[y == 0, 0], X_skernpca[y == 0, 1],
color='red', marker='^', alpha=0.5)
plt.scatter(X_skernpca[y == 1, 0], X_skernpca[y == 1, 1],
color='blue', marker='o', alpha=0.5) plt.xlabel('PC1')
plt.ylabel('PC2')
plt.tight_layout()
# plt.savefig('./figures/scikit_kpca.png', dpi=300)
plt.show()

  

参考: https://blog.csdn.net/weixin_40604987/article/details/79632888

PCA python 实现的更多相关文章

  1. 主成分分析 (PCA) 与其高维度下python实现(简单人脸识别)

    Introduction 主成分分析(Principal Components Analysis)是一种对特征进行降维的方法.由于观测指标间存在相关性,将导致信息的重叠与低效,我们倾向于用少量的.尽可 ...

  2. 机器学习笔记----四大降维方法之PCA(内带python及matlab实现)

    大家看了之后,可以点一波关注或者推荐一下,以后我也会尽心尽力地写出好的文章和大家分享. 本文先导:在我们平时看NBA的时候,可能我们只关心球员是否能把球打进,而不太关心这个球的颜色,品牌,只要有3D效 ...

  3. Python 主成分分析PCA

    主成分分析(PCA)是一种基于变量协方差矩阵对数据进行压缩降维.去噪的有效方法,PCA的思想是将n维特征映射到k维上(k<n),这k维特征称为主元,是旧特征的线性组合,这些线性组合最大化样本方差 ...

  4. 三种方法实现PCA算法(Python)

    主成分分析,即Principal Component Analysis(PCA),是多元统计中的重要内容,也广泛应用于机器学习和其它领域.它的主要作用是对高维数据进行降维.PCA把原先的n个特征用数目 ...

  5. Python机器学习:5.6 使用核PCA进行非线性映射

    许多机器学习算法都有一个假设:输入数据要是线性可分的.感知机算法必须针对完全线性可分数据才能收敛.考虑到噪音,Adalien.逻辑斯蒂回归和SVM并不会要求数据完全线性可分. 但是现实生活中有大量的非 ...

  6. Python机器学习笔记 使用scikit-learn工具进行PCA降维

    之前总结过关于PCA的知识:深入学习主成分分析(PCA)算法原理.这里打算再写一篇笔记,总结一下如何使用scikit-learn工具来进行PCA降维. 在数据处理中,经常会遇到特征维度比样本数量多得多 ...

  7. 深入学习主成分分析(PCA)算法原理(Python实现)

    一:引入问题 首先看一个表格,下表是某些学生的语文,数学,物理,化学成绩统计: 首先,假设这些科目成绩不相关,也就是说某一科目考多少分与其他科目没有关系,那么如何判断三个学生的优秀程度呢?首先我们一眼 ...

  8. 【转】利用python的KMeans和PCA包实现聚类算法

    转自:https://www.cnblogs.com/yjd_hycf_space/p/7094005.html 题目: 通过给出的驾驶员行为数据(trip.csv),对驾驶员不同时段的驾驶类型进行聚 ...

  9. [机器学习笔记]主成分分析PCA简介及其python实现

    主成分分析(principal component analysis)是一种常见的数据降维方法,其目的是在“信息”损失较小的前提下,将高维的数据转换到低维,从而减小计算量. PCA的本质就是找一些投影 ...

随机推荐

  1. SCADA系统构架的安全分析总结

    概念: SCADA 数据采集与监控 Supervisory Control And Data Acquisition  .包括了计算机设备  工业控制组件    网络 组成部件 ,SCADA 系统被用 ...

  2. 批处理引擎MapReduce编程模型

    批处理引擎MapReduce编程模型 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. MapReduce是一个经典的分布式批处理计算引擎,被广泛应用于搜索引擎索引构建,大规模数据处理 ...

  3. sqlite3入门之sqlite3_open,sqlite3_exec,slite3_close

    sqlite3_open sqlite3_open函数原型: int sqlite3_open( const char *filename, /* Database filename (UTF-8) ...

  4. flask 关于get、post的写法

    一. get 方法获取入参方法  request.args.get 地址: 127.0.0.1:5000/test?arg1=1&arg2=2 如图: 二. pots方法获取入参方法类型比较多 ...

  5. PHP——json_encode转码保留中文

    前言 特殊的情况,特殊对待吧.转码为GBK再json_encode会报错,因为json_encode是只支持utf8的. 代码 文档 | https://www.php.net/manual/en/f ...

  6. centos7下用命令安装node&pm2

    一.下载node安装包 1.wget https://npm.taobao.org/mirrors/node/latest-v12.x/node-v12.4.0-linux-x64.tar.gz 二. ...

  7. java中的String要点解析

    String类使我们经常使用的一个类,经常用来表示字符串常量. 字符串一旦被创建赋值,就不能被改变,因为String 底层是数组实现的,且被定义成final类型.我们可以看String源码. /** ...

  8. c#调用CMD编辑命令

    对于C#通过程序来调用cmd命令的操作,网上有很多类似的文章,但很多都不行,竟是漫天的拷贝.我自己测试整理了一下. 代码: string str = Console.ReadLine(); Syste ...

  9. sql server 行转列和列转行的使用

    1: 行转列 子查询,获取一定数据集结果 SELECT objid,action,count(1) AS [count] FROM T_MyAttention WHERE objid IN(SELEC ...

  10. C# 模式匹配

    最近在使用vs编码时,重构提示:模式匹配 Element view = bindable as Element; if (view == null) { return; } 运用模式匹配可以简写为: ...