• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

sklearn例程:核岭回归与SVM回归的比较

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

核岭回归与SVM回归的比较简介

核岭回归(KRR)和SVM回归(SVR)都是通过采用核技巧来学习非线性函数。也就是说,二者在由核产生的空间中学习了一个线性函数,这个函数与原始空间中的非线性函数相对应。它们的损失函数是不同的(岭损失 VS epsilon松弛损失)。与SVR相比,KRR能以闭式解完成的拟合,所以对于中等规模的数据集通常更快。不过,KRR学习的模型是非稀疏的,因此在预测时比产生稀疏解的SVR要慢。

此示例介绍了人工数据集上的两种方法,该方法由正弦目标函数和添加到每五个数据点的强噪声组成。下文中的第一张图比较了KRR和SVR学习到的模型,其中复杂度/正则化和RBF核的带宽都使用了网格搜索(grid-search)优化。可以看到,学到的函数非常相似;不过,拟合KRR大约比拟合SVR快7倍(两者均使用grid-search)。但是,使用SVR对100000个目标值做预测时的速度比KRR快了3倍以上,因为它仅使用了100个训练数据点的约1/3就学会了稀疏模型(作为支持向量)。

从示例代码输出的图片可以看到(见下文),不同大小的训练集的KRR和SVR的拟合和预测时间的对比情况。对于中等规模的训练集(少于1000个样本),拟合KRR比SVR更快。但是,对于较大的训练集,SVR的扩展性更好。关于预测时间,由于SVR学到的是稀疏解决方案,对于所有规模的训练集,SVR均比KRR更快。请注意,稀疏程度以及预测时间取决于SVR的参数epsilon和C。

代码实现[Python]


# -*- coding: utf-8 -*- 

# Authors: Jan Hendrik Metzen 
# License: BSD 3 clause


import time

import numpy as np

from sklearn.svm import SVR
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import learning_curve
from sklearn.kernel_ridge import KernelRidge
import matplotlib.pyplot as plt

rng = np.random.RandomState(0)

# #############################################################################
# 生成样本数据
X = 5 * rng.rand(10000, 1)
y = np.sin(X).ravel()

# Add noise to targets
y[::5] += 3 * (0.5 - rng.rand(X.shape[0] // 5))

X_plot = np.linspace(0, 5, 100000)[:, None]

# #############################################################################
# 拟合回归模型
train_size = 100
svr = GridSearchCV(SVR(kernel='rbf', gamma=0.1), cv=5,
                   param_grid={"C": [1e0, 1e1, 1e2, 1e3],
                               "gamma": np.logspace(-2, 2, 5)})

kr = GridSearchCV(KernelRidge(kernel='rbf', gamma=0.1), cv=5,
                  param_grid={"alpha": [1e0, 0.1, 1e-2, 1e-3],
                              "gamma": np.logspace(-2, 2, 5)})

t0 = time.time()
svr.fit(X[:train_size], y[:train_size])
svr_fit = time.time() - t0
print("SVR complexity and bandwidth selected and model fitted in %.3f s"
      % svr_fit)

t0 = time.time()
kr.fit(X[:train_size], y[:train_size])
kr_fit = time.time() - t0
print("KRR complexity and bandwidth selected and model fitted in %.3f s"
      % kr_fit)

sv_ratio = svr.best_estimator_.support_.shape[0] / train_size
print("Support vector ratio: %.3f" % sv_ratio)

t0 = time.time()
y_svr = svr.predict(X_plot)
svr_predict = time.time() - t0
print("SVR prediction for %d inputs in %.3f s"
      % (X_plot.shape[0], svr_predict))

t0 = time.time()
y_kr = kr.predict(X_plot)
kr_predict = time.time() - t0
print("KRR prediction for %d inputs in %.3f s"
      % (X_plot.shape[0], kr_predict))


# #############################################################################
# 结果可视化
sv_ind = svr.best_estimator_.support_
plt.scatter(X[sv_ind], y[sv_ind], c='r', s=50, label='SVR support vectors',
            zorder=2, edgecolors=(0, 0, 0))
plt.scatter(X[:100], y[:100], c='k', label='data', zorder=1,
            edgecolors=(0, 0, 0))
plt.plot(X_plot, y_svr, c='r',
         label='SVR (fit: %.3fs, predict: %.3fs)' % (svr_fit, svr_predict))
plt.plot(X_plot, y_kr, c='g',
         label='KRR (fit: %.3fs, predict: %.3fs)' % (kr_fit, kr_predict))
plt.xlabel('data')
plt.ylabel('target')
plt.title('SVR versus Kernel Ridge')
plt.legend()

# 可视化训练和预测时间
plt.figure()

# 生成样本数据
X = 5 * rng.rand(10000, 1)
y = np.sin(X).ravel()
y[::5] += 3 * (0.5 - rng.rand(X.shape[0] // 5))
sizes = np.logspace(1, 4, 7).astype(np.int)
for name, estimator in {"KRR": KernelRidge(kernel='rbf', alpha=0.1,
                                           gamma=10),
                        "SVR": SVR(kernel='rbf', C=1e1, gamma=10)}.items():
    train_time = []
    test_time = []
    for train_test_size in sizes:
        t0 = time.time()
        estimator.fit(X[:train_test_size], y[:train_test_size])
        train_time.append(time.time() - t0)

        t0 = time.time()
        estimator.predict(X_plot[:1000])
        test_time.append(time.time() - t0)

    plt.plot(sizes, train_time, 'o-', color="r" if name == "SVR" else "g",
             label="%s (train)" % name)
    plt.plot(sizes, test_time, 'o--', color="r" if name == "SVR" else "g",
             label="%s (test)" % name)

plt.xscale("log")
plt.yscale("log")
plt.xlabel("Train size")
plt.ylabel("Time (seconds)")
plt.title('Execution Time')
plt.legend(loc="best")

# 可视化学习曲线
plt.figure()

svr = SVR(kernel='rbf', C=1e1, gamma=0.1)
kr = KernelRidge(kernel='rbf', alpha=0.1, gamma=0.1)
train_sizes, train_scores_svr, test_scores_svr = \
    learning_curve(svr, X[:100], y[:100], train_sizes=np.linspace(0.1, 1, 10),
                   scoring="neg_mean_squared_error", cv=10)
train_sizes_abs, train_scores_kr, test_scores_kr = \
    learning_curve(kr, X[:100], y[:100], train_sizes=np.linspace(0.1, 1, 10),
                   scoring="neg_mean_squared_error", cv=10)

plt.plot(train_sizes, -test_scores_svr.mean(1), 'o-', color="r",
         label="SVR")
plt.plot(train_sizes, -test_scores_kr.mean(1), 'o-', color="g",
         label="KRR")
plt.xlabel("Train size")
plt.ylabel("Mean Squared Error")
plt.title('Learning curves')
plt.legend(loc="best")

plt.show()

代码执行

代码运行时间大约:0分13.067秒。
运行代码输出的文本内容如下:

SVR complexity and bandwidth selected and model fitted in 0.389 s
KRR complexity and bandwidth selected and model fitted in 0.175 s
Support vector ratio: 0.320
SVR prediction for 100000 inputs in 0.117 s
KRR prediction for 100000 inputs in 0.141 s

运行代码输出的图片内容如下:

源码下载

  • Python版源码文件: plot_kernel_ridge_regression.py
  • Jupyter Notebook版源码文件: plot_kernel_ridge_regression.ipynb

参考资料

  • Comparison of kernel ridge regression and SVR

鲜花

握手

雷人

路过

鸡蛋
专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap