集成学习之Blending

编程入门 行业动态 更新时间:2024-10-27 00:28:48

集成学习之<a href=https://www.elefans.com/category/jswz/34/1654173.html style=Blending"/>

集成学习之Blending

一、Blending思想和主要步骤

简单来说,就是“它山之石可以攻玉”。

  1. 将数据划分为训练集和测试集,其中训练集需要再次划分为训练集(train_set)和验证集(val_set);
  2. 创建第一层的多个模型,这些模型可以使同质的也可以是异质的;
  3. 使用train_set和y_train训练步骤2中的多个模型,然后用训练好的模型预测val_set和test_set得到val_predict, test_predict;
  4. 创建第二层的模型,使用val_predict和y_val作为训练集训练第二层的模型;
  5. 使用第二层训练好的模型对第二层测试集test_predict进行预测,该结果为整个测试集的结果

二、Blending流程图

三、Blending代码实现

# 加载相关工具包
import numpy as np
import pandas as pd 
import matplotlib.pyplot as plt
plt.style.use("ggplot")
%matplotlib inline
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
from sklearn import datasets 
from sklearn.datasets import make_blobs
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.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score# 创建数据
data, target = make_blobs(n_samples=10000, centers=2, random_state=1, cluster_std=1.0)
## 创建训练集和测试集
X_train1,X_test,y_train1,y_test = train_test_split(data, target, 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)
#  设置第一层学习器
clfs = [SVC(probability = True),RandomForestClassifier(n_estimators=5, n_jobs=-1, criterion='gini'),KNeighborsClassifier()]
# 设置第二层学习器
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_featuretest_features[:,i] = test_feature
# 将第一层的验证集的结果输入第二层训练第二层分类器
lr.fit(val_features,y_val)
# 输出预测的结果 采用10折交叉验证
result = cross_val_score(lr,test_features,y_test,cv=5)
resultThe shape of training X: (5600, 2)
The shape of training y: (5600,)
The shape of test X: (2000, 2)
The shape of test y: (2000,)
The shape of validation X: (2400, 2)
The shape of validation y: (2400,)
array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])

四、Iris数据集实现

使用Blending方式对iris数据集进行预测,并用第四章的决策边界画出来,找找规律。

参考文献

[1].DataWhale组队学习-集成学习(下)

[2].图解Blending&Stacking

更多推荐

集成学习之Blending

本文发布于:2024-02-11 17:46:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1682397.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Blending

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!