DataWhale-树模型与集成学习-Task04-集成模式-202110

2023-12-27 21:58

本文主要是介绍DataWhale-树模型与集成学习-Task04-集成模式-202110,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

part B:集成模式:4. 两种并行集成的树模型

一、练习题

1. 练习题1

 解答:均方误差RMSE是预测值与真实值得误差平方根的均值。r2_score方法是将预测值和只使用均值的情况下相比,看能好多少。

                                          RMSE=\sqrt{\frac{1}{n}\sum_{i=1}^n(y_i-\bar{y})^2}

                                           R^2=1-\frac{\sum_{i=1}^n(y_i-\hat{y}_i)^2}{\sum_{i=1}^{n}(y_i-\bar{y})^2}

当量纲不同时,r2_score更容易衡量模型的效果好坏。

2. 练习题2

 解答: 没有影响,因为只是对应位置上的值相减,和位置的顺序没有关系。

二、知识回顾

4. 什么是随机森林的oob得分?

解答:

      随机森林由于每一个基学习器使用了重复抽样得到的数据集进行训练,因此总存在比例大约为1-e^-1的数据集没有参与训练,我们把这一部分数据称为out-of-bag样本,简称oob样本。此时,对每一个基学习器训练完毕后,我们都对oob样本进行预测,每个样本对应的oob_prediction_值为所有没有采样到该样本进行训练的基学习器预测结果均值。在得到所有样本的oob_prediction_后,对于回归问题,使用r2_score来计算对应的oob_score_,而对于分类问题,直接使用accuracy_score来计算oob_score_。

5. 随机森林是如何集成多个决策树模型的?

解答:

      当处理回归问题时,输出值为各学习器的均值;当处理分类问题时有两种策略,第一种是原始论文中使用的投票策略,即每个学习器输出一个类别,返回最高预测频率的类别,第二种是sklearn中采用的概率聚合策略,即通过各个学习器输出的概率分布先计算样本属于某个类别的平均概率,在对平均的概率分布取argmax以输出最可能的类别。

6. 请叙述孤立森林的算法原理和流程

 解答:

     多次随机选取特征和对应的分割点以分开空间中样本点,那么异常点很容易在较早的几次分割中就已经与其他样本隔开,正常点由于较为紧密故需要更多的分割次数才能将其分开。

       对于n个样本而言,我们可以构建一棵在每个分支进行特征大小判断的树来将样本分派到对应的叶子节点,为了定量刻画异常情况,在这篇文献中证明了树中的平均路径(即树的根节点到叶子结点经过的节点数)长度c为

                                           c(n)=2H(n-1)-\frac{2(n-1)}{n}

       此时对于某个样本x,假设其分派到叶子节点的路径长度为h(x),我们就能用h(x)/c(n)的大小来度量异常的程度,该值越小则越有可能为异常点。由于单棵树上使用的是随机特征的随机分割点,稳健度较差,因此孤立森林将建立t棵树,每棵树上都在数据集上抽样出ψ个样本进行训练。为了总和集成的结果,我们定义指标

                                         s(x,n)=2^{-\frac{\mathbb{E}h(x)}{c{n}}}

 指数上\mathbb{E}h(x)  表示样本x在各树的路径平均值。我们可以规定树的生长停止当且仅当树的高度(路径的最大值)达到了给定的限定高度,或者叶子结点样本数仅为1,或者叶子节点样本数的所有特征值完全一致(即空间中的点重合,无法分离)。那么如何决定树的限定高度呢? 由于c(n)c与log⁡n数量级相同,故给定的限定高度可以设置为logn。            

三、代码实现

1. 分类的随机森林算法

