使用BaggingClassifier,可以完成每一个分类器都使用相同的训练算法,但是在不同的训练集上去训练它们。bagging是有放回采样,而pasting为无放回采样。
from sklearn.ensemble import RandomForestClassifier,VotingClassifier,BaggingClassifier
from sklearn.tree import DicisionTreeClassifier
bag_clf=BaggingClassifier(DecisionTreeClassifier(),
n_estimators=500,
max_samples=100,
bootstrap=True,
n_jobs=-1,
oob_score=True)
可以通过设置参数 bootstrap=False来切换为无放回采样。
n_estimators=500,表示有有500个相同的决策器。
max_samples=100,表示在数据集上有放回采样 100 个训练实例。
n_jobs=-1,n_jobs 参数告诉 sklearn 用于训练和预测所需要 CPU 核的数量。(-1 代表着 sklearn 会使用所有空闲核)
oob_score=True,表示包外评估,在bootstrap=True的时候,我们有放回的抽样会导致大概有37%左右的实例是未被采样的,用这些实例来对模型进行检验,将多个训练器在包外实例上的评估结果取平均值,就可以得到集成的评估。
两者获得的评估精度是很接近的。同时如果基础预测器支持predict_probe方法的话,那么可以使用oob_decision_function_变量来展示。
会提供分类后每种类别的概率。
上面是BaggingClassifier对于实例的取样,BaggingClassifier同时也支持对特征的取样。
由两个超参数 max_features 和 bootstrap_features 控制。
max_features,表示的是最大采样特征的数量。
bootstrap_features=True表示对特征采样。
from matplotlib.colors import ListedColormap
def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True):
x1s = np.linspace(axes[0], axes[1], 100)
x2s = np.linspace(axes[2], axes[3], 100)
x1, x2 = np.meshgrid(x1s, x2s)
X_new = np.c_[x1.ravel(), x2.ravel()]
y_pred = clf.predict(X_new).reshape(x1.shape)
custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
if contour:
custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", alpha=alpha)
plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", alpha=alpha)
plt.axis(axes)
plt.xlabel(r"$x_1$", fontsize=18)
plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
tree_clf = DecisionTreeClassifier(random_state=42,max_depth=4)
tree_clf.fit(xtr, ytr)
y_pred_tree = tree_clf.predict(xte)
print(accuracy_score(yte, y_pred_tree))
plt.figure(figsize=(11,4))
plt.subplot(121)
plot_decision_boundary(tree_clf, x, y)
plt.title("Decision Tree", fontsize=14)
plt.subplot(122)
plot_decision_boundary(bag_clf, x, y)
plt.title("Decision Trees with Bagging", fontsize=14)
plt.show()
使用上面的代码可以画出两种算法的决策边界。