-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathIsolationTree.scala
53 lines (45 loc) · 1.61 KB
/
IsolationTree.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Wei Chen - Isolation Tree
// 2022-03-04
package com.scalaml.algorithm
class IsolationTree() extends Abnormal {
val algoname: String = "IsolationTree"
val version: String = "0.1"
var maxLayer = 5
var tree: DecisionNode = null
override def clear(): Boolean = {
maxLayer = 5
true
}
override def config(paras: Map[String, Any]): Boolean = try {
maxLayer = paras.getOrElse("maxLayer", 5.0).asInstanceOf[Double].toInt
true
} catch { case e: Exception =>
Console.err.println(e)
false
}
private def buildtree(data: Array[Array[Double]], layer: Int = 0): DecisionNode = {
val dataSize = data.size
val columnSize: Int = data.head.size
val col = scala.util.Random.nextInt(columnSize)
val colData = data.map(d => d(col))
val minV = colData.min
val maxV = colData.max
val value = (maxV - minV) * scala.util.Random.nextDouble() + minV
val (tData, fData) = data.partition { d =>
d(col) >= value
}
if (tData.size > 0 && fData.size > 0 && layer < maxLayer) {
val tnode = buildtree(tData, layer + 1)
val fnode = buildtree(fData, layer + 1)
new DecisionNode(col, value, tnode, fnode)
} else new DecisionNode(0, 0, null, null, layer)
}
override def train(data: Array[Array[Double]]): Boolean = try {
tree = buildtree(data)
true
} catch { case e: Exception =>
Console.err.println(e)
false
}
override def predict(x: Array[Array[Double]]): Array[Double] = x.map(xi => tree.predict(xi))
}