集成模型

Bagging思想
- 先构建,后结合(投票法,带权投票法,学习法)
- 个体学习器之间不存在强依赖关系,一系列个体学习器可以并行生成,然后使用组合策略,得到最终的集成模型,这就是Bagging的思想

Bagging分类例题

代码实现
import pandas as pd
from sklearn.tree import DecisionTreeClassifier
import numpy as np
df = pd.DataFrame([[0,1],[1,1],[2,1],[3,-1],[4,-1],
[5,-1],[6,1],[7,1],[8,1],[9,-1]])
M =[] # 存储决策树模型的数组
n_trees = 20 # 设置树的颗数
for i in range(n_trees):
tmp = df.sample(frac=1,replace=True)# 对样本进行采样,目的是建造不同的树
X = tmp.iloc[:,:-1]# 构造X
Y = tmp.iloc[:,-1]# 构造Y
model =DecisionTreeClassifier(max_depth=2) # 新建决策树模型
model.fit(X,Y)
# 将决策树模型加入数组
M.append(model)
# 打印每个基础模型的效果
X = df.iloc[:,:-1]# 获取全部数据的X
Y = df.iloc[:,-1] # 获取全部数据的Y
res = 0 # 初始化全零向量
for i in M: # 遍历模型数组
res += i.predict(X) # 将每个模型预测值叠加到res变量
# 取平均输出最终对每个样本标签的预测值
res = np.sign(res)
print(res)
'''
# 效果
>>[ 1 1 1 -1 -1 -1 1 1 1 1]
'''
版权声明:本文为qq872890060原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。