-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathneuron.go
More file actions
91 lines (82 loc) · 1.68 KB
/
Copy pathneuron.go
File metadata and controls
91 lines (82 loc) · 1.68 KB
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
package nn
import (
"fmt"
"math"
"math/rand"
"time"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
type neuron struct {
input []chan float64
output []chan float64
weight []float64
bias float64
id int
isInput bool
}
type inpMes struct {
val float64
id int
}
func (n *neuron) mergeInputChannels() chan inpMes {
ch := make(chan inpMes)
for k, c := range n.input {
go func(k int, c <-chan float64, ch chan<- inpMes) {
for {
ch <- inpMes{val: <-c, id: k}
}
}(k, c, ch)
}
return ch
}
func sigmoid(sum float64) float64 {
return 1.0 / (1.0 + math.Exp(-sum))
}
func (n *neuron) activate() {
//fmt.Println("neuron", n.id, "activated")
lenOut := len(n.output)
lenIn := len(n.input)
c := n.mergeInputChannels()
for {
totalInpVal := float64(0)
for i := 0; i < lenIn; i++ {
res := <-c
totalInpVal += res.val * n.weight[res.id]
//fmt.Println("neur", n.id, "received", res, "weight", n.weight[res.id])
}
for i := 0; i < lenOut; i++ {
//fmt.Println("sending from ", n.id, "val", sigmoid(totalInpVal))
n.output[i] <- sigmoid(totalInpVal) //+ n.bias
}
}
}
func (n *neuron) String() string {
str := ""
for k, v := range n.weight {
str += fmt.Sprintln("\t\tweight aplied to neur", k, "is", v)
}
for k, v := range n.input {
str += fmt.Sprintln("\t\tchannel", k, "is", v)
}
return str
}
var numNeur = 0
func newNeuron(input []chan float64, output []chan float64, isInput bool, weights []float64) *neuron {
n := &neuron{
input: input,
output: output,
weight: weights,
id: numNeur,
isInput: isInput,
bias: -0.5,
}
numNeur++
if n.isInput == true {
for k := range n.weight {
n.weight[k] = 1.0
}
}
return n
}