天天看点

集成学习之Blending

1.Blending

​ Blending将训练数据进行划分,划分之后的训练数据一部分训练基模型,一部分经模型预测后作为新的特征训练元模型。测试数据同样经过基模型预测,形成新的测试数据。最后,元模型对新的测试数据进行预测。算法的具体执行过程如下:

(1) 将数据划分为训练集和测试集(test_set),其中训练集需要再次划分为训练集(train_set)和验证集(val_set);

(2) 创建第一层的多个模型,这些模型可以使同质的也可以是异质的,这些模型可称为基模型

(3) 使用train_set训练步骤2中的多个模型,得到基模型,然后用训练好的基模型预测验证集(val_set),将得到的结果数据行行合并,作为第二层的训练集数据,记作val_predict

(4)使用基模型对测试集进行预测,将结果作为第二层的预测集数据,记作test_predict

(5) 创建第二层的模型,使用val_predict作为训练集训练第二层的模型,该模型可称为元模型

(5) 使用元模型对第二层测试集test_predict进行预测,该结果为整个测试集的结果。

集成学习之Blending

​ 下面我们就用具体的例子梳理这个过程:

​ 在(1)步中,总的数据集被分成训练集和测试集,如80%训练集和20%测试集,然后在这80%的训练集中再拆分训练集70%和验证集30%,因此拆分后的数据集由三部分组成:训练集80%* 70%、测试集20%、验证集80%* 30% 。训练集是为了训练模型,测试集是为了调整模型(调参),测试集则是为了检验模型的优度。

​ 在(2)-(4)步中,我们使用训练集创建了K个模型,如SVM、random forests、XGBoost等,这个是第一层的模型。 训练好模型后将验证集输入模型进行预测,得到K组不同的输出,我们记作 A 1 , . . . , A K A_1,...,A_K A1​,...,AK​,然后将测试集输入K个模型也得到K组输出,我们记作 B 1 , . . . , B K B_1,...,B_K B1​,...,BK​,其中 A i A_i Ai​的样本数与验证集一致, B i B_i Bi​的样本数与测试集一致。如果总的样本数有10000个样本,那么使用5600个样本训练了K个模型,输入验证集2400个样本得到K组2400个样本的结果 A 1 , . . . , A K A_1,...,A_K A1​,...,AK​,输入测试集2000个得到K组2000个样本的结果 B 1 , . . . , B K B_1,...,B_K B1​,...,BK​ 。

​ 在(5)步中,我们使用K组2400个样本的验证集结果 A 1 , . . . , A K A_1,...,A_K A1​,...,AK​作为第二层分类器的特征,验证集的2400个标签为因变量,训练第二层分类器,得到2400个样本的输出。

​ 在(6)步中,将输入测试集2000个得到K组2000个样本的结果 B 1 , . . . , B K B_1,...,B_K B1​,...,BK​放入第二层分类器,得到2000个测试集的预测结果。

2. 代码示例

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.datasets import load_iris
from mlxtend.plotting import plot_decision_regions
import matplotlib.gridspec as gridspec
import itertools

pd.set_option('display.max_columns', None)
plt.style.use("ggplot")

if __name__ == '__main__':
    # 我们画出决策边界
    data = load_iris()
    iris_data = data.data
    x = data.data[:, :2]
    y = data.target
    # 创建训练集和测试集
    x_train1, x_test, y_train1, y_test = train_test_split(x, y, test_size=0.2, random_state=1, stratify=y)
    # 创建训练集和验证集
    x_train, x_val, y_train, y_val = train_test_split(x_train1, y_train1, test_size=0.3, random_state=1)
    # 创建第一层的基模型
    clf1 = SVC(probability=True)
    clf2 = RandomForestClassifier(n_estimators=5, n_jobs=-1, criterion='gini')
    clf3 = KNeighborsClassifier()
    clfs = [SVC(probability=True), RandomForestClassifier(n_estimators=5, n_jobs=-1, criterion='gini'),
            KNeighborsClassifier()]
    dtc = DecisionTreeClassifier(max_depth=5)
    # 输出第一层的验证集结果与测试集结果
    val_features = np.zeros((x_val.shape[0], len(clfs)))  # 初始化验证集结果
    test_features = np.zeros((x_test.shape[0], len(clfs)))  # 初始化测试集结果
    for i, clf in enumerate(clfs):
        clf.fit(x_train, y_train)
        val_feature = clf.predict_proba(x_val)[:, 1]
        test_feature = clf.predict_proba(x_test)[:, 1]
        val_features[:, i] = val_feature
        test_features[:, i] = test_feature
    # 将第一层的验证集的结果输入第二层训练第二层分类器
    dtc.fit(val_features, y_val)
    gs = gridspec.GridSpec(2, 2)
    fig = plt.figure(figsize=(10, 8))
    for clf, lab, grd in zip([clf1, clf2, clf3, dtc],
                             ['SVC',
                              'RandomForestClassifier',
                              'KNeighborsClassifier',
                              'Blending'],
                             itertools.product([0, 1], repeat=2)):
        clf.fit(x, y)
        ax = plt.subplot(gs[grd[0], grd[1]])
        fig = plot_decision_regions(X=x, y=y, clf=clf)
        plt.title(lab)
    plt.savefig('Blending.png')
    plt.show()

           

边界图如下:

集成学习之Blending

继续阅读