-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPerceptron.kt
76 lines (70 loc) · 2.19 KB
/
Perceptron.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
class Perceptron(input: MutableList<MutableList<Number>>, var teta:Double){
var x = input
var y = x.removeAt(input.size-1)
var w = MutableList(x.size){0.0}
var b = 0.0
fun compute (input:MutableList<Double>):Int?{
var yin = 0.0
var i = 0
while (i < w.size){
yin += w[i] * input[i]
i++
}
yin += b
return when {
teta < yin -> 1
-teta < yin && yin < teta -> 0
yin < -teta -> -1
else -> null
}
}
fun learn (a:Number,debug:Boolean){
var m = 0
var changed = false
while (true){
if (m == w.size - 1){
m = 0
if (!changed){
break
}
}
changed = false
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){
w[j] += a.toDouble() * x[j][i].toDouble() * y[i].toDouble()
changed = true
}
b += y[i].toDouble()
}
if (debug) print()
}
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")
}
}