孤立森林算法 python_用Python实现孤立森林

2023-11-06

from random import sample, random, choice, randint

from math import ceil, log

from utils import run_time

class Node(object):

def __init__(self, size):

"""Node class to build tree leavesKeyword Arguments:size{int}-- Node size (default:{None})"""

# Node size

self.size = size

# Feature to split

self.split_feature = None

# Split point

self.split_point = None

# Left child node

self.left = None

# Right child node

self.right = None

class IsolationTree(object):

def __init__(self, X, n_samples, max_depth):

"""Isolation Tree classArguments:X{list}-- 2d list with int or floatn_samples{int}-- Subsample sizemax_depth{int}-- Maximum height of isolation tree"""

self.height = 0

# In case of n_samples is greater than n

n = len(X)

if n_samples > n:

n_samples = n

# Root node

self.root = Node(n_samples)

# Build isolation tree

self._build_tree(X, n_samples, max_depth)

def _get_split(self, X, idx, split_feature):

"""Randomly choose a split pointArguments:X{list}-- 2d list object with int or floatidx{list}-- 1d list object with intsplit_feature{int}-- Column index of XReturns:int -- split point"""

# The split point should be greater than min(X[feature])

unique = set(map(lambda i: X[i][split_feature], idx))

# Cannot split

if len(unique) == 1:

return None

unique.remove(min(unique))

x_min, x_max = min(unique), max(unique)

# Caution: random() -> x in the interval [0, 1).

return random() * (x_max - x_min) + x_min

def _build_tree(self, X, n_samples, max_depth):

"""The current node data space is divided into 2 sub space: less than thesplit point in the specified dimension on the left child of the current node,put greater than or equal to split point data on the current node's right child.Recursively construct new child nodes until the data cannot be splitted in thechild nodes or the child nodes have reached the max_depth.Arguments:X{list}-- 2d list object with int or floatn_samples{int}-- Subsample sizemax_depth{int}-- Maximum depth of IsolationTree"""

# Dataset shape

m = len(X[0])

n = len(X)

# Randomly selected sample points into the root node of the tree

idx = sample(range(n), n_samples)

# Depth, Node and idx

que = [[0, self.root, idx]]

# BFS

while que and que[0][0] <= max_depth:

depth, nd, idx = que.pop(0)

# Stop split if X cannot be splitted

nd.split_feature = choice(range(m))

nd.split_point = self._get_split(X, idx, nd.split_feature)

if nd.split_point is None:

continue

# Split

idx_left = []

idx_right = []

while idx:

i = idx.pop()

xi = X[i][nd.split_feature]

if xi < nd.split_point:

idx_left.append(i)

else:

idx_right.append(i)

# Generate left and right child

nd.left = Node(len(idx_left))

nd.right = Node(len(idx_right))

# Put the left and child into the que and depth plus one

que.append([depth+1, nd.left, idx_left])

que.append([depth+1, nd.right, idx_right])

# Update the height of IsolationTree

self.height = depth

def _predict(self, xi):

"""Auxiliary function of predict.Arguments:xi{list}-- 1D list with int or floatReturns:int -- the depth of the node which the xi belongs to"""

# Search xi from the IsolationTree until xi is at an leafnode

nd = self.root

depth = 0

while nd.left and nd.right:

if xi[nd.split_feature] < nd.split_point:

nd = nd.left

else:

nd = nd.right

depth += 1

return depth, nd.size

class IsolationForest(object):

def __init__(self):

"""IsolationForest, randomly build some IsolationTree instance,and the average score of each IsolationTreeAttributes:trees{list}-- 1d list with IsolationTree objectsajustment{float}"""

self.trees = None

self.adjustment = None # TBC

def fit(self, X, n_samples=100, max_depth=10, n_trees=256):

