RBF核的显式特征映射近似简介
本文用一个示例介绍了近似RBF核的特征映射的方法。
具体来说,示例中展示了在便用SVM对数字数据集进行分类的情况下,如何使用RBFSampler
和Nystroem来近似
RBF核的特征映射。其中比较了使用原始空间中的线性SVM,使用近似映射和使用内核化SVM的结果。不同模型运行时间和精度的比较涉及:不同蒙特卡洛采样样本数量(对于RBFSampler
,它使用随机傅立叶特征)和训练集的不同大小子集(用于Nystroem
)。
请注意,核近似的主要优势在于性能提升,但这里的数据集规模不足以显示核近似的好处,因为精确的SVM仍然相当快。
对更多维度进行采样显然会带来更好的分类结果,但代价更高。这意味着在运行时间和精度之间需要权衡,这由参数n_components给出。请注意,通过使用随机梯度下降法(sklearn.linear_model.SGDClassifier)
可以大大加快求解线性SVM以及近似核SVM的速度。对于有核函数的SVM,这是不容易实现的。
第二个图显示了RBF核SVM和带有近似核映射的线性SVM的决策面。该图显示了投影到数据的前两个主要成分上的分类器的决策面。注意,这种可视化结果是否完全准确是存疑的,因为它只是决策面上64个维度中的一个有趣切片。特别要注意的是,数据点(用点表示)不一定要分类到它所在的区域,因为它不会位于前两个主要成分所跨越的平面上。
对于RBFSampler
和Nystroem的详细用法,请参考文档
核近似。
代码实现[Python]
# -*- coding: utf-8 -*-
print(__doc__)
# Author: Gael Varoquaux
# Andreas Mueller
# License: BSD 3 clause
# 导入Python标准科学计算相关模块
import matplotlib.pyplot as plt
import numpy as np
from time import time
# 导入数据集、分类器、性能评估标准
from sklearn import datasets, svm, pipeline
from sklearn.kernel_approximation import (RBFSampler,
Nystroem)
from sklearn.decomposition import PCA
# 手写数字数据集
digits = datasets.load_digits(n_class=9)
# 为了在数据集上应用分类器,我们需要展平图像到一个维度,将样本数据集转为(samples, feature)矩阵的形式:
n_samples = len(digits.data)
data = digits.data / 16.
data -= data.mean(axis=0)
# 使用1/2的数字数据集作为训练集
data_train, targets_train = (data[:n_samples // 2],
digits.target[:n_samples // 2])
# 另外1/2作为测试集
data_test, targets_test = (data[n_samples // 2:],
digits.target[n_samples // 2:])
# data_test = scaler.transform(data_test)
# 创建SVM分类器
kernel_svm = svm.SVC(gamma=.2)
linear_svm = svm.LinearSVC()
# 创建核近似pipeline,并添加线性SVM
feature_map_fourier = RBFSampler(gamma=.2, random_state=1)
feature_map_nystroem = Nystroem(gamma=.2, random_state=1)
fourier_approx_svm = pipeline.Pipeline([("feature_map", feature_map_fourier),
("svm", svm.LinearSVC())])
nystroem_approx_svm = pipeline.Pipeline([("feature_map", feature_map_nystroem),
("svm", svm.LinearSVC())])
# 使用线性SVM和核SVM做拟合和预测
kernel_svm_time = time()
kernel_svm.fit(data_train, targets_train)
kernel_svm_score = kernel_svm.score(data_test, targets_test)
kernel_svm_time = time() - kernel_svm_time
linear_svm_time = time()
linear_svm.fit(data_train, targets_train)
linear_svm_score = linear_svm.score(data_test, targets_test)
linear_svm_time = time() - linear_svm_time
sample_sizes = 30 * np.arange(1, 10)
fourier_scores = []
nystroem_scores = []
fourier_times = []
nystroem_times = []
for D in sample_sizes:
fourier_approx_svm.set_params(feature_map__n_components=D)
nystroem_approx_svm.set_params(feature_map__n_components=D)
start = time()
nystroem_approx_svm.fit(data_train, targets_train)
nystroem_times.append(time() - start)
start = time()
fourier_approx_svm.fit(data_train, targets_train)
fourier_times.append(time() - start)
fourier_score = fourier_approx_svm.score(data_test, targets_test)
nystroem_score = nystroem_approx_svm.score(data_test, targets_test)
nystroem_scores.append(nystroem_score)
fourier_scores.append(fourier_score)
# 绘制结果图:
plt.figure(figsize=(8, 8))
accuracy = plt.subplot(211)
# second y axis for timeings
timescale = plt.subplot(212)
accuracy.plot(sample_sizes, nystroem_scores, label="Nystroem approx. kernel")
timescale.plot(sample_sizes, nystroem_times, '--',
label='Nystroem approx. kernel')
accuracy.plot(sample_sizes, fourier_scores, label="Fourier approx. kernel")
timescale.plot(sample_sizes, fourier_times, '--',
label='Fourier approx. kernel')
# 水平线用于精确的rbf和线性内核
accuracy.plot([sample_sizes[0], sample_sizes[-1]],
[linear_svm_score, linear_svm_score], label="linear svm")
timescale.plot([sample_sizes[0], sample_sizes[-1]],
[linear_svm_time, linear_svm_time], '--', label='linear svm')
accuracy.plot([sample_sizes[0], sample_sizes[-1]],
[kernel_svm_score, kernel_svm_score], label="rbf svm")
timescale.plot([sample_sizes[0], sample_sizes[-1]],
[kernel_svm_time, kernel_svm_time], '--', label='rbf svm')
# 垂直线用于数据集维度 = 64
accuracy.plot([64, 64], [0.7, 1], label="n_features")
# legends and labels
accuracy.set_title("Classification accuracy")
timescale.set_title("Training times")
accuracy.set_xlim(sample_sizes[0], sample_sizes[-1])
accuracy.set_xticks(())
accuracy.set_ylim(np.min(fourier_scores), 1)
timescale.set_xlabel("Sampling steps = transformed feature dimension")
accuracy.set_ylabel("Classification accuracy")
timescale.set_ylabel("Training time in seconds")
accuracy.legend(loc='best')
timescale.legend(loc='best')
# 可视化决策面,向下投影到数据集的前两个主要组成部分
pca = PCA(n_components=8).fit(data_train)
X = pca.transform(data_train)
# Generate grid along first two principal components
multiples = np.arange(-2, 2, 0.1)
# steps along first component
first = multiples[:, np.newaxis] * pca.components_[0, :]
# steps along second component
second = multiples[:, np.newaxis] * pca.components_[1, :]
# combine
grid = first[np.newaxis, :, :] + second[:, np.newaxis, :]
flat_grid = grid.reshape(-1, data.shape[1])
# 图像标题
titles = ['SVC with rbf kernel',
'SVC (linear kernel)\n with Fourier rbf feature map\n'
'n_components=100',
'SVC (linear kernel)\n with Nystroem rbf feature map\n'
'n_components=100']
plt.tight_layout()
plt.figure(figsize=(12, 5))
# 预测和绘图
for i, clf in enumerate((kernel_svm, nystroem_approx_svm,
fourier_approx_svm)):
# Plot the decision boundary. For that, we will assign a color to each
# point in the mesh [x_min, x_max]x[y_min, y_max].
plt.subplot(1, 3, i + 1)
Z = clf.predict(flat_grid)
# Put the result into a color plot
Z = Z.reshape(grid.shape[:-1])
plt.contourf(multiples, multiples, Z, cmap=plt.cm.Paired)
plt.axis('off')
# Plot also the training points
plt.scatter(X[:, 0], X[:, 1], c=targets_train, cmap=plt.cm.Paired,
edgecolors=(0, 0, 0))
plt.title(titles[i])
plt.tight_layout()
plt.show()
代码执行
代码运行时间大约:0分2.188秒。
运行代码输出的图片内容如下:
源码下载
- Python版源码文件: plot_kernel_approximation.py
- Jupyter Notebook版源码文件: plot_kernel_approximation.ipynb