-
Notifications
You must be signed in to change notification settings - Fork 0
/
NeuralNetwork.pde
107 lines (82 loc) · 2.53 KB
/
NeuralNetwork.pde
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
96
97
98
99
100
101
102
103
104
105
106
107
public class NeuralNetwork{
int in_nodes;
int h_nodes;
int o_nodes;
Matrix weights_ih;
Matrix weights_ho;
Matrix bias_h;
Matrix bias_o;
public NeuralNetwork(int in_nodes, int h_nodes, int o_nodes){
this.in_nodes = in_nodes;
this.h_nodes = h_nodes;
this.o_nodes = o_nodes;
this.weights_ih = new Matrix(this.h_nodes, this.in_nodes);
this.weights_ho = new Matrix(this.o_nodes, this.h_nodes);
this.bias_h = new Matrix(this.h_nodes, 1);
this.bias_o = new Matrix(this.o_nodes, 1);
weights_ih.randomize();
weights_ho.randomize();
bias_h.randomize();
bias_o.randomize();
}
public NeuralNetwork(Matrix ih_w, Matrix ho_w, Matrix h_b, Matrix o_b){
this.in_nodes = ih_w.cols;
this.h_nodes = ih_w.rows;
this.o_nodes = ho_w.rows;
this.weights_ih = ih_w;
this.weights_ho = ho_w;
this.bias_h = h_b;
this.bias_o = o_b;
}
public double[] feedforward(double[] input){
MapFunction squash = new MapFunction("sigmoid");
MapFunction binary = new MapFunction("binary");
Matrix inputs = Matrix.fromArray(input);
Matrix hidden = Matrix.multiply(weights_ih, inputs);
hidden.add(this.bias_h);
hidden.map(squash);
Matrix output = Matrix.multiply(weights_ho, hidden);
output.add(this.bias_o);
output.map(squash);
output.map(binary);
return output.toArray();
}
public NeuralNetwork copy(){
NeuralNetwork newCopy = new NeuralNetwork(this.in_nodes, this.h_nodes, this.o_nodes);
newCopy.weights_ih = this.weights_ih.copy();
newCopy.weights_ho = this.weights_ho.copy();
newCopy.bias_h = this.bias_h.copy();
newCopy.bias_o = this.bias_o.copy();
return newCopy;
}
public void mutate(double mutationRate){
for(int i=0; i<h_nodes; i++){
for(int j=0; j<in_nodes; j++){
if(random(1)<mutationRate){
weights_ih.data[i][j] = Math.random()*2-1;
}
}
}
for(int i=0; i<o_nodes; i++){
for(int j=0; j<h_nodes; j++){
if(random(1)<mutationRate){
weights_ho.data[i][j] = Math.random()*2-1;
}
}
}
for(int i=0; i<h_nodes; i++){
for(int j=0; j<1; j++){
if(random(1)<mutationRate){
bias_h.data[i][j] = Math.random()*2-1;
}
}
}
for(int i=0; i<o_nodes; i++){
for(int j=0; j<1; j++){
if(random(1)<mutationRate){
bias_o.data[i][j] = Math.random()*2-1;
}
}
}
}
}