没有合适的资源?快使用搜索试试~ 我知道了~
二手车交易价格预测_Task5_模型融合
7 下载量 132 浏览量
2020-12-21
16:26:01
上传
评论 2
收藏 229KB PDF 举报
温馨提示
试读
13页
模型融合_代码示例部分 #导入工具包 import numpy as np import pandas as pd from sklearn import metrics from sklearn import linear_model from sklearn.datasets import make_blobs # 这是打包好的波士顿房价数据集 from sklearn import datasets from sklearn.tree import DecisionTreeClassifier # 分类决策树模型 from sklearn.ensemble import
资源详情
资源评论
资源推荐
二手车交易价格预测二手车交易价格预测_Task5_模型融合模型融合
模型融合模型融合_代码示例部分代码示例部分
#导入工具包导入工具包
import numpy as np
import pandas as pd
from sklearn import metrics
from sklearn import linear_model
from sklearn.datasets import make_blobs # 这是打包好的波士顿房价数据集
from sklearn import datasets
from sklearn.tree import DecisionTreeClassifier # 分类决策树模型
from sklearn.ensemble import RandomForestClassifier # 随机森林回归模型
from sklearn.ensemble import VotingClassifier # 分类投票模型
from xgboost import XGBClassifier # xgboost用于解决f分类问题
from sklearn.linear_model import LogisticRegression # 逻辑回归模型
from sklearn.svm import SVC # 支持向量机模型 - 用于分类问题
from sklearn.svm import SVR # 支持向量机模型 - 用于回归问题
from sklearn.model_selection import train_test_split # 用于拆分训练集和测试集
from sklearn.datasets import make_moons # 创建月亮形的数据集
from sklearn.metrics import accuracy_score, roc_auc_score # ROC-Auc指标,评价模型得分用的
from sklearn.model_selection import cross_val_score # 用于做交叉验证
from sklearn.model_selection import GridSearchCV # 用于网格搜索
from sklearn.model_selection import StratifiedKFold # 分层交叉验证,每一折中都保持着原始数据中各个类别的比例关系
from sklearn.ensemble import ExtraTreesClassifier, GradientBoostingClassifier, GradientBoostingRegressor
import lightgbm as lgb
import xgboost as xgb
from sklearn.metrics import mean_squared_error, mean_absolute_error
import itertools # 用于创建自定义的迭代器
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec # 用于调整子图的位置大小
from sklearn.neighbors import KNeighborsClassifier # k近邻分类算法
from sklearn.naive_bayes import GaussianNB # 先验为高斯分布的朴素贝叶斯
from mlxtend.classifier import StackingClassifier # 快速完成对sklearn模型的stacking
from mlxtend.plotting import plot_learning_curves # 绘制学习曲线
from mlxtend.plotting import plot_decision_regions # 绘制决策边界
from sklearn import preprocessing # 数据归一化(标准化)
from sklearn.decomposition import PCA, FastICA, FactorAnalysis, SparsePCA # 用于降维等特征处理
import warnings
warnings.filterwarnings('ignore') # 忽略警告
# 简单加权平均简单加权平均-结果直接融合结果直接融合
'''
生成一些简单的样本数据,
test_prei - 代表第i个模型的预测值
y_test_true - 代表真实值
'''
test_pre1 = [1.2, 3.2, 2.1, 6.2] test_pre2 = [0.9, 3.1, 2.0, 5.9] test_pre3 = [1.1, 2.9, 2.2, 6.0] y_test_true = [1, 3, 2, 6]
# 定义结果的加权平均函数定义结果的加权平均函数 – 根据加权计算根据加权计算
def weighted_method(test_pre1, test_pre2, test_pre3, w=[1/3, 1/3, 1/3]):
weighted_result = w[0] * pd.Series(test_pre1) + w[1] * pd.Series(test_pre2) + w[2] * pd.Series(test_pre3)
return weighted_result
# 根据各模型的预测结果计算根据各模型的预测结果计算MAE
'''
metrics.mean_absolute_error - 多维数组MAE的计算方法
'''
print('Pred1 MAE:', metrics.mean_absolute_error(y_test_true, test_pre1))
print('Pred2 MAE:', metrics.mean_absolute_error(y_test_true, test_pre2))
print('Pred3 MAE:', metrics.mean_absolute_error(y_test_true, test_pre3))
Pred1 MAE: 0.1750000000000001
Pred2 MAE: 0.07499999999999993
Pred3 MAE: 0.10000000000000009
# 根据加权计算根据加权计算MAE
## 定义比重权值定义比重权值
w = [0.3, 0.4, 0.3] weighted_pre = weighted_method(test_pre1, test_pre2, test_pre3, w)
print('Weighted_pre MAE:', metrics.mean_absolute_error(y_test_true, weighted_pre))
Weighted_pre MAE: 0.05750000000000027
# 定义结果的加权平均函数定义结果的加权平均函数 – mean平均平均
def mean_method(test_pre1, test_pre2, test_pre3):
mean_result = pd.concat([pd.Series(test_pre1),
pd.Series(test_pre2),
pd.Series(test_pre3)], axis=1).mean(axis=1)
return mean_result
# 根据均值计算根据均值计算MAE
Mean_pre = mean_method(test_pre1, test_pre2, test_pre3)
print('Mean_pre MAE:', metrics.mean_absolute_error(y_test_true, Mean_pre))
Mean_pre MAE: 0.06666666666666693
# 定义结果的加权平均函数定义结果的加权平均函数 – median平均平均
def median_method(test_pre1, test_pre2, test_pre3):
median_result = pd.concat([pd.Series(test_pre1),
pd.Series(test_pre2),
pd.Series(test_pre3)], axis=1).median(axis=1)
return median_result
# 根据中位数计算根据中位数计算MAE
Median_pre = median_method(test_pre1, test_pre2, test_pre3)
print('Median_pre MAE:', metrics.mean_absolute_error(y_test_true, Median_pre))
Median_pre MAE: 0.07500000000000007
# Stacking融合融合(回归回归)
# 定义定义Stacking融合函数融合函数
def Stacking_method(train_reg1, train_reg2, train_reg3,
y_train_true,
test_pre1, test_pre2, test_pre3,
model_L2=linear_model.LinearRegression()):
'''
:param train_reg1: 第一个模型预测train得到的标签
:param train_reg2: 第二个模型预测train得到的标签
:param train_reg3: 第三个模型预测train得到的标签
:param y_train_true: train真实的标签
:param test_pre1: 第一个模型预测test得到的标签
:param test_pre2: 第二个模型预测test得到的标签
:param test_pre3: 第三个模型预测test得到的标签
:param model_L2: 次级模型:以真实训练集的标签为标签,以多个模型训练训练集后得到的标签合并后的数据集为特征进行训练
注意:次级模型不宜选取的太复杂,这样会导致模型在训练集上过拟合,测试集泛化效果差
:return: 训练好的次机模型预测test数据集得到的预测值 - Stacking_result
'''
model_L2.fit(pd.concat([pd.Series(train_reg1), pd.Series(train_reg2), pd.Series(train_reg3)], axis=1).values,
y_train_true) # 次级模型训练
stacking_result = model_L2.predict(pd.concat([pd.Series(test_pre1),
pd.Series(test_pre2), pd.Series(test_pre3)], axis=1).values)
return stacking_result
# 生成一些简单的样本数据生成一些简单的样本数据,test_prei代表第代表第i个模型的预测值个模型的预测值,y_test_true代表模型的真实值代表模型的真实值
train_reg1 = [3.2, 8.2, 9.1, 5.2] train_reg2 = [2.9, 8.1, 9.0, 4.9] train_reg3 = [3.1, 7.9, 9.2, 5.0] y_train_true = [3, 8, 9, 5]
test_pre1 = [1.2, 3.2, 2.1, 6.2] test_pre2 = [0.9, 3.1, 2.0, 5.9] test_pre3 = [1.1, 2.9, 2.2, 6.0] y_test_true = [1, 3, 2, 6]
# 看一下看一下Stacking融合的效果融合的效果
model_L2 = linear_model.LinearRegression() # 不设定这个参数也可以,创建函数的时候默认了
Stacking_pre = Stacking_method(train_reg1, train_reg2, train_reg3, y_train_true,
test_pre1, test_pre2, test_pre3, model_L2)
print('Stacking_pre MAE: ', metrics.mean_absolute_error(y_test_true, Stacking_pre))
Stacking_pre MAE: 0.042134831460675204
# 发现模型效果相对于之前有了更近一步的提升
# 分类模型融合分类模型融合 – Voting,Stacking…
# Voting投票机制投票机制
'''
Voting - 投票机制
1.硬投票 - 对多个模型直接进行投票,不区分模型结果的相对重要度,最终投票数最多的类为最终被预测的类
2.软投票 - 和硬投票原理相同,增加了设置权重的功能,可以为不同模型设置不同权重,进而区别模型不同的重要度
'''
# # 硬投票
iris = datasets.load_iris() # 读取鸢尾花数据集 - 分类问题
x = iris.data # 分离特征集和标签
y = iris.target
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3) # 训练集和测试集按照7:3比例切分
# 用用XGB分类模型训练数据分类模型训练数据
'''
colsample_bytree - 训练每棵树时,使用的特征占全部特征的比例
objective - 目标函数
二分类问题 - binary:logistic - 返回概率
'''
clf1 = XGBClassifier(learning_rate=0.1, n_estimators=150, max_depth=3, min_child_weight=2, subsample=0.7,
colsample_bytree=0.6, objective='binary:logistic')
# 用随机森林分类模型训练数据用随机森林分类模型训练数据
'''
n_estimators - 随机森林中决策树的个数
max_depth - 决策树的最大深度
如果值为None,那么会扩展节点,直到所有的叶子是纯净的,或者直到所有叶子包含少于min_sample_split的样本
min_samples_split - 分割内部节点所需要的最小样本数量
min_samples_leaf - 需要在叶子结点上的最小样本数量
oob_score - 是否使用袋外样本来估计泛化精度
树的生成过程并不会使用所有的样本,未使用的样本就叫(out_of_bag)oob袋外样本,通过袋外样本,可以评估这个树的准确度
'''
clf2 = RandomForestClassifier(n_estimators=50, max_depth=1, min_samples_split=4,
min_samples_leaf=63, oob_score=True)
# 用用SVC训练数据训练数据
'''
支持向量机 - 分类算法,但是也可以做回归,根据输入的数据不同可做不同的模型
1.若输入标签为连续值则做回归
2.若输入标签为分类值则用SVC()做分类
支持向量机的学习策略是间隔最大化,最终可转化为一个凸二次规划问题的求解
参数详解:
C - 惩罚参数; 值越大,对误分类的惩罚大,不容犯错,于是训练集测试准确率高,但是泛化能力弱
值越小,对误分类的惩罚小,允许犯错,泛化能力较强
probability - 是否采用概率估计,默认为False
'''
clf3 = SVC(C=0.1)
# 硬投票硬投票
'''
eclf - 其实就是三个模型的集成算法,硬投票决定最终被预测的类
'''
eclf = VotingClassifier(estimators=[('xgb', clf1), ('rf', clf2), ('svc', clf3)], voting='hard') # 本质是Ensemble
for clf, label in zip([clf1, clf2, clf3, eclf], ['XGBBoosting', 'Random Forest', 'SVM', 'Ensemble']):
scores = cross_val_score(clf, x, y, cv=5, scoring='accuracy') # 以准确度度量评分
print('Accuracy: %0.2f (+/- %0.2f) [%s]' % (scores.mean(), scores.std(), label))
Accuracy: 0.96 (+/- 0.02) [XGBBoosting] Accuracy: 0.33 (+/- 0.00) [Random Forest] Accuracy: 0.92 (+/- 0.03) [SVM] Accuracy: 0.95 (+/-
0.05) [Ensemble]
# 软投票软投票
x = iris.data
y = iris.target
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3)
clf1 = XGBClassifier(learning_rate=0.1, n_estimators=150, max_depth=3, min_child_weight=2, subsample=0.8,
colsample_bytree=0.8, objective='binary:logistic')
clf2 = RandomForestClassifier(n_estimators=50, max_depth=1, min_samples_split=4,
min_samples_leaf=63, oob_score=True)
clf3 = SVC(C=0.1, probability=True)
eclf = VotingClassifier(estimators=[('xgb', clf1), ('rf', clf2), ('svc', clf3)], voting='soft', weights=[2, 1, 1])
for clf, label in zip([clf1, clf2, clf3, eclf], ['XGBBoosting', 'Random Forest', 'SVM', 'Ensemble']):
scores = cross_val_score(clf, x, y, cv=5, scoring='accuracy') # 以准确度度量评分
print('Accuracy: %0.2f (+/- %0.2f) [%s]' % (scores.mean(), scores.std(), label))
Accuracy: 0.96 (+/- 0.02) [XGBBoosting] Accuracy: 0.33 (+/- 0.00) [Random Forest] Accuracy: 0.92 (+/- 0.03) [SVM] Accuracy: 0.96 (+/-
0.02) [Ensemble]
# 分类的分类的Stacking/Blending融合融合
'''
Stacking是一种分层模型集成框架,以两层为例
第一层由多个基学习器组成,其输入为原始训练集
第二层的模型则是以第一层学习器的输出作为训练集进行再训练,从而得到完整的stacking模型
'''
# ## 创建训练用的数据集
data_0 = iris.data
data = data_0[:100, :] # 100个样本
target_0 = iris.target
target = target_0[:100]
# ## 模型融合中使用到的各个单模型
'''
LogisticRegression()
solver - 用来优化权重 {‘lbfgs’, ‘sgd’, ‘adam’},默认adam,
lbfgs - quasi-Newton方法的优化器:对小数据集来说,lbfgs收敛更快效果也更好
sgd - 随机梯度下降
adam - 机遇随机梯度的优化器
RandomForestClassifier()
n_estimators - 决策树个数
n_jobs - 用于拟合和预测的并行运行的工作数量,如果值为-1,那么工作数量被设置为核的数量
criterion - 衡量分裂质量的性能
剩余12页未读,继续阅读
weixin_38623255
- 粉丝: 4
- 资源: 919
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
最新资源
- 毕业设计-仿生六足机器人的制作全教程源码+电子元器件+程序代码+线路组件图+安装教程+搭建视频教程
- 基于ROS和webots的xrobot机械臂仿真初探C++源码
- 基于ROS的点焊机器人仿真与控制python源码+文档说明+使用说明+详细注释
- 基于vue实现的细粒度交通时空大数据分析系统+源代码+文档说明
- 安卓大作业-基于Electron的交通时空大数据分析挖掘系统客户端(Android)+源代码+文档说明+界面截图
- 基于Java的朱氏集团客户关系管理系统设计源码
- 基于C++的作业提交与批改系统设计源码
- 基于Vue2的移动端电影资讯网站设计源码
- 高分课程设计作业-基于QT的模仿宝石迷阵游戏C++源码+文档说明+界面截图
- 基于Apache Spark的Spark DistCP重实现设计源码
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
评论0