-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecurrentNeuralNetwork.java
More file actions
262 lines (227 loc) · 8 KB
/
Copy pathRecurrentNeuralNetwork.java
File metadata and controls
262 lines (227 loc) · 8 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Kevin
*/
public class RecurrentNeuralNetwork {
protected final int[] shape;
protected final float[] neurons;
protected final float[] weights;
protected final float[] bias;
//Used for duplicate() method
public RecurrentNeuralNetwork(int[] shape, float[] neurons, float[] weights, float[] bias) {
this.shape = shape;
this.neurons = new float[neurons.length];
this.bias = new float[bias.length];
this.weights = new float[weights.length];
int i = 0;
for (float val: neurons) this.neurons[i++] = val;
i = 0;
for (float val: bias) this.bias[i++] = val;
i = 0;
for (float val: weights) this.weights[i++] = val;
}
/**
* Create a new neural network from a given shape.
* @param shape Shape of neural network per layer
*/
public RecurrentNeuralNetwork(int[] shape) {
this.shape = shape;
//Initialise neuron matrix and neuron bias matrix
int sum = shape[shape.length-1];
for (int i: shape) sum += i;
neurons = new float[sum];
bias = new float[sum-shape[0]-shape[shape.length-1]];
//Initialise weight matrix
sum = shape[shape.length-1]*shape[1];
for (int i = 0; i < shape.length-1; i++)
sum += shape[i]*shape[i+1];
weights = new float[sum];
//Random weight initilisation -1 to 1
for (int i = 0; i < weights.length; i++)
weights[i] = (float)(Math.random()*2 - 1);
for (int i = 0; i < bias.length; i++)
bias[i] = (float)(Math.random()*2 - 1);
}
/**
* Reset recurrent input
*/
public void reset() {
//Reset of recurrent neurons
for (int i = 0; i < shape[shape.length-1]; i++)
neurons[i] = 0;
}
/**
* Do weight calculations on the neural network
*/
public void engage() {
int pos = shape[shape.length-1];
for (int i = 0; i < shape.length-1; i++) pos+= shape[i];
for (int i = 0; i < shape[shape.length-1]; i++) {
neurons[i] = neurons[pos++];
}
//Reset values to a bias
int j = 0;
for (int i = shape[0] + shape[shape.length-1]; i < neurons.length; i++)
neurons[i] = bias[j++];
int currentLayer = 0, nextLayerIndex = shape[0] + shape[shape.length-1], w = 0;
for (int i = 0; i < neurons.length-shape[shape.length-1]; i++) {
if (currentLayer != 0)
neurons[i] = sigmoid(neurons[i]);
for (j = 0; j < shape[currentLayer+1]; j++)
neurons[nextLayerIndex+j] += neurons[i] * weights[w++];
if (i == nextLayerIndex - 1) {
currentLayer++;
nextLayerIndex += shape[currentLayer];
}
}
}
/**
* Set input state for processing
* @param inputs Array of inputs of range (-1, 1)
*/
public void input(float[] inputs) {
if (inputs.length != shape[0]) return;
int j = shape[shape.length-1];
for (float i: inputs) neurons[j++] = i;
}
/**
* Get specific weight at layer/index
*/
public float getWeight(int layer, int index) {
int pos = shape[shape.length-1];
for (int i = 0; i<layer; i++) pos += shape[i];
pos += index;
return neurons[pos];
}
public float[] getLayer(int layer) {
int start = shape[shape.length-1];
float[] out = new float[shape[layer]];
for (int i = 0; i<layer; i++) start += shape[i];
for (int i = 0; i < out.length; i++) out[i] = neurons[start++];
return out;
}
/**
* Get the output layer of the neural network
* @return Array of output values
*/
public float[] getOutputLayer() {
return getLayer(shape.length-1);
}
/**
* Get the index of highest value output
* @return index of best output
*/
public int getOutputIndex() {
float[] output = getLayer(shape.length-1);
int i = -1;
for (int j = 0; j < output.length; j++)
if (i == -1 || output[j] > output[i]) i = j;
return i;
}
/**
* Get output using softmax probability
* @return randomised output
*/
public int getOutput() {
double sum = 0, r = Math.random();
float[] output = getLayer(shape.length-1);
for (int i = 0; i < output.length; i++) output[i] = Math.abs(output[i]);
for (float i: output) sum += (double)i;
for (int i = 0; i < output.length; i++)
output[i] /= sum;
int i = 0;
sum = output[i];
while (sum < r) sum += output[++i];
i--;
return i;
}
/**
* Save weight matrix and bias to file
* @param filename Path of file to be saved
*/
public void save(String filename) {
try {
FileWriter fw = new FileWriter(new File(filename));
for (float w: weights) fw.write(w + ",");
fw.write("#");
for (float b: bias) fw.write(b + ",");
fw.close();
} catch (IOException ex) {
Logger.getLogger(RecurrentNeuralNetwork.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Load weight matrix and bias to network
* @param filename Path of file to be loaded
*/
public void load(String filename) {
try {
Scanner fs = new Scanner(new File(filename));
int i = 0;
String line = fs.nextLine();
String[] input = line.split("#")[0].split(",");
while (i<weights.length)
weights[i] = (float)Double.parseDouble(input[i++]);
i = 0;
input = line.split("#")[1].split(",");
while (i<bias.length)
bias[i] = (float)Double.parseDouble(input[i++]);
fs.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(RecurrentNeuralNetwork.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Mutate weight matrix and bias
*/
public void mutate(float rate) {
for (int i = 0; i < weights.length; i++) {
double r = Math.random();
if (r < rate/10) {
weights[i] = (float)(Math.random()*2 - 1);
} else if (r < rate*1.1) {
weights[i] *= (1 + (float)(Math.random()*2-1)*0.05);
if (weights[i] < -1) weights[i] = -1;
if (weights[i] > 1) weights[i] = 1;
}
}
for (int i = 0; i < bias.length; i++) {
double r = Math.random();
if (r < rate/10) {
bias[i] = (float)(Math.random()*2 - 1);
} else if (r < rate*1.1) {
bias[i] *= (1 + (float)(Math.random()*2-1)*0.05);
if (bias[i] < -1) weights[i] = -1;
if (bias[i] > 1) weights[i] = 1;
}
}
//for (float i: bias) if (i != 0) System.out.println(i);
}
/**
* Activation function
*/
public static float sigmoid(double x) {
return (float)(1/( 1 + Math.pow(Math.E,(-1*x))));
}
/**
* Create duplicated instance of neural network
* @return Duplicate RecurrentNeuralNetwork
*/
public RecurrentNeuralNetwork duplicate() {
return new RecurrentNeuralNetwork(shape, neurons, weights, bias);
}
@Override
public String toString() {
String out = "[" + shape[0];
for (int i = 1; i < shape.length; i++)
out += ", " + shape[i];
return out + "]: Neurons = " + neurons.length + ", Weights = " + weights.length;
}
}