import numpy as np
from sklearn.tree import DecisionTreeClassifier as ClassificationTree
from sklearn import datasets
from sklearn.model_selection import train_test_splitclass RandomForest():"""Random Forest classifier. Uses a collection of classification trees thattrains on random subsets of the data using a random subsets of the features.Parameters:-----------n_estimators: int树的数量The number of classification trees that are used.max_features: int每棵树选用数据集中的最大的特征数The maximum number of features that the classification trees are allowed touse.min_samples_split: int每棵树中最小的分割数,比如 min_samples_split = 2表示树切到还剩下两个数据集时就停止The minimum number of samples needed to make a split when building a tree.min_gain: float每棵树切到小于min_gain后停止The minimum impurity required to split the tree further.max_depth: int每棵树的最大层数The maximum depth of a tree."""def __init__(self, n_estimators=100, min_samples_split=2, min_gain=0,max_depth=7, max_features=None):self.n_estimators = n_estimators #树的数量self.min_samples_split = min_samples_split #每棵树中最小的分割数,比如 min_samples_split = 2表示树切到还剩下两个数据集时就停止self.min_gain = min_gain   #每棵树切到小于min_gain后停止self.max_depth = max_depth  #每棵树的最大层数self.max_features = max_features #每棵树选用数据集中的最大的特征数self.trees = []# 建立森林(bulid forest)for _ in range(self.n_estimators):tree = ClassificationTree(min_samples_split=self.min_samples_split, min_impurity_decrease=self.min_gain,max_depth=self.max_depth)self.trees.append(tree)def fit(self, X, Y):# 训练,每棵树使用随机的数据集(bootstrap)和随机的特征# every tree use random data set(bootstrap) and random featuresub_sets = self.get_bootstrap_data(X, Y)n_features = X.shape[1]if self.max_features == None:self.max_features = int(np.sqrt(n_features))for i in range(self.n_estimators):# 生成随机的特征# get random featuresub_X, sub_Y = sub_sets[i]idx = np.random.choice(n_features, self.max_features, replace=True)sub_X = sub_X[:, idx]self.trees[i].fit(sub_X, sub_Y)self.trees[i].feature_indices= idxprint("tree", i, "fit complete")def predict(self, X):y_preds = []for i in range(self.n_estimators):idx = self.trees[i].feature_indicessub_X = X[:, idx]y_pre = self.trees[i].predict(sub_X)y_preds.append(y_pre)y_preds = np.array(y_preds).Ty_pred = []for y_p in y_preds:# np.bincount()可以统计每个索引出现的次数# np.argmax()可以返回数组中最大值的索引# cheak np.bincount() and np.argmax() in numpy Docsy_pred.append(np.bincount(y_p.astype('int')).argmax())return y_preddef get_bootstrap_data(self, X, Y):# 通过bootstrap的方式获得n_estimators组数据# get int(n_estimators) datas by bootstrapm = X.shape[0] #行数Y = Y.reshape(m, 1)# 合并X和Y,方便bootstrap (conbine X and Y)X_Y = np.hstack((X, Y)) #np.vstack():在竖直方向上堆叠/np.hstack():在水平方向上平铺np.random.shuffle(X_Y) #随机打乱data_sets = []for _ in range(self.n_estimators):idm = np.random.choice(m, m, replace=True) #在range(m)中,有重复的选取 m个数字bootstrap_X_Y = X_Y[idm, :]bootstrap_X = bootstrap_X_Y[:, :-1]bootstrap_Y = bootstrap_X_Y[:, -1:]data_sets.append([bootstrap_X, bootstrap_Y])return data_setsif __name__ == '__main__':data = datasets.load_digits()X = data.datay = data.targetX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=2)print("X_train.shape:", X_train.shape)print("Y_train.shape:", y_train.shape)clf = RandomForest(n_estimators=100)clf.fit(X_train, y_train)y_pred = clf.predict(X_test)

2.  孤立森林算法

直接贴老师给的代码

from pyod.utils.data import generate_data
import matplotlib.pyplot as plt
import numpy as npclass Node:def __init__(self, depth):self.depth = depthself.left = Noneself.right = Noneself.feature = Noneself.pivot = Noneclass Tree:def __init__(self, max_height):self.root = Node(0)self.max_height = max_heightself.c = Nonedef _build(self, node, X,):if X.shape[0] == 1:returnif node.depth+1 > self.max_height:node.depth += self._c(X.shape[0])returnnode.feature = np.random.randint(X.shape[1])pivot_min = X[:, node.feature].min()pivot_max = X[:, node.feature].max()node.pivot = np.random.uniform(pivot_min, pivot_max)node.left, node.right = Node(node.depth+1), Node(node.depth+1)self._build(node.left, X[X[:, node.feature]<node.pivot])self._build(node.right, X[X[:, node.feature]>=node.pivot])def build(self, X):self.c = self._c(X.shape[0])self._build(self.root, X)def _c(self, n):if n == 1:return 0else:return 2 * ((np.log(n-1) + 0.5772) - (n-1)/n)def _get_h_score(self, node, x):if node.left is None and node.right is None:return node.depthif x[node.feature] < node.pivot:return self._get_h_score(node.left, x)else:return self._get_h_score(node.right, x)def get_h_score(self, x):return self._get_h_score(self.root, x)class IsolationForest:def __init__(self, n_estimators=100, max_samples=256):self.n_estimator = n_estimatorsself.max_samples = max_samplesself.trees = []def fit(self, X):for tree_id in range(self.n_estimator):random_X = X[np.random.randint(0, X.shape[0], self.max_samples)]tree = Tree(np.log(random_X.shape[0]))tree.build(X)self.trees.append(tree)def predict(self, X):result = []for x in X:h = 0for tree in self.trees:h += tree.get_h_score(x) / tree.cscore = np.power(2, - h/len(self.trees))result.append(score)return np.array(result)if __name__ == "__main__":np.random.seed(0)# 1%异常点X_train, X_test, y_train, y_test = generate_data(n_train=1000, n_test=500, contamination=0.05, behaviour="new", random_state=0)IF = IsolationForest()IF.fit(X_train)res = IF.predict(X_test)abnormal_X = X_test[res > np.quantile(res, 0.95)]plt.scatter(X_test[:, 0], X_test[:, 1], s=5)plt.scatter(abnormal_X[:, 0], abnormal_X[:, 1],s=30, edgecolors="Red", facecolor="none")plt.show()

