对线性不可分数据(例如圆形)进行特征降维的时候 ,可以尝试使用Kernel PCA来进行非线性的降维。

可以使用sklearn.decomposition.KernelPCA对象,以下是其重要参数:

  • n_components : int, default=None

      降维后特征的数量,如果不提供则保持原来的维度
  • kernel : "linear" | "poly" | "rbf" | "sigmoid" | "cosine" | "precomputed"

      核函数,默认为 linear
    
  • gamma : float, default=1/n_features

      当核函数是 rbf, poly 或者 sigmoid核时可设置
    
  • degree : int, default=3

      当使用poly核函数时使用,代表阶数
    

注意:

  1. 在使用Kernel PCA的时候,需要注意,其无法如传统PCA一样按照保留的信心量来自动降维,而必须指定降维后的特征数
  2. 在使用核函数的时候,需要进行调参,每个核都有自己的参数可以调整,例如rbf核有gamma值,可以使用不同的参数降维后来训练机器学习模型,找出最优模型的组合。

下面为具体的代码:

  1. 导入库函数
from sklearn.decomposition import KernelPCA
from sklearn.datasets import make_circles
import matplotlib.pyplot as plt
import numpy as np
  1. 建立圆形的类别并画出来
features, _ = make_circles(n_samples = 2000, 
                           random_state=1, 
                           noise=0.1, 
                           factor=0.1)

labels = np.zeros(2000)
labels[(features[:, 0] ** 2 + features[:, 1] **2) <= np.pi / 6] = 1

c1 = features[labels == 1]
c2 = features[labels != 1]

plt.figure()
plt.scatter(c1[:, 0], c1[:, 1], c='g')
plt.scatter(c2[:, 0], c2[:, 1], c='r')

  1. 创建Kernel PCA工具,并将其转换为1维的特征
kpca = KernelPCA(kernel='rbf', gamma=15, n_components=1)
feature_kpca = kpca.fit_transform(features)
  1. 画出转换后的结果
plt.figure()
plt.plot(feature_kpca[labels == 1], c='g')
plt.plot(feature_kpca[labels != 1], c='r')

  1. 尝试保留两个特征
kpca = KernelPCA(kernel='rbf', gamma=15, n_components=2)
feature_kpca = kpca.fit_transform(features)

plt.figure()
plt.scatter(feature_kpca[labels == 1][:, 0], 
            feature_kpca[labels == 1][:, 1], c='g')
plt.scatter(feature_kpca[labels != 1][:, 0], 
            feature_kpca[labels != 1][:, 1], c='r')

如此,可以看出最终结果被转换为线性可分。

scikit-learn文档:Kernel PCA

最后修改:2021 年 06 月 01 日 02 : 21 PM
如果觉得我的文章对你有用,请随意赞赏