-
Notifications
You must be signed in to change notification settings - Fork 9
/
LinearClassification.scala
56 lines (48 loc) · 1.74 KB
/
LinearClassification.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
// Wei Chen - Linear Classification
// 2015-12-21
package com.scalaml.algorithm
import com.scalaml.general.MatrixFunc._
class LinearClassification() extends Classification {
val algoname: String = "LinearRegression"
val version: String = "0.1"
private def dot(x:Array[Double], y:Array[Double]): Double =
arraymultiply(x, y).sum
var projector = Array[(Int, Int, Array[Double], Array[Double])]()
override def clear(): Boolean = {
projector = Array[(Int, Int, Array[Double], Array[Double])]()
true
}
override def config(paras: Map[String, Any]): Boolean = {
true
}
// --- Start Linear Classification Function ---
override def train(
data: Array[(Int, Array[Double])] // Data Array(yi, xi)
): Boolean = { // Return PData Class
val centers = data.groupBy(_._1).map { l =>
val datasize = l._2.size
(l._1, matrixaccumulate(l._2.map(_._2)).map(_ / datasize))
}
centers.map { center1 =>
centers.map { center2 =>
if (center1._1 < center2._1) {
val m = arraysum(center1._2, center2._2).map(_ / 2)
var w = arrayminus(center2._2, center1._2)
if (w.sum > 1) w = w.map(_ / w.sum)
projector :+= (center1._1, center2._1, m, w)
}
}
}
true
}
// --- Dual Projection Linear Classification ---
override def predict(
data: Array[Array[Double]]
): Array[Int] = {
return data.map { d =>
projector.map(p =>
if (dot(arrayminus(d, p._3), p._4) < 0) p._1 else p._2
).groupBy(identity).mapValues(_.size).maxBy(_._2)._1
}
}
}