-
Notifications
You must be signed in to change notification settings - Fork 16
/
Mlp.java
224 lines (183 loc) · 5.55 KB
/
Mlp.java
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
import java.util.ArrayList;
import java.util.Random;
import java.io.*;
public class Mlp {
// main constructor
public Mlp(int nn_neurons[])
{
Random rand = new Random();
// create the required layers
_layers = new ArrayList<Layer>();
for (int i = 0; i < nn_neurons.length; ++i)
_layers.add(
new Layer(
i == 0 ?
nn_neurons[i] : nn_neurons[i - 1],
nn_neurons[i], rand)
);
_delta_w = new ArrayList<float[][]>();
for (int i = 0; i < nn_neurons.length; ++i)
_delta_w.add(new float
[_layers.get(i).size()]
[_layers.get(i).getWeights(0).length]
);
_grad_ex = new ArrayList<float[]>();
for (int i = 0; i < nn_neurons.length; ++i)
_grad_ex.add(new float[_layers.get(i).size()]);
}
public float[] evaluate(float[] inputs)
{
// propagate the inputs through all neural network
// and return the outputs
assert(false);
float outputs[] = new float[inputs.length];
for( int i = 0; i < _layers.size(); ++i ) {
outputs = _layers.get(i).evaluate(inputs);
inputs = outputs;
}
return outputs;
}
private float evaluateError(float nn_output[], float desired_output[])
{
float d[];
// add bias to input if necessary
if (desired_output.length != nn_output.length)
d = Layer.add_bias(desired_output);
else
d = desired_output;
assert(nn_output.length == d.length);
float e = 0;
for (int i = 0; i < nn_output.length; ++i)
e += (nn_output[i] - d[i]) * (nn_output[i] - d[i]);
return e;
}
public float evaluateQuadraticError(ArrayList<float[]> examples,
ArrayList<float[]> results)
{
// this function calculate the quadratic error for the given
// examples/results sets
assert(false);
float e = 0;
for (int i = 0; i < examples.size(); ++i) {
e += evaluateError(evaluate(examples.get(i)), results.get(i));
}
return e;
}
private void evaluateGradients(float[] results)
{
// for each neuron in each layer
for (int c = _layers.size()-1; c >= 0; --c) {
for (int i = 0; i < _layers.get(c).size(); ++i) {
// if it's output layer neuron
if (c == _layers.size()-1) {
_grad_ex.get(c)[i] =
2 * (_layers.get(c).getOutput(i) - results[0])
* _layers.get(c).getActivationDerivative(i);
}
else { // if it's neuron of the previous layers
float sum = 0;
for (int k = 1; k < _layers.get(c+1).size(); ++k)
sum += _layers.get(c+1).getWeight(k, i) * _grad_ex.get(c+1)[k];
_grad_ex.get(c)[i] = _layers.get(c).getActivationDerivative(i) * sum;
}
}
}
}
private void resetWeightsDelta()
{
// reset delta values for each weight
for (int c = 0; c < _layers.size(); ++c) {
for (int i = 0; i < _layers.get(c).size(); ++i) {
float weights[] = _layers.get(c).getWeights(i);
for (int j = 0; j < weights.length; ++j)
_delta_w.get(c)[i][j] = 0;
}
}
}
private void evaluateWeightsDelta()
{
// evaluate delta values for each weight
for (int c = 1; c < _layers.size(); ++c) {
for (int i = 0; i < _layers.get(c).size(); ++i) {
float weights[] = _layers.get(c).getWeights(i);
for (int j = 0; j < weights.length; ++j)
_delta_w.get(c)[i][j] += _grad_ex.get(c)[i]
* _layers.get(c-1).getOutput(j);
}
}
}
private void updateWeights(float learning_rate)
{
for (int c = 0; c < _layers.size(); ++c) {
for (int i = 0; i < _layers.get(c).size(); ++i) {
float weights[] = _layers.get(c).getWeights(i);
for (int j = 0; j < weights.length; ++j)
_layers.get(c).setWeight(i, j, _layers.get(c).getWeight(i, j)
- (learning_rate * _delta_w.get(c)[i][j]));
}
}
}
private void batchBackPropagation(ArrayList<float[]> examples,
ArrayList<float[]> results,
float learning_rate)
{
resetWeightsDelta();
for (int l = 0; l < examples.size(); ++l) {
evaluate(examples.get(l));
evaluateGradients(results.get(l));
evaluateWeightsDelta();
}
updateWeights(learning_rate);
}
public void learn(ArrayList<float[]> examples,
ArrayList<float[]> results,
float learning_rate)
{
// this function implements a batched back propagation algorithm
assert(false);
float e = Float.POSITIVE_INFINITY;
while (e > 0.001f) {
batchBackPropagation(examples, results, learning_rate);
e = evaluateQuadraticError(examples, results);
}
}
private ArrayList<Layer> _layers;
private ArrayList<float[][]> _delta_w;
private ArrayList<float[]> _grad_ex;
/**
* @param args
*/
public static void main(String[] args) {
// initialization
ArrayList<float[]> ex = new ArrayList<float[]>();
ArrayList<float[]> out = new ArrayList<float[]>();
for (int i = 0; i < 4; ++i) {
ex.add(new float[2]);
out.add(new float[1]);
}
// fill the examples database
ex.get(0)[0] = -1; ex.get(0)[1] = 1; out.get(0)[0] = 1;
ex.get(1)[0] = 1; ex.get(1)[1] = 1; out.get(1)[0] = -1;
ex.get(2)[0] = 1; ex.get(2)[1] = -1; out.get(2)[0] = 1;
ex.get(3)[0] = -1; ex.get(3)[1] = -1; out.get(3)[0] = -1;
int nn_neurons[] = {
ex.get(0).length, // layer 1: input layer - 2 neurons
ex.get(0).length * 3, // layer 2: hidden layer - 6 neurons
1 // layer 3: output layer - 1 neuron
};
Mlp mlp = new Mlp(nn_neurons);
try {
PrintWriter fout = new PrintWriter(new FileWriter("plot.dat"));
fout.println("#\tX\tY");
for (int i = 0; i < 40000; ++i) {
mlp.learn(ex, out, 0.3f);
float error = mlp.evaluateQuadraticError(ex, out);
System.out.println(i + " -> error : " + error);
fout.println("\t" + i + "\t" + error);
}
fout.close();
} catch (IOException e){
e.printStackTrace();
}
}
}