forked from Wei-1/Scala-Machine-Learning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBayesianDecision.scala
65 lines (57 loc) · 1.62 KB
/
BayesianDecision.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
54
55
56
57
58
59
60
61
62
63
64
65
// Wei Chen - Bayesian Decision
// 2015-12-20
package com.scalaml.algorithm
import com.scalaml.general.MatrixFunc._
class BayesianDecision() extends Classification {
val algoname: String = "BayesianDecision"
val version: String = "0.1"
var groupcnt = Map[Int, Int]()
var groupavg = Map[Int, Array[Double]]()
var groupcov = Map[Int, Array[Array[Double]]]()
override def clear(): Boolean = {
groupcnt = Map[Int, Int]()
groupavg = Map[Int, Array[Double]]()
groupcov = Map[Int, Array[Array[Double]]]()
true
}
override def config(paras: Map[String, Any]): Boolean = {
true
}
private def arrstats(
i: Int,
data: Array[Array[Double]]
) {
val n = data.size
val m = matrixaccumulate(data).map(_/n)
val s = covariance(data)
groupcnt += (i -> n)
groupavg += (i -> m)
groupcov += (i -> s)
}
override def train(
data: Array[(Int, Array[Double])]
): Boolean = try {
data.groupBy(_._1).foreach { d =>
arrstats(d._1, d._2.map(_._2))
}
true
} catch { case e: Exception =>
Console.err.println(e)
false
}
override def predict(
data: Array[Array[Double]]
): Array[Int] = {
val n = groupavg.size
if (n == 0) {
Array[Int]()
} else {
data.map { d =>
groupcnt.map { cnt =>
val i = cnt._1
(i, cnt._2 * gaussianprobability(d, groupavg(i), groupcov(i)))
}.toArray.maxBy(_._2)._1
}
}
}
}