一,介绍

现实中往往很多数据是线性不可分的,因此我们需要引入核函数把数据映射到高纬度而达到线性可分。基于核函数的主成分分析(KPCA)和主成分分析(KPCA)的步骤是一样的,只不过需要用核函数替代了原来的数据。

原理从其他地方拷贝而来:

机器学习-降维算法(KPCA算法)

二,代码实现

from sklearn.datasets import make_moons
from sklearn.decomposition import PCA
from sklearn.decomposition import KernelPCA
import matplotlib.pyplot as plt
import numpy as np

x2, y2 = make_moons(n_samples=100, random_state=123)

if __name__ == "__main__":
    pca = PCA(n_components=2)
    x_spca = pca.fit_transform(x2)
    fig, ax = plt.subplots(nrows=1, ncols=3, figsize=(14, 6))
    ax[0].scatter(x_spca[y2 == 0, 0], x_spca[y2 == 0, 1], color='red', marker='^', alpha=0.5)
    ax[0].scatter(x_spca[y2 == 1, 0], x_spca[y2 == 1, 1], color='blue', marker='o', alpha=0.5)
    ax[1].scatter(x_spca[y2 == 0, 0], np.zeros((50, 1)) + 0.02, color='red', marker='^', alpha=0.5)
    ax[1].scatter(x_spca[y2 == 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')

    kpca = KernelPCA(n_components=2, kernel='rbf', gamma=15)
    x_kpca = kpca.fit_transform(x2)

    ax[2].scatter(x_kpca[y2 == 0, 0], x_kpca[y2 == 0, 1], color='red', marker='^', alpha=0.5)
    ax[2].scatter(x_kpca[y2 == 1, 0], x_kpca[y2 == 1, 1], color='blue', marker='o', alpha=0.5)

    plt.show()

结果:

机器学习-降维算法(KPCA算法)

相关文章:

  • 2021-12-06
  • 2021-06-06
  • 2021-04-11
  • 2021-03-26
  • 2021-05-21
  • 2022-03-11
  • 2021-04-18
  • 2021-07-15
猜你喜欢
  • 2018-06-29
  • 2021-11-05
  • 2022-12-23
  • 2021-05-18
  • 2022-01-18
  • 2022-02-27
相关资源
相似解决方案