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

相关文章

Go语言实现桥接模式

《Go语言实现桥接模式》桥接模式是一种结构型设计模式,它将抽象部分与实现部分分离,使它们可以独立地变化,本文就来介绍一下了Go语言实现桥接模式,感兴趣的可以了解一下... 目录简介核心概念为什么使用桥接模式?应用场景案例分析步骤一:定义实现接口步骤二:创建具体实现类步骤三:定义抽象类步骤四:创建扩展抽象类步

Spring Boot 集成 mybatis核心机制

《SpringBoot集成mybatis核心机制》这篇文章给大家介绍SpringBoot集成mybatis核心机制,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值... 目录Spring Boot浅析1.依赖管理(Starter POMs)2.自动配置(AutoConfigu

SpringBoot集成iText快速生成PDF教程

《SpringBoot集成iText快速生成PDF教程》本文介绍了如何在SpringBoot项目中集成iText9.4.0生成PDF文档,包括新特性的介绍、环境准备、Service层实现、Contro... 目录SpringBoot集成iText 9.4.0生成PDF一、iText 9新特性与架构变革二、环

JAVA SpringBoot集成Jasypt进行加密、解密的详细过程

《JAVASpringBoot集成Jasypt进行加密、解密的详细过程》文章详细介绍了如何在SpringBoot项目中集成Jasypt进行加密和解密,包括Jasypt简介、如何添加依赖、配置加密密钥... 目录Java (SpringBoot) 集成 Jasypt 进行加密、解密 - 详细教程一、Jasyp

Java领域模型示例详解

《Java领域模型示例详解》本文介绍了Java领域模型(POJO/Entity/VO/DTO/BO)的定义、用途和区别,强调了它们在不同场景下的角色和使用场景,文章还通过一个流程示例展示了各模型如何协... 目录Java领域模型(POJO / Entity / VO/ DTO / BO)一、为什么需要领域模

C++中的解释器模式实例详解

《C++中的解释器模式实例详解》这篇文章总结了C++标准库中的算法分类,还介绍了sort和stable_sort的区别,以及remove和erase的结合使用,结合实例代码给大家介绍的非常详细,感兴趣... 目录1、非修改序列算法1.1 find 和 find_if1.2 count 和 count_if1

Redis中群集三种模式的实现

《Redis中群集三种模式的实现》Redis群集有三种模式,分别是主从同步/复制、哨兵模式、Cluster,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 目录1. Redis三种模式概述2、Redis 主从复制2.1 主从复制的作用2.2 主从复制流程2

深入理解Redis线程模型的原理及使用

《深入理解Redis线程模型的原理及使用》Redis的线程模型整体还是多线程的,只是后台执行指令的核心线程是单线程的,整个线程模型可以理解为还是以单线程为主,基于这种单线程为主的线程模型,不同客户端的... 目录1 Redis是单线程www.chinasem.cn还是多线程2 Redis如何保证指令原子性2.

深入理解MySQL流模式

《深入理解MySQL流模式》MySQL的Binlog流模式是一种实时读取二进制日志的技术,允许下游系统几乎无延迟地获取数据库变更事件,适用于需要极低延迟复制的场景,感兴趣的可以了解一下... 目录核心概念一句话总结1. 背景知识:什么是 Binlog?2. 传统方式 vs. 流模式传统文件方式 (非流式)流

springBoot (springCloud2025)集成redisCluster 集群的操作方法

《springBoot(springCloud2025)集成redisCluster集群的操作方法》文章介绍了如何使用SpringBoot集成RedisCluster集群,并详细说明了pom.xm... 目录pom.XMLapplication.yamlcluster配置类其他配置类连接池配置类Redis