核岭回归与 SVR 的比较#
核岭回归 (KRR) 和 SVR 都通过使用核技巧来学习非线性函数,即它们在由相应核诱导的空间中学习线性函数,这对应于原始空间中的非线性函数。它们在损失函数方面有所不同(岭与 epsilon 不敏感损失)。与 SVR 相比,拟合 KRR 可以通过闭式解完成,并且通常对于中等大小的数据集更快。另一方面,学习到的模型是非稀疏的,因此在预测时比 SVR 慢。
此示例在人工数据集上说明了这两种方法,该数据集包含正弦目标函数,并且每个第五个数据点都添加了强噪声。
作者:Jan Hendrik Metzen <jhm@informatik.uni-bremen.de> 许可证:BSD 3 条款
生成样本数据#
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': 0.09999999999999999} and R2 score: 0.737
SVR complexity and bandwidth selected and model fitted in 0.658 s
Best KRR with params: {'alpha': 0.1, 'gamma': 0.09999999999999999} and R2 score: 0.723
KRR complexity and bandwidth selected and model fitted in 0.227 s
Support vector ratio: 0.340
SVR prediction for 100000 inputs in 0.129 s
KRR prediction for 100000 inputs in 0.116 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()
上图比较了 KRR 和 SVR 的学习模型,当使用网格搜索优化 RBF 核的复杂度/正则化和带宽时。学习到的函数非常相似;然而,拟合 KRR 比拟合 SVR 快大约 3-4 倍(两者都使用网格搜索)。
理论上,预测 100000 个目标值可以使用 SVR 快大约三倍,因为它使用大约 1/3 的训练数据点作为支持向量学习了一个稀疏模型。然而,在实践中,情况并非一定如此,因为内核函数在每个模型中的计算方式存在实现细节,这使得 KRR 模型即使计算了更多算术运算,也能与 SVR 一样快,甚至更快。
可视化训练和预测时间#
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 分钟 9.162 秒)
相关示例