# -*- coding: utf-8 -*-
"""
Created on Fri Jun 12 10:43:37 2020
@author: 55024
核主成分分析法,应对样本数据线性不可分的情况。将数据投射到高维空间,使得数据线性可分,用核技巧
在低维计算高维投射,之后再用PCA把维度降低,可将无穷维降到二维
下面和学习过程相反,先上干活,直接从sklearn导入包,再手工制作体会理论基础
程序来源机器学习书源代码第五章后半部分
"""
from sklearn.decomposition import KernelPCA
import matplotlib.pyplot as plt
from sklearn.datasets import make_moons
X, y = make_moons(n_samples=100, random_state=123) #这是产生半月形的数据集产生代码
scikit_kpca = KernelPCA(n_components=2, kernel='rbf', gamma=15)#这就是KPCA
X_skernpca = scikit_kpca.fit_transform(X) #这是经过投射高维,又降维的新数据
#下面是画图,表示这种KPCA方法,可以投射到线性可分的空间
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('images/05_19.png', dpi=300)
plt.show()
#'''
#以下是手工制作的过程,是根据数学理论推导,一点一点做的
#不同于上述的集成包一步到位,但可以证明结果是一样的
#'''
#from scipy.spatial.distance import pdist, squareform #导入算距离的函数
#from scipy.linalg import eigh #导入算特征值和特征向量的函数
#import numpy as np
#
#def rbf_kernel_pca(X, gamma, n_components): #参数,原始数据,核函数的gamma,取前几个主成分
# """
# 一堆样本投射到很高维(从而在新的特征空间线性可分),然后用PCA去降维
# RBF kernel PCA implementation.
#
# Parameters
# ------------
# X: {NumPy ndarray}, shape = [n_examples, 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_examples, k_features]
# Projected dataset 返回已经降维,并且已经投射过的数据。相当于在kernel的世界里做的降维
#
# """
# # 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 = np.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
# # scipy.linalg.eigh returns them in ascending order
# eigvals, eigvecs = eigh(K) #求出特征根,特征向量,但是预设由小排到大
# eigvals, eigvecs = eigvals[::-1], eigvecs[:, ::-1] #次序对调,从大排到小
#
# # Collect the top k eigenvectors (projected examples)
# X_pc = np.column_stack([eigvecs[:, i] #将要的前面几列特征向量拿出来
# for i in range(n_components)])
# #上面求出的向量是A而不是V,因为无穷维太高,无法直接求V,降V转化为了A和kernel的乘积加总,这里实际求出的是A,见书P588
# #a的长度不是1电脑直接变成1,其实是v长度为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) #画一百个点,固定随机数种子,X是100*2,y是100*1
#
#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('images/05_12.png', dpi=300)
#plt.show()
#
#'''使用传统的PCA做,结果发现投射后的数据仍有部分重叠,无论怎么旋转轴,都无法使得数据线性可分'''
#from sklearn.decomposition import PCA #传统的PCA,基本上是X、Y轴转角度,然后投射
#scikit_pca = PCA(n_components=2)
#X_spca = scikit_pca.fit_transform(X)
#
#fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(7, 3))#画子图,排成1*2
#
#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('images/05_13.png', dpi=300)
#plt.show()
#
#'''调用上面的手工制作的KPCA程序,运行发现可以做'''
#X_kpca = rbf_kernel_pca(X, gamma=15, n_components=2) #投射到无穷维后用PCA降到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')
#
#plt.tight_layout()
## plt.savefig('images/05_14.png', dpi=300)
#plt.show()
#
#'''做了一个循环,测试核参数gamma,发现15开始可以线性可分'''
#for i in range(31): #尝试gamma从0到30,看看不同参数的效果,从15开始分的很开
# print('i=',i)
# X_kpca = rbf_kernel_pca(X, gamma=i, n_components=2) #投射到无穷维后用PCA降到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')
#
# plt.tight_layout()
# # plt.savefig('images/05_14.png', dpi=300)
# plt.show()
#'''又做了一个新的样本集,是两个环,典型的完全线性不可分'''
#from sklearn.datasets import make_circles
#
#X, y = make_circles(n_samples=1000, random_state=123, noise=0.1, factor=0.2) #产生乱数,画下图的圆
#
#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.s

lithops7
- 粉丝: 378
最新资源
- 基于微课的翻转课堂在中职计算机教学中的应用与创新.docx
- 电力系统潮流分析计算的MATLAB仿真周明亮01.doc
- 现场签证管理作业指引.doc
- 基于单片机的数控稳压电源毕业设计.doc
- 国家重点研发计划项目答辩评审表格.doc
- 中餐布草送洗程序及标准.pdf
- 小学数学深度学习的实践探索-(4).doc
- 基于Android的2048游戏的设计与实现.doc
- 基于matlab的IIR滤波器的设计文献综述.doc
- 2003沉积学原理试题及答案.doc
- 三菱PLC的三层电梯控制系统设计.docx
- 基于BP神经网络数学算法的智能照明控制应用.docx
- 电力建设工程质量通病典型缺陷防治.doc
- 信息化教学背景下高职教学管理的现状及对策.docx
- d1200-32离心鼓风机试车方案.doc
- 30m预应力工字梁安装方案.doc
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈



- 1
- 2
- 3
- 4
前往页