注意
跳转至页面底部 下载完整示例代码,或通过 JupyterLite 或 Binder 在浏览器中运行此示例。
单估计器与装袋法:偏差-方差分解#
本示例演示并比较了单估计器与装袋(bagging)集成模型在预期均方误差上的偏差-方差分解。
在回归任务中,估计器的预期均方误差可以分解为偏差、方差和噪声。在对回归问题的多个数据集求平均后,偏差项衡量的是估计器的预测值与该问题最优估计器(即贝叶斯模型)预测值之间的平均差异。方差项衡量的是当在同一问题的不同随机实例上进行拟合时,估计器预测值的变异程度。在下文中,每个问题实例都被记为“LS”(代表“学习样本”,Learning Sample)。最后,噪声衡量的是由数据变异性引起的不可约误差部分。
左上图展示了一个单一决策树在某玩具一维回归问题的随机数据集 LS(蓝色圆点)上训练后的预测结果(深红色)。图中还展示了其他单一决策树在针对该问题的其他(且不同)随机抽取的实例 LS 上训练后的预测结果(浅红色)。直观地看,此处的方差项对应于单个估计器预测值(浅红色)波束的宽度。方差越大,x 的预测值对训练集的小波动就越敏感。偏差项对应于估计器的平均预测值(青色)与最优模型(深蓝色)之间的差异。在这一问题中,我们可以观察到偏差相当低(青色曲线和蓝色曲线非常接近),而方差很大(红色波束相当宽)。
左下图绘制了单决策树预期均方误差的逐点分解图。它证实了偏差项(蓝色)很低,而方差(绿色)很大。它还展示了误差中的噪声部分,正如预期那样,该部分表现为常数,约为 0.01。
右侧图形对应相同的绘图,但使用的是决策树的装袋集成模型。在这两张图中,我们可以观察到偏差项比之前的情况要大。在右上图中,平均预测值(青色)与最优模型之间的差异更大(例如,注意 x=2 附近的偏移)。在右下图,偏差曲线也比左下图略高。然而在方差方面,预测波束更窄,这表明方差更低。事实上,正如右下图所证实的那样,方差项(绿色)比单决策树要低。总的来说,偏差-方差分解发生了变化。对于装袋法而言,这种权衡更为有利:对在数据集的自助采样副本(bootstrap copies)上拟合的多棵决策树进行平均,虽然略微增加了偏差项,但允许方差大幅降低,从而实现了更低的总体均方误差(比较下图中红色的曲线)。脚本输出也证实了这一直觉。装袋集成模型的总误差低于单决策树的总误差,且这种差异主要源于方差的减少。
关于偏差-方差分解的更多详细信息,请参阅 [1] 的第 7.3 节。
参考文献#

Tree: 0.0255 (error) = 0.0003 (bias^2) + 0.0152 (var) + 0.0098 (noise)
Bagging(Tree): 0.0196 (error) = 0.0004 (bias^2) + 0.0092 (var) + 0.0098 (noise)
# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause
import matplotlib.pyplot as plt
import numpy as np
from sklearn.ensemble import BaggingRegressor
from sklearn.tree import DecisionTreeRegressor
# Settings
n_repeat = 50 # Number of iterations for computing expectations
n_train = 50 # Size of the training set
n_test = 1000 # Size of the test set
noise = 0.1 # Standard deviation of the noise
np.random.seed(0)
# Change this for exploring the bias-variance decomposition of other
# estimators. This should work well for estimators with high variance (e.g.,
# decision trees or KNN), but poorly for estimators with low variance (e.g.,
# linear models).
estimators = [
("Tree", DecisionTreeRegressor()),
("Bagging(Tree)", BaggingRegressor(DecisionTreeRegressor())),
]
n_estimators = len(estimators)
# Generate data
def f(x):
x = x.ravel()
return np.exp(-(x**2)) + 1.5 * np.exp(-((x - 2) ** 2))
def generate(n_samples, noise, n_repeat=1):
X = np.random.rand(n_samples) * 10 - 5
X = np.sort(X)
if n_repeat == 1:
y = f(X) + np.random.normal(0.0, noise, n_samples)
else:
y = np.zeros((n_samples, n_repeat))
for i in range(n_repeat):
y[:, i] = f(X) + np.random.normal(0.0, noise, n_samples)
X = X.reshape((n_samples, 1))
return X, y
X_train = []
y_train = []
for i in range(n_repeat):
X, y = generate(n_samples=n_train, noise=noise)
X_train.append(X)
y_train.append(y)
X_test, y_test = generate(n_samples=n_test, noise=noise, n_repeat=n_repeat)
plt.figure(figsize=(10, 8))
# Loop over estimators to compare
for n, (name, estimator) in enumerate(estimators):
# Compute predictions
y_predict = np.zeros((n_test, n_repeat))
for i in range(n_repeat):
estimator.fit(X_train[i], y_train[i])
y_predict[:, i] = estimator.predict(X_test)
# Bias^2 + Variance + Noise decomposition of the mean squared error
y_error = np.zeros(n_test)
for i in range(n_repeat):
for j in range(n_repeat):
y_error += (y_test[:, j] - y_predict[:, i]) ** 2
y_error /= n_repeat * n_repeat
y_noise = np.var(y_test, axis=1)
y_bias = (f(X_test) - np.mean(y_predict, axis=1)) ** 2
y_var = np.var(y_predict, axis=1)
print(
"{0}: {1:.4f} (error) = {2:.4f} (bias^2) "
" + {3:.4f} (var) + {4:.4f} (noise)".format(
name, np.mean(y_error), np.mean(y_bias), np.mean(y_var), np.mean(y_noise)
)
)
# Plot figures
plt.subplot(2, n_estimators, n + 1)
plt.plot(X_test, f(X_test), "b", label="$f(x)$")
plt.plot(X_train[0], y_train[0], ".b", label="LS ~ $y = f(x)+noise$")
for i in range(n_repeat):
if i == 0:
plt.plot(X_test, y_predict[:, i], "r", label=r"$\^y(x)$")
else:
plt.plot(X_test, y_predict[:, i], "r", alpha=0.05)
plt.plot(X_test, np.mean(y_predict, axis=1), "c", label=r"$\mathbb{E}_{LS} \^y(x)$")
plt.xlim([-5, 5])
plt.title(name)
if n == n_estimators - 1:
plt.legend(loc=(1.1, 0.5))
plt.subplot(2, n_estimators, n_estimators + n + 1)
plt.plot(X_test, y_error, "r", label="$error(x)$")
plt.plot(X_test, y_bias, "b", label="$bias^2(x)$")
plt.plot(X_test, y_var, "g", label="$variance(x)$")
plt.plot(X_test, y_noise, "c", label="$noise(x)$")
plt.xlim([-5, 5])
plt.ylim([0, 0.1])
if n == n_estimators - 1:
plt.legend(loc=(1.1, 0.5))
plt.subplots_adjust(right=0.75)
plt.show()
脚本总运行时间: (0 分 1.196 秒)
相关示例