集成算法中的Bagging
Bagging meta-estimator
基本描述
在集成算法中,bagging 方法會在原始訓練集的隨機子集上構建一類黑盒估計器的多個實例,然后把這些估計器的預測結果結合起來形成最終的預測結果。 該方法通過在構建模型的過程中引入隨機性,來減少基估計器的方差(例如,決策樹)。 在多數情況下,bagging 方法提供了一種非常簡單的方式來對單一模型進行改進,而無需修改背后的算法。 因為 bagging 方法可以減小過擬合,所以通常在強分類器和復雜模型上使用時表現的很好(例如,完全決策樹,fully developed decision trees),相比之下 boosting 方法則在弱模型上表現更好(例如,淺層決策樹,shallow decision trees)。
bagging 方法有很多種,其主要區別在于隨機抽取訓練子集的方法不同:
- 如果抽取的數據集的隨機子集是樣例的隨機子集,我們叫做 Pasting 。
- 如果樣例抽取是有放回的,我們稱為 Bagging 。
- 如果抽取的數據集的隨機子集是特征的隨機子集,我們叫做隨機子空間 (Random Subspaces)。
- 最后,如果基估計器構建在對于樣本和特征抽取的子集之上時,我們叫做隨機補丁 (Random Patches) 。
在 scikit-learn 中,bagging 方法使用統一的 BaggingClassifier 元估計器(或者 BaggingRegressor ),輸入的參數和隨機子集抽取策略由用戶指定。max_samples 和 max_features 控制著子集的大小(對于樣例和特征), bootstrap 和 bootstrap_features 控制著樣例和特征的抽取是有放回還是無放回的。 當使用樣本子集時,通過設置 oob_score=True ,可以使用袋外(out-of-bag)樣本來評估泛化精度。
采樣概率
在Bagging中,一個樣本可能被多次采樣,也可能一直不被采樣,假設一個樣本一直不出現在采樣集的概率為(1-1/N) ** N,那么對其求極限可知,原始樣本數據集中約有63.2%的樣本出現在了,Bagging使用的數據集中,同時在采樣中,我們還可以使用袋外樣本(out of Bagging)來對我們模型的泛化精度進行評估.
最終的預測結果
- 對于分類任務使用簡單投票法,即每個分類器一票進行投票(也可以進行概率平均)
- 對于回歸任務,則采用簡單平均獲取最終結果,即取所有分類器的平均值
雖然在Bagging中引入的隨機分割增加了偏差,但是因為多個模型的集成平均,同時也使得我們在總體上獲取了更好的模型,在本篇文章中,我們稱之為Bagging的特性一,在后面我們將會驗證這一特性。
簡單的實用
基于KNN的Bagging算法
關于參數和方法要注意的是:
- 首先控制特征子采樣與樣本子采樣是否采用,采用的話是否要注意控制比例(一般而言,不要采取較小的數值,太小的特征子采樣和樣本子采樣都會造成子學習器的性能太差.一般而言特征選擇越少,方差越大,這點可以與最后的實驗方差偏差分解對比分析).
- 其次控制Bagging中的隨機數參數random_state固定,不然不同實驗的結果將不一致,同時要注意的很多時候random_state對于測試誤差的影響很大,因此加入你想要在某一個數據集上使用Bagging,那么建議多嘗試幾個不同的Random_state
- oob_score = True 對性能有一定的提升(使用袋外樣本進行泛化能力的評估,但是很多時候效果并不明顯,或者看不出什么效果)
- 其他參數一般默認即可
隨機數對訓練誤差與測試誤差的影響
sores_list = [] param_range = range(0,101) for i in param_range:baggingclf_2 = BaggingClassifier(KNeighborsClassifier(),max_samples = 0.8,max_features=0.8,random_state=i)baggingclf_2.fit(X_train,y_train)y_pre = baggingclf_2.predict(X_test)sores_list.append(accuracy_score(y_test,y_pre,normalize=True))plt.plot(param_range,sores_list) plt.show()偏差方差分解
之前我們說過:雖然在Bagging中引入的隨機分割增加了偏差,但是因為多個模型的集成平均,同時也使得我們在總體上獲取了更好的模型.而下面就是對Bagging誤差分解后與單個決策樹的對比圖。Bagging(Tree)相較于Tree增加了偏差,但是降低了方差,最終得到了優于Tree的模型,而同樣的Bagging(Tree)_2進一步大幅度增加了偏差,但是同樣的方差也大幅度下降,最終得到了效果優于Bagging(Tree)的最終模型。
import numpy as np import matplotlib.pyplot as plt plt.figure(figsize=(20,10))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())),("Bagging(Tree)_2",BaggingRegressor(DecisionTreeRegressor(), max_samples=0.5, random_state=100))]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 - 5X = 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, yX_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)# Loop over estimators to compare for n, (name, estimator) in enumerate(estimators):# Compute predictionsy_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 errory_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]) ** 2y_error /= (n_repeat * n_repeat)y_noise = np.var(y_test, axis=1)y_bias = (f(X_test) - np.mean(y_predict, axis=1)) ** 2y_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 figuresplt.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="$\^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="$\mathbb{E}_{LS} \^y(x)$")plt.xlim([-5, 5])plt.title(name)if n == 0:plt.legend(loc="upper left", prop={"size": 11})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 == 0:plt.legend(loc="upper left", prop={"size": 11})plt.show() 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) Bagging(Tree)_2: 0.0195 (error) = 0.0020 (bias^2) + 0.0075 (var) + 0.0098 (noise)參考
- sklearn ApacheCN中文官方文檔 : 集成算法
- sklearn官方文檔 : Single estimator versus bagging: bias-variance decomposition
- 《機器學習》 周志華編著
如果你想了解更多關于其他集成算法,或者Bagging系列算法的其他內容,比如隨機森林等,請關注我的博客
轉載于:https://www.cnblogs.com/fonttian/p/8480686.html
總結
以上是生活随笔為你收集整理的集成算法中的Bagging的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: NowCoder小定律
- 下一篇: JAVA配置注解方式搭建简单的Sprin