集成学习之-stacking

一、引言

对于单模型来说,模型的抗干扰能力低,且难以拟合复杂的数据。
所以可以集成多个模型的优缺点,提高泛化能力。
集成学习一般有三种:boosting是利用多个弱学习器串行,逐个纠错,构造强学习器。
bagging是构造多个独立的模型,然后增强泛化能力。
而stacking结合了以上两种方式,将xy先进行n-fold,然后分给n个基学习器学习,再将n个输出的预测值进行堆叠,形成新的样本数据作为x。新的x和旧的y交给第二层模型进行拟合。

二、代码

import numpy as np
from sklearn.model_selection import KFold
from sklearn import datasets
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
class MyStacking:

初始化模型参数

def init(self, estimators, final_estimator, cv=5, method='predict'):
self.cv = cv
self.method = method
self.estimators = estimators
self.final_estimator = final_estimator

模型训练

def fit(self, X, y):

获得一级输出

dataset_train = self.stacking(X, y)

模型融合

self.final_estimator.fit(dataset_train, y)

堆叠输出

def stacking(self, X, y):
kf = KFold(n_splits=self.cv, shuffle=True, random_state=2021)

获得一级输出

dataset_train = np.zeros((X.shape0, len(self.estimators)))
for i, model in enumerate(self.estimators):
for (train, val) in kf.split(X, y):
X_train = Xtrain
X_val = Xval
y_train = ytrain
y_val_pred = model.fit(X_train, y_train).predict(X_val)
dataset_trainval, i = y_val_pred
self.estimatorsi = model
return dataset_train

模型预测

def predict(self, X):
datasets_test = np.zeros((X.shape0, len(self.estimators)))
for i, model in enumerate(self.estimators):
datasets_test:, i = model.predict(X)
return self.final_estimator.predict(datasets_test)

模型精度

def score(self, X, y):
datasets_test = np.zeros((X.shape0, len(self.estimators)))
for i, model in enumerate(self.estimators):
datasets_test:, i = model.predict(X)
return self.final_estimator.score(datasets_test, y)
if name == 'main':
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, train_size=0.7, random_state=0)
estimators = RandomForestClassifier(n_estimators=10), GradientBoostingClassifier(n_estimators=10)
clf = MyStacking(estimators=estimators,
final_estimator=LogisticRegression())
clf.fit(X_train, y_train)
print(clf.score(X_train, y_train))
print(clf.score(X_test, y_test))

相关推荐
H03111698516 分钟前
App竞品数据查询工具整理 月狐数据 蝉大师 点点数据功能概览
人工智能
叠层归一研究院1 小时前
基于极限自指的叠层归一宇宙结构理论——无元外部封闭系统的内生区分模型
人工智能·经验分享·算法·agi
IT_陈寒1 小时前
Java线程池用错参数,我的服务居然悄悄崩溃了
前端·人工智能·后端
why-geo1 小时前
Hermes Agent 与 Python 的会产生什么样的碰撞
人工智能·python·ai编程
正经教主1 小时前
【FDE系列】阶段2:Day 29:FastAPI 进阶 — Pydantic 模型与完整 CRUD 实战
人工智能·python·fde
时速GEO系统1 小时前
初元 AI V1.1 版本升级,首个正式版发布一周・实现生成、部署、上线、优化全流程自动化闭环
人工智能·数据挖掘·node.js
咕泡科技1 小时前
咕泡科技FDE系列最新产品重磅发布!
人工智能·大模型·ai落地·fde·前沿部署工程师
犀利豆2 小时前
为什么全世界的 AI 都画不好一只骑自行车的鹈鹕
人工智能·llm·aigc
天天被压力2 小时前
【跨市场数据实战 #08】可转债折价机会怎么筛:3个接口抓比价、列表和实时盘口
java·人工智能·python
baopixiaoz2 小时前
BeeQuant × BeeAgent:用AI加速策略验证
大数据·人工智能·python·区块链