1. Bagging
说明并比较了预期均方误差的偏差方差分解,单个学习器与bagging集成的比较。
在回归中,估计器的预期均方误差可以根据偏差、方差和噪声进行分解。
在回归问题的数据集上的平均值上,偏差项测量估计器的预测与问题的最佳可能估计器(即贝叶斯
模型)的预测不同的平均量。
方差项测量在问题的不同实例上拟合时估计器的预测的可变性。
最后,噪声测量由于数据的可变性而导致的误差的不可约部分。
from sklearn.ensemble import BaggingClassifier
from sklearn.neighbors import KNeighborsClassifier
bagging = BaggingClassifier(KNeighborsClassifier(), max_samples=0.5, max_features=0.5)
import numpy as np
import matplotlib.pyplot as plt
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)
estimators = [("Tree", DecisionTreeRegressor()),
("Bagging(Tree)", BaggingRegressor(DecisionTreeRegressor()))]
n_estimators = len(estimators)
BaggingRegressor 和 DecisionTreeRegressor:分别是sklearn中的集成学习和决策树回归器。
estimators 是一个包含两个估算器的列表:
第一个是单个决策树回归器(DecisionTreeRegressor())。
第二个是使用Bagging方法包装的决策树回归器(BaggingRegressor(DecisionTreeRegressor()))。
Bagging通过对数据集进行自助采样(bootstrap)来构建多个子集合,然后对每个子集合进行训
练,最终将它们的预测进行平均或投票来得到最终结果。
# Generate data
def f(x):
x = x.ravel() # ravel() 和 flatten()函数,将多维数组降为一维,ravel返回视图,flatten返回拷贝
return np.exp(-x ** 2) + 1.5 * np.exp(-(x - 2) ** 2)
# 生成符合真实世界数据分布的样本
def generate(n_samples, noise, n_repeat=1):
# numpy.random.randn(d0, d1, …, dn)是从标准正态分布中返回一个或多个样本值。
# numpy.random.rand(d0, d1, …, dn)的随机样本位于[0, 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) # numpy.random.normal(loc=0.0, scale=1.0, size=None) 均值,标准差,形状
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))
函数 f(x):定义了一个简单的数学函数,根据输入的 x 返回一个相关的输出。使用指数函数和高斯
形状的组合来生成一个特定的模式。
函数 generate(n_samples, noise, n_repeat=1):用于生成样本数据。它的作用是创建一个特定分
布模式的数据集。n_samples:生成的样本数量。noise:加入到数据中的噪声水平。n_repeat:
重复生成数据的次数。
首先,它生成 n_samples 个服从均匀分布的随机数 X,然后对其排序,从而得到 X。
对于单次生成(n_repeat = 1),它根据函数 f(x) 和指定的噪声水平 noise,生成对应的输出 y。
对于多次生成(n_repeat > 1),它为每次生成创建一个独立的输出 y,得到一个二维数组。
返回 X 和相应的 y。
数据生成和准备:使用 g