kpca rbf matlab实现,用Gram矩阵实现RBF核的Python实现?

我们可以手工编写内核pca。让我们从政治核开始。在from sklearn.datasets import make_circles

from scipy.spatial.distance import pdist, squareform

from scipy.linalg import eigh

import numpy as np

import matplotlib.pyplot as plt

%matplotlib inline

X_c, y_c = make_circles(n_samples=100, random_state=654)

plt.figure(figsize=(8,6))

plt.scatter(X_c[y_c==0, 0], X_c[y_c==0, 1], color='red')

plt.scatter(X_c[y_c==1, 0], X_c[y_c==1, 1], color='blue')

plt.ylabel('y coordinate')

plt.xlabel('x coordinate')

plt.show()

数据:

up8k7.png

^{pr2}$

现在转换数据并绘制它X_c1 = degree_pca(X_c, gamma=5, degree=2, n_components=2)

plt.figure(figsize=(8,6))

plt.scatter(X_c1[y_c==0, 0], X_c1[y_c==0, 1], color='red')

plt.scatter(X_c1[y_c==1, 0], X_c1[y_c==1, 1], color='blue')

plt.ylabel('y coordinate')

plt.xlabel('x coordinate')

plt.show()

线性可分:

EELLr.png

现在点可以线性分开。在

接下来我们编写RBF核函数。为了演示,让我们来看看月亮。在from sklearn.datasets import make_moons

X, y = make_moons(n_samples=100, random_state=654)

plt.figure(figsize=(8,6))

plt.scatter(X[y==0, 0], X[y==0, 1], color='red')

plt.scatter(X[y==1, 0], X[y==1, 1], color='blue')

plt.ylabel('y coordinate')

plt.xlabel('x coordinate')

plt.show()

月亮:

BBwEZ.png

核pca变换:def stepwise_kpca(X, gamma, n_components):

"""

X: A MxN dataset as NumPy array where the samples are stored as rows (M), features as columns (N).

gamma: coefficient for the RBF kernel.

n_components: number of components to be returned.

"""

# Calculating the squared Euclidean distances for every pair of points

# in the MxN dimensional dataset.

sq_dists = pdist(X, 'sqeuclidean')

# Converting the pairwise distances into a symmetric MxM matrix.

mat_sq_dists = squareform(sq_dists)

K=np.exp(-gamma*mat_sq_dists)

# Centering the symmetric NxN 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 eigenvalues in descending order with corresponding

# eigenvectors from the symmetric matrix.

eigvals, eigvecs = eigh(K)

# Obtaining the i eigenvectors that corresponds to the i highest eigenvalues.

X_pc = np.column_stack((eigvecs[:,-i] for i in range(1,n_components+1)))

return X_pc

我们来策划一下X_4 = stepwise_kpca(X, gamma=15, n_components=2)

plt.scatter(X_4[y==0, 0], X_4[y==0, 1], color='red')

plt.scatter(X_4[y==1, 0], X_4[y==1, 1], color='blue')

plt.ylabel('y coordinate')

plt.xlabel('x coordinate')

plt.show()

结果:

huuZQ.png

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值