-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNeuralNetwork.java
More file actions
216 lines (189 loc) · 6.18 KB
/
Copy pathNeuralNetwork.java
File metadata and controls
216 lines (189 loc) · 6.18 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
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 NeuralNetwork {
protected final int[] shape;
protected final float[] neurons;
protected final float[] weights;
//Used for duplicate() method
public NeuralNetwork(int[] shape, float[] neurons, float[] weights) {
this.shape = shape;
this.neurons = new float[neurons.length];
int i = 0;
for (float val: neurons) this.neurons[i++] = val;
this.weights = new float[weights.length];
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 NeuralNetwork(int[] shape) {
this.shape = shape;
//initialise neuron matrix
int sum = 0;
for (int i: shape) sum += i;
neurons = new float[sum];
//initialise weight matrix
sum = 0;
for (int i = 0; i < shape.length-1; i++)
sum += shape[i]*shape[i+1];
weights = new float[sum];
//Random weight init -1 to 1
for (int i = 0; i < sum; i++)
weights[i] = (float)(Math.random()*2 - 1);
}
/**
* Do weight calculations on the neural network
*/
public void engage() {
//Reset values
for (int i = shape[0]; i < neurons.length; i++)
neurons[i] = 0;
int currentLayer = 0, nextLayerIndex = shape[0], w = 0;
for (int i = 0; i < neurons.length-shape[shape.length-1]; i++) {
if (currentLayer != 0)
neurons[i] = sigmoid(neurons[i]);
for (int 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 = 0;
for (float i: inputs) neurons[j++] = i;
}
/**
* Get specific weight at layer/index
*/
public float getWeight(int layer, int index) {
int pos = 0;
for (int i = 0; i<layer; i++) pos += shape[i];
pos += index;
return neurons[pos];
}
public float[] getLayer(int layer) {
int start = 0;
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.close();
} catch (IOException ex) {
Logger.getLogger(NeuralNetwork.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[] input = fs.nextLine().split(",");
while (i<weights.length) {
weights[i] = (float)Double.parseDouble(input[i++]);
}
fs.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(NeuralNetwork.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;
}
}
}
/**
* 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 NeuralNetwork duplicate() {
return new NeuralNetwork(shape, neurons, weights);
}
@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;
}
}