This repository has been archived by the owner on Sep 8, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathneuron.go
85 lines (75 loc) · 1.68 KB
/
neuron.go
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
package bareml
import "math"
type ActivationType uint8
const (
TANH ActivationType = 1
RELU ActivationType = 2
SIGM ActivationType = 3
)
type Neuron struct {
rawVal float64
activatedVal float64
derivedVal float64
activationType ActivationType
}
func NewNeuron(val float64, aType ActivationType) *Neuron {
n := new(Neuron)
n.activationType = aType
n.Set(val)
return n
}
func (n *Neuron) Set(val float64) {
n.rawVal = val
n.Activate()
n.Derive()
}
func (n *Neuron) Copy() *Neuron {
return &Neuron{
rawVal: n.RawVal(),
activatedVal: n.ActivatedVal(),
derivedVal: n.DerivedVal(),
activationType: n.ActivationType(),
}
}
func (n *Neuron) Activate() {
if n.activationType == TANH {
n.activatedVal = math.Tanh(n.rawVal)
} else if n.activationType == RELU {
if n.rawVal > 0 {
n.activatedVal = n.rawVal
} else {
n.activatedVal = 0
}
} else if n.activationType == SIGM {
n.activatedVal = n.rawVal / (1 + math.Abs(n.rawVal))
} else {
n.activatedVal = n.rawVal / (1 + math.Abs(n.rawVal))
}
}
func (n *Neuron) Derive() {
if n.activationType == TANH {
n.derivedVal = (1.0 - (n.activatedVal * n.activatedVal))
} else if n.activationType == RELU {
if n.rawVal > 0 {
n.derivedVal = 1
} else {
n.derivedVal = 0
}
} else if n.activationType == SIGM {
n.derivedVal = n.activatedVal * (1 - n.activatedVal)
} else {
n.derivedVal = n.activatedVal * (1 - n.activatedVal)
}
}
func (n *Neuron) RawVal() float64 {
return n.rawVal
}
func (n *Neuron) ActivatedVal() float64 {
return n.activatedVal
}
func (n *Neuron) DerivedVal() float64 {
return n.derivedVal
}
func (n *Neuron) ActivationType() ActivationType {
return n.activationType
}