本文主要是介绍集成学习下 01 blending集成学习算法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
集成学习下 01 blending集成学习算法
导读:开源学习地址datawhale
1.何为blending?
blending类似于对多个模型的效果进行融合,具体如下:
1)将数据划分为训练集和测试集,训练集再划分为训练集train_set和验证集val_set
2) 建立第一层的多个模型,通过train_set训练第一层的模型,预测val_set和测试集,得到val_predict和test_predict1
3)创建第二层的模型,根据val_predict训练第二层的模型
4)根据训练好的第二层模型,预测test_predict1。预测结果为整个测试集的结果
2.示例
#方法二
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#获取鸢尾花数据
#仅仅考虑0,1类鸢尾花
iris = datasets.load_iris()
X = iris.data
y = iris.target
features = iris.feature_names
iris_data = pd.DataFrame(X, columns=features)
iris_data['target'] = y
# 数据预处理
# 仅仅考虑0,1类鸢尾花
iris_data = iris_data.loc[iris_data.target.isin([0, 1])]
y = iris_data['target'].values
X = iris_data[['sepal length (cm)', 'sepal width (cm)']].values## 创建训练集和测试集
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)# 设置第一层分类器
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifierclfs = [SVC(probability = True),RandomForestClassifier(),KNeighborsClassifier()]# 设置第二层分类器
from sklearn.linear_model import LogisticRegression
lr = LogisticRegression()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(X_val)test_feature = clf.predict(X_test)val_features[:,i] = val_featuretest_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)#默认计算的是模型精度
The shape of training X: (56, 2)
The shape of training y: (56,)
The shape of test X: (20, 2)
The shape of test y: (20,)
The shape of validation X: (24, 2)
The shape of validation y: (24,)
Out[200]:
array([1., 1., 1., 1., 1.])
#决策边界
x_min, x_max = X_test[:, 0].min() - 1, X_test[:, 0].max() + 1
y_min, y_max = X_test[:, 1].min() - 1, X_test[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1),np.arange(y_min, y_max, 0.1))
# Obtain labels for each point in mesh using the model.
X_TEST=np.c_[xx.ravel(), yy.ravel()]
meta_X=np.zeros((len(X_TEST),len(clfs)))
for i,clf in enumerate(clfs):yhat= clf.predict(X_TEST)meta_X[:,i]=yhat
# 第二层模型预测
Z = lr.predict(meta_X).reshape(-1, 1).reshape(xx.shape)
plt.contourf(xx, yy, Z, alpha=0.3)
plt.scatter(X_test[y_test == 0, 0], X_test[y_test == 0, 1], c='blue', marker='^')
plt.scatter(X_test[y_test == 1, 0], X_test[y_test == 1, 1], c='red', marker='o')
这篇关于集成学习下 01 blending集成学习算法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!