-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAdaline.kt
95 lines (85 loc) · 2.8 KB
/
Adaline.kt
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
class Adaline(input: MutableList<MutableList<Number>>){
var x = input
var y = x.removeAt(input.size-1)
var w = MutableList(x.size){0.0}
var b = 0.0
private fun yin (input:MutableList<Double>):Double{
var yin = 0.0
var i = 0
while (i < w.size){
yin += w[i] * input[i]
i++
}
yin += b
return yin
}
fun compute (input:MutableList<Double>):Int{
return when {
yin(input) >= 0 -> 1
else -> -1
}
}
fun learn (a:Number,delta:Number,successPercent:Number?,debug:Boolean){
var m = 0
var e = 0.0
var es = mutableListOf<Double>()
while (true){
if (m == w.size - 1){
m = 0
es = es.toDoubleArray().toSortedSet().reversed().toMutableList()
if (es.first() <= delta.toDouble()){
if (successPercent == null) {
break
}
}
if (successPercent != null) {
if (test(debug) >= successPercent.toDouble()){
break
}
}
es = mutableListOf()
}
for (i in 0 until y.size){
val line = mutableListOf<Double>()
for (n in 0 until x.size){
line.add(x[n][i].toDouble())
}
if (compute(line).toDouble() != y[i].toDouble()){
for (j in 0 until x.size){
e = w[j]
w[j] += a.toDouble() * x[j][i].toDouble() * (y[i].toDouble() - yin(line))
e -= w[j]
es.add(e)
}
b += a.toDouble() * (y[i].toDouble() - yin(line))
}
if (debug) print(e)
}
m++
}
}
fun test (debug:Boolean):Double{
var wins = 0
var losses = 0
for (i in 0 until y.size){
val line = mutableListOf<Double>()
for (n in 0 until x.size){
line.add(x[n][i].toDouble())
}
if (debug) println(line + " : " + compute(line).toString() + " ?= " + y[i].toString())
if (compute(line).toDouble() == y[i].toDouble())
wins ++
else
losses ++
}
val percent = (wins.toDouble() * 100.0)/(wins.toDouble() + losses.toDouble())
if (debug) println("$wins:$losses = ${percent.toInt()}%")
return percent
}
fun print (){
println(w + "$b")
}
fun print (e:Double){
println(w + "$b" + "error : $e")
}
}