这篇关于DataWhale-树模型与集成学习-Task04-集成模式-202110的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/544407

相关文章

Spring Boot集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控

Java设计模式---迭代器模式(Iterator)解读

《Java设计模式---迭代器模式(Iterator)解读》:本文主要介绍Java设计模式---迭代器模式(Iterator),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录1、迭代器(Iterator)1.1、结构1.2、常用方法1.3、本质1、解耦集合与遍历逻辑2、统一

Java 线程安全与 volatile与单例模式问题及解决方案

《Java线程安全与volatile与单例模式问题及解决方案》文章主要讲解线程安全问题的五个成因(调度随机、变量修改、非原子操作、内存可见性、指令重排序)及解决方案,强调使用volatile关键字... 目录什么是线程安全线程安全问题的产生与解决方案线程的调度是随机的多个线程对同一个变量进行修改线程的修改操

在Spring Boot中集成RabbitMQ的实战记录

《在SpringBoot中集成RabbitMQ的实战记录》本文介绍SpringBoot集成RabbitMQ的步骤,涵盖配置连接、消息发送与接收,并对比两种定义Exchange与队列的方式:手动声明(... 目录前言准备工作1. 安装 RabbitMQ2. 消息发送者(Producer)配置1. 创建 Spr

如何在Spring Boot项目中集成MQTT协议

《如何在SpringBoot项目中集成MQTT协议》本文介绍在SpringBoot中集成MQTT的步骤,包括安装Broker、添加EclipsePaho依赖、配置连接参数、实现消息发布订阅、测试接口... 目录1. 准备工作2. 引入依赖3. 配置MQTT连接4. 创建MQTT配置类5. 实现消息发布与订阅

SpringBoot集成LiteFlow工作流引擎的完整指南

《SpringBoot集成LiteFlow工作流引擎的完整指南》LiteFlow作为一款国产轻量级规则引擎/流程引擎,以其零学习成本、高可扩展性和极致性能成为微服务架构下的理想选择,本文将详细讲解Sp... 目录一、LiteFlow核心优势二、SpringBoot集成实战三、高级特性应用1. 异步并行执行2

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

Redis Cluster模式配置

《RedisCluster模式配置》:本文主要介绍RedisCluster模式配置,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录分片 一、分片的本质与核心价值二、分片实现方案对比 ‌三、分片算法详解1. ‌范围分片(顺序分片)‌2. ‌哈希分片3. ‌虚

SpringBoot集成LiteFlow实现轻量级工作流引擎的详细过程

《SpringBoot集成LiteFlow实现轻量级工作流引擎的详细过程》LiteFlow是一款专注于逻辑驱动流程编排的轻量级框架,它以组件化方式快速构建和执行业务流程,有效解耦复杂业务逻辑,下面给大... 目录一、基础概念1.1 组件(Component)1.2 规则(Rule)1.3 上下文(Conte

Go学习记录之runtime包深入解析

《Go学习记录之runtime包深入解析》Go语言runtime包管理运行时环境,涵盖goroutine调度、内存分配、垃圾回收、类型信息等核心功能,:本文主要介绍Go学习记录之runtime包的... 目录前言:一、runtime包内容学习1、作用:① Goroutine和并发控制:② 垃圾回收:③ 栈和