Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 11 additions & 18 deletions lib/model/isolation_forest.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import Tree from '../util/tree.js'

const shuffle = function (arr) {
for (let i = arr.length - 1; i > 0; i--) {
let r = Math.floor(Math.random() * (i + 1))
Expand All @@ -12,7 +10,7 @@ class IsolationTree {
// https://www.slideshare.net/kataware/isolation-forest
// https://cs.nju.edu.cn/zhouzh/zhouzh.files/publication/icdm08b.pdf
constructor() {
this._tree = new Tree({})
this._tree = {}
}

get c() {
Expand Down Expand Up @@ -53,37 +51,32 @@ class IsolationTree {
const nodes = [[this._tree, datas]]
while (nodes.length > 0) {
const [node, data] = nodes.pop()
if (node.isLeaf()) {
const sep = this._separate(data)
if (!sep) {
continue
}
const [f, th] = sep
node.value.feature = f
node.value.threshold = th
node.push({})
node.push({})
const sep = this._separate(data)
if (!sep) {
continue
}
;[node.feature, node.threshold] = sep

const leftData = []
const rightData = []
for (let i = 0; i < data.length; i++) {
if (data[i][node.value.feature] <= node.value.threshold) {
if (data[i][node.feature] <= node.threshold) {
leftData.push(data[i])
} else {
rightData.push(data[i])
}
}
nodes.push([node.at(0), leftData])
nodes.push([node.at(1), rightData])
nodes.push([(node.left = {}), leftData])
nodes.push([(node.right = {}), rightData])
}
}

depth(data) {
return data.map(d => {
let t = this._tree
let depth = 0
while (!t.isLeaf()) {
t = d[t.value.feature] <= t.value.threshold ? t.at(0) : t.at(1)
while (t.left) {
t = d[t.feature] <= t.threshold ? t.left : t.right
depth++
}
return depth
Expand Down