注意
转到末尾 下载完整的示例代码。或通过JupyterLite或Binder在您的浏览器中运行此示例
核岭回归和SVR的比较#
核岭回归 (KRR) 和 SVR 都通过使用核技巧学习非线性函数,即它们在由各自核诱导的空间中学习线性函数,这对应于原始空间中的非线性函数。它们的区别在于损失函数(岭损失与 ε-不敏感损失)。与 SVR 相反,KRR 的拟合可以封闭形式完成,并且对于中等大小的数据集通常更快。另一方面,学习到的模型是非稀疏的,因此在预测时间比 SVR 慢。
此示例在一个人工数据集上说明这两种方法,该数据集由正弦目标函数和添加到每个第五个数据点的强噪声组成。
作者:scikit-learn 开发者 SPDX-License-Identifier: BSD-3-Clause
生成样本数据#
import numpy as np
rng = np.random.RandomState(42)
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]
构建基于核的回归模型#
from sklearn.kernel_ridge import KernelRidge
from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVR
train_size = 100
svr = GridSearchCV(
SVR(kernel="rbf", gamma=0.1),
param_grid={"C": [1e0, 1e1, 1e2, 1e3], "gamma": np.logspace(-2, 2, 5)},
)
kr = GridSearchCV(
KernelRidge(kernel="rbf", gamma=0.1),
param_grid={"alpha": [1e0, 0.1, 1e-2, 1e-3], "gamma": np.logspace(-2, 2, 5)},
)
比较SVR和核岭回归的时间#
import time
t0 = time.time()
svr.fit(X[:train_size], y[:train_size])
svr_fit = time.time() - t0
print(f"Best SVR with params: {svr.best_params_} and R2 score: {svr.best_score_:.3f}")
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(f"Best KRR with params: {kr.best_params_} and R2 score: {kr.best_score_:.3f}")
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))
Best SVR with params: {'C': 1.0, 'gamma': np.float64(0.1)} and R2 score: 0.737
SVR complexity and bandwidth selected and model fitted in 0.535 s
Best KRR with params: {'alpha': 0.1, 'gamma': np.float64(0.1)} and R2 score: 0.723
KRR complexity and bandwidth selected and model fitted in 0.217 s
Support vector ratio: 0.340
SVR prediction for 100000 inputs in 0.112 s
KRR prediction for 100000 inputs in 0.102 s
查看结果#
import matplotlib.pyplot as plt
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()
上图比较了当使用网格搜索优化 RBF 核的复杂度/正则化和带宽时,KRR 和 SVR 的学习模型。学习到的函数非常相似;但是,KRR 的拟合速度大约比 SVR 快 3-4 倍(两者都使用网格搜索)。
理论上,预测 100000 个目标值的速度可以使用 SVR 快三倍左右,因为它只使用了大约 1/3 的训练数据点作为支持向量学习了一个稀疏模型。然而,实际上,情况并非总是如此,因为内核函数在每个模型中计算的方式存在实现细节,这使得 KRR 模型即使计算更多算术运算也能同样快甚至更快。
可视化训练和预测时间#
plt.figure()
sizes = np.logspace(1, 3.8, 7).astype(int)
for name, estimator in {
"KRR": KernelRidge(kernel="rbf", alpha=0.01, gamma=10),
"SVR": SVR(kernel="rbf", C=1e2, 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")
此图比较了不同大小的训练集的 KRR 和 SVR 的拟合和预测时间。对于中等大小的训练集(少于几千个样本),KRR 的拟合速度比 SVR 快;但是,对于更大的训练集,SVR 的扩展性更好。关于预测时间,由于学习到的稀疏解,SVR 应该比 KRR 快,对于所有大小的训练集都是如此,但这在实践中并不一定如此,因为存在实现细节。请注意,稀疏程度以及预测时间取决于 SVR 的参数 epsilon 和 C。
可视化学习曲线#
from sklearn.model_selection import LearningCurveDisplay
_, ax = plt.subplots()
svr = SVR(kernel="rbf", C=1e1, gamma=0.1)
kr = KernelRidge(kernel="rbf", alpha=0.1, gamma=0.1)
common_params = {
"X": X[:100],
"y": y[:100],
"train_sizes": np.linspace(0.1, 1, 10),
"scoring": "neg_mean_squared_error",
"negate_score": True,
"score_name": "Mean Squared Error",
"score_type": "test",
"std_display_style": None,
"ax": ax,
}
LearningCurveDisplay.from_estimator(svr, **common_params)
LearningCurveDisplay.from_estimator(kr, **common_params)
ax.set_title("Learning curves")
ax.legend(handles=ax.get_legend_handles_labels()[0], labels=["SVR", "KRR"])
plt.show()
脚本总运行时间:(0 分钟 8.701 秒)
相关示例