理论
Blending是一种模型融合方法
对于一般的blending
(1) 将数据划分为训练集和测试集(test_set),其中训练集需要再次划分为训练集(train_set)和验证集(val_set);
(2) 创建第一层的多个模型,这些模型可以使同质的也可以是异质的;
(3) 使用train_set训练步骤2中的多个模型,然后用训练好的模型预测val_set和test_set得到val_predict, test_predict1;
(4) 创建第二层的模型,使用val_predict作为训练集训练第二层的模型;
(5) 使用第二层训练好的模型对第二层测试集test_predict1进行预测,该结果为整个测试集的结果。
Linear Blending(线性融合)
一般而言, 在个体学习器性能相近时适合使用均匀融合(每个模型g的作用相同),个体学习器性能相差较大时,使用加权平均给每个g都一个不同的权重,效果可能会更好,这就是线性融合(Linear Blending)
Notes(stacking和blending区别):
stacking是k折交叉验证,元模型的训练数据等同于基于模型的训练数据,该方法为每个样本都生成了元特征,每生成元特征的模型不一样(k是多少,每个模型的数量就是多少);测试集生成元特征时,需要用到k(k fold不是模型)个加权平均;
blending是holdout方法,直接将训练集切割成两个部分,仅10%用于元模型的训练;
代码(以鸢尾花为例)
# 加载相关工具包
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use("ggplot")
%matplotlib inline
import seaborn as sns
导入鸢尾花的数据集,提取两个特征
# 创建数据
from sklearn import datasets
from sklearn.datasets import make_blobs
from sklearn.model_selection import train_test_split
from sklearn import datasets #导入方法类
iris = datasets.load_iris() #加载 iris 数据集
x = iris.data[:,:2] #特征数据
y = iris.target #分类数据
## 创建训练集和测试集
X_train1,X_test,y_train1,y_test = train_test_split(x, y, test_size=0.2, random_state=1)
## 创建训练集和验证集
X_train,X_val,y_train,y_val = train_test_split(X_train1, y_train1, test_size=0.3, random_state=1)
print("The shape of training X:",X_train.shape)
print("The shape of training y:",y_train.shape)
print("The shape of test X:",X_test.shape)
print("The shape of test y:",y_test.shape)
print("The shape of validation X:",X_val.shape)
print("The shape of validation y:",y_val.shape)
The shape of training X: (84, 2)
The shape of training y: (84,)
The shape of test X: (30, 2)
The shape of test y: (30,)
The shape of validation X: (36, 2)
The shape of validation y: (36,)
# 设置第一层分类器
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
#clfs = [SVC(probability = True),RandomForestClassifier(n_estimators=5, n_jobs=-1, criterion='gini'),KNeighborsClassifier()]
clfs = [SVC(probability = True,C= 1, kernel= 'linear'),
RandomForestClassifier(n_estimators=30, max_depth=9,min_samples_split=50,n_jobs=-1,criterion='gini'),
KNeighborsClassifier(n_neighbors=7)]
# 设置第二层分类器
from sklearn.linear_model import LinearRegression
lr = LinearRegression()
# 输出第一层的验证集结果与测试集结果
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
# 将第一层的验证集的结果输入第二层训练第二层分类器
lr.fit(val_features,y_val)
# 输出预测的结果
from sklearn.model_selection import cross_val_score
cross_val_score(lr,test_features,y_test,cv=5)
array([-0.18611117, 0.55012112, 0.47358219, 0.63868026, 0.36940921])
x_min = X_train[:, 0].min() - 1
x_max = X_train[:, 0].max() + 1
y_min = X_train[:, 1].min() - 1
y_max = X_train[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1),np.arange(y_min, y_max, 0.1))
Z = lr.predict(np.c_[xx.ravel(), yy.ravel()])
Z = clfs.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, alpha=0.3)
plt.scatter(x[:,0],x[:,1],c=y)
plt.xlim(xx.min(),xx.max())
plt.ylim(yy.min(),.max())
plt.show()
有时间了还需要在修改