"""Build IsolationForest with dataset XArguments:X{list}-- 2d list with int or floatKeyword Arguments:n_samples{int}-- According to paper, set number of samples to 256 (default:{256})max_depth{int}-- Tree height limit (default:{10})n_trees{int}-- According to paper, set number of trees to 100 (default:{100})"""

self.adjustment = self._get_adjustment(n_samples)

self.trees = [IsolationTree(X, n_samples, max_depth)

for _ in range(n_trees)]

def _get_adjustment(self, node_size):

"""Calculate adjustment according to the formula in the paper.Arguments:node_size{int}-- Number of leaf nodesReturns:float -- ajustment"""

if node_size > 2:

i = node_size - 1

ret = 2 * (log(i) + 0.5772156649) - 2 * i / node_size

elif node_size == 2:

ret = 1

else:

ret = 0

return ret

def _predict(self, xi):

"""Auxiliary function of predict.Arguments:xi{list}-- 1d list object with int or floatReturns:list -- 1d list object with float"""

# Calculate average score of xi at each tree

score = 0

n_trees = len(self.trees)

for tree in self.trees:

depth, node_size = tree._predict(xi)

score += (depth + self._get_adjustment(node_size))

score = score / n_trees

# Scale

return 2 ** -(score / self.adjustment)

def predict(self, X):

"""Get the prediction of y.Arguments:X{list}-- 2d list object with int or floatReturns:list -- 1d list object with float"""

return [self._predict(xi) for xi in X]

@run_time

def main():

print("Comparing average score of X and outlier's score...")

# Generate a dataset randomly

n = 100

X = [[random() for _ in range(5)] for _ in range(n)]

# Add outliers

X.append([10]*5)

# Train model

clf = IsolationForest()

clf.fit(X, n_samples=500)

# Show result

print("Average score is%.2f" % (sum(clf.predict(X)) / len(X)))

print("Outlier's score is%.2f" % clf._predict(X[-1]))

if __name__ == "__main__":

main()

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

孤立森林算法 python_用Python实现孤立森林 的相关文章

  • 【2023.07.15】生成模型(三)Score-based Generative Models

    1 main contribution 来自Score based Generative Model的原文 1 提供了一个统一SMLD denoising score matching with langevin dynamics 和DDP
  • MPLS LDP的原理与配置

    一 LDP协议的概述 1 LDP会话 本地会话 LSR之间是直连的 双方使用组播地址224 0 0 2建立会话 远程会话 LSR之间可以是非直连的 双方建立会话是使用单播建立的 缺省是本地会话 2 LDP领接体 只要双方建立了会话之后就建立
  • Flink+Hudi 构架湖仓一体化解决方案

    摘要 本文详细介绍了 Flink Hudi 湖仓一体化方案的原型构建 主要内容为 Hudi 新架构与湖仓一体 最佳实践 Flink on Hudi Flink CDC 2 0 on Hudi Tips FFA 2021 重磅开启 点击 阅读
  • tcp第三次握手ack均是1?

    本人做了tcp连接测试 但是结果和网络中其他人的说法有点不一致 测试使用了命令 tcpdump s1用网卡ens33抓取端口好为80的网络数据包 tcpdump nn i ens33 port 80 s2访问百度 建立3次连接请求数据 cu
  • P1094 [NOIP2007 普及组] 纪念品分组 Python (贪心算法)

    题目地址 P1094 NOIP2007 普及组 纪念品分组 又是一道水题 但CSDN上没有详细Python代码 于是我就来水一贴 对于想要学算法提升能力的同学来说可以刷这套题单 能力全面提升综合题单 读完题目后我们可以快速得出 既然要求最小
  • 青少年CTFmisc-simpleness

    提示弱口令 爆破出hint的密码123456 hint zip里面解出两个文件 hint png hint rar 这个hint rar是伪加密 随便打开一个十六进制的编辑器 这里的24表示已加密 改成20表示未加密 打开hint txt
  • 8B10B编解码的Verilog实现

    此篇是我在学习中做的归纳与总结 其中如果存在版权或知识错误或问题请直接联系我 欢迎留言 PS 本着知识共享的原则 此篇博客可以转载 但请标明出处 目录 0 8B 10B编码 0 0 8B 10B编码原理 0 1 8B 10B编码的FPGA实
  • pycharm调整字母长度分割线为80

    写过 python 的同学都知道 python 代码默认一行的长度不超过 80 个字符 但是 pycharm 默认的分割线在第 120 个字符处 需要作如下修改 设置 File gt Settings gt Code Style gt Ri
  • JetBrains全家桶使用说明

    一 二 三 友情推荐 激活获取地址
  • 泰勒公式和二项式展开定理的共同点

    泰勒公式和二项式展开定理的共同点 对于f x 1 x n 采用泰勒展开法有 f x fk0 0 x 0 0 fk1 0 x 1 1 fk2 0 x 2 2 其中fk0 0 fk1 0 分别代表fk x 的k阶导数 并且传0代替k阶导数中的x
  • 保姆级教程:Linux和Windows下本地化部署Vicuna模型

    目录 文章摘要 一 Vicuna简介 1 Vicuna模型定义 2 Vicuna模型的应用场景 3 Vicuna模型的训练数据 4 Vicuna模型的版本 5 性能评估 二 linux 操作系统下部署 1 环境介绍 2 安装Python3
  • Windows 动态磁盘卷:简单卷、跨区卷 、带区卷 、镜像卷 、RAID5卷 相关配置操作

    Windows Server 2003 提供了新的磁盘管理方式 能够提高磁盘性能和容错能力 将基本磁盘升级为动态磁盘 能够更灵活分配和管理磁盘空间 能够配置各种磁盘阵列提高磁盘能力 动态磁盘与基本磁盘对比 一块基本磁盘只能包含4个分区 它们
  • C语言——malloc与free

    文章目录 1 malloc 1 1 size t 1 2 malloc可申请的字节数 1 2 1 整形常量溢出 1 3 malloc一维数组 1 4 calloc 2 free 1 malloc 在堆区申请一个指定大小 连续的空间并返回空间
  • 使用FTP(IOS FTP客户端开发教程)

    本文翻译自新近Wrox出版社出版的 由Peter van de Put所著的 Professional iOS Programming 该书题材比较新颖 结构合理 是一本不错的IOS开发书籍 本文译自该书第八章 Using FTP 本文开放
  • C语言中的移位运算

    左移运算 对于一个位表示为的操作数 x x lt lt k 会生成一个指 其位表达式为 也就是说将x右边的w k位向左移动k位 丢弃最高的k位 并在右端补k个0 例如 操作数 x 位表达式为 01010101 x lt lt 3 将得到 1
  • 完成人机猜拳(0:石头;1:剪刀;2:布)游戏

    完成人机猜拳 0 石头 1 剪刀 2 布 游戏 详细代码见链接 共同学习 加油 文末有知识点分析 文章所使用的知识点if lese语句 if 条件1 print 条件为1 elif 条件2 print 条件为2 elif 条件3 print
  • 014人脸识别打卡签到系统pyqt界面

    目标检测一般是yolov3 yolov4 yolov5 yolox PSPnet faster rcnn SDD等 教学视频 银色子弹zg的个人空间 银色子弹zg个人主页 哔哩哔哩视频 效果图如下 完整的代码文件 其中dataset文件下是
  • vue2-slot是什么?

    1 slot是什么 在html中slot元素 作为web Compoents技术套件的一部分 是Web组件内的一个占位符 该占位符可以在后期使用自己的标记语言填充 举例 template不会展示到页面中 需要先获取它的引用 然后添加到DOM
  • swagger快速升级方案

    背景 在使用SpringBoot 2 6以前去创建API文档工具一般会采用SpringFox提供的Swagger库 但是由于SpringBoot版本的不断升级和SpringFox摆烂不更新 导致了SpringBoot2 6之后的项目无法使用

随机推荐