-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathNeuralNetwork.java
387 lines (302 loc) · 10.5 KB
/
NeuralNetwork.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
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
import java.util.ArrayList;
import java.util.List;
public class NeuralNetwork {
Matrix weights_ih, weights_ho, bias_h, bias_o;
double l_rate = 0.01;
boolean useMultiThreading = false;
public NeuralNetwork(int i, int h, int o) {
weights_ih = new Matrix(h, i);
weights_ho = new Matrix(o, h);
bias_h = new Matrix(h, 1);
bias_o = new Matrix(o, 1);
}
public NeuralNetwork(int i, int h, int o, boolean useMultiThreading) {
weights_ih = new Matrix(h, i);
weights_ho = new Matrix(o, h);
bias_h = new Matrix(h, 1);
bias_o = new Matrix(o, 1);
this.useMultiThreading = useMultiThreading;
}
public NeuralNetwork(int i, int h, int o, double l_rate) {
weights_ih = new Matrix(h, i);
weights_ho = new Matrix(o, h);
bias_h = new Matrix(h, 1);
bias_o = new Matrix(o, 1);
this.l_rate = l_rate;
}
public NeuralNetwork(int i, int h, int o, double l_rate, boolean useMultiThreading) {
weights_ih = new Matrix(h, i);
weights_ho = new Matrix(o, h);
bias_h = new Matrix(h, 1);
bias_o = new Matrix(o, 1);
this.l_rate = l_rate;
this.useMultiThreading = useMultiThreading;
}
public List<Double> predict(double[] X) {
Matrix input = Matrix.fromArray(X);
Matrix hidden = Matrix.multiply(weights_ih, input, useMultiThreading);
hidden.add(bias_h);
hidden.sigmoid();
Matrix output = Matrix.multiply(weights_ho, hidden, useMultiThreading);
output.add(bias_o);
output.sigmoid();
return output.toArray();
}
public void fit(double[][] X, double[][] Y, int epochs) {
for (int i = 0; i < epochs; i++) {
int sampleN = (int) (Math.random() * X.length);
this.train(X[sampleN], Y[sampleN], false);
}
}
public void fit(double[][] X, double[][] Y, int epochs, int verbose) {
switch (verbose) {
case 0: {
System.out.println("Staring training with " + epochs + " epochs");
long start = System.currentTimeMillis();
for (int i = 0; i < epochs; i++) {
int sampleN = (int) (Math.random() * X.length);
this.train(X[sampleN], Y[sampleN], i + 1 == epochs);
}
long end = System.currentTimeMillis();
long elapsedTime = end - start;
System.out.println("Training took : " + (elapsedTime / 1000) + "s");
break;
}
case 1: {
System.out.println("Staring training with " + epochs + " epochs");
long start = System.currentTimeMillis();
for (int i = 0; i < epochs; i++) {
System.out.println("Epoch: " + (i + 1));
int sampleN = (int) (Math.random() * X.length);
this.train(X[sampleN], Y[sampleN], true);
}
long end = System.currentTimeMillis();
long elapsedTime = end - start;
System.out.println("Training took : " + (elapsedTime / 1000) + "s");
break;
}
}
}
public void train(double[] X, double[] Y, Boolean showLoss) {
Matrix input = Matrix.fromArray(X);
Matrix hidden = Matrix.multiply(weights_ih, input, useMultiThreading);
hidden.add(bias_h);
hidden.sigmoid();
Matrix output = Matrix.multiply(weights_ho, hidden, useMultiThreading);
output.add(bias_o);
output.sigmoid();
Matrix target = Matrix.fromArray(Y);
Matrix error = Matrix.subtract(target, output);
Matrix gradient = output.dsigmoid();
gradient.multiply(error);
gradient.multiply(l_rate);
if (showLoss)
printLoss(error);
Matrix hidden_T = Matrix.transpose(hidden);
Matrix who_delta = Matrix.multiply(gradient, hidden_T, useMultiThreading);
weights_ho.add(who_delta);
bias_o.add(gradient);
Matrix who_T = Matrix.transpose(weights_ho);
Matrix hidden_errors = Matrix.multiply(who_T, error, useMultiThreading);
Matrix h_gradient = hidden.dsigmoid();
h_gradient.multiply(hidden_errors);
h_gradient.multiply(l_rate);
Matrix i_T = Matrix.transpose(input);
Matrix wih_delta = Matrix.multiply(h_gradient, i_T, useMultiThreading);
weights_ih.add(wih_delta);
bias_h.add(h_gradient);
}
private void printLoss(Matrix error) {
double avg = 0.0;
for (int i = 0; i < error.rows; i++) {
for (int j = 0; j < error.cols; j++) {
avg += error.data[i][j];
}
}
System.out.print("Average Error: " + avg + "\n");
}
}
class Matrix {
double[][] data;
int rows, cols;
public Matrix(int rows, int cols) {
data = new double[rows][cols];
this.rows = rows;
this.cols = cols;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
data[i][j] = Math.random() * 2 - 1;
}
}
}
public void print() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(this.data[i][j] + " ");
}
System.out.println();
}
}
public void add(int scaler) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
this.data[i][j] += scaler;
}
}
}
public void add(Matrix m) {
if (cols != m.cols || rows != m.rows) {
System.out.println("Shape Mismatch");
return;
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
this.data[i][j] += m.data[i][j];
}
}
}
public static Matrix fromArray(double[] x) {
Matrix temp = new Matrix(x.length, 1);
for (int i = 0; i < x.length; i++)
temp.data[i][0] = x[i];
return temp;
}
public List<Double> toArray() {
List<Double> temp = new ArrayList<Double>();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
temp.add(data[i][j]);
}
}
return temp;
}
public static Matrix subtract(Matrix a, Matrix b) {
Matrix temp = new Matrix(a.rows, a.cols);
for (int i = 0; i < a.rows; i++) {
for (int j = 0; j < a.cols; j++) {
temp.data[i][j] = a.data[i][j] - b.data[i][j];
}
}
return temp;
}
public static Matrix transpose(Matrix a) {
Matrix temp = new Matrix(a.cols, a.rows);
for (int i = 0; i < a.rows; i++) {
for (int j = 0; j < a.cols; j++) {
temp.data[j][i] = a.data[i][j];
}
}
return temp;
}
// TODO Add Multi-threading
public static Matrix multiply(Matrix a, Matrix b, boolean useMultiThreading) {
Matrix temp = new Matrix(a.rows, b.cols);
if (!useMultiThreading) {
for (int i = 0; i < temp.rows; i++) {
for (int j = 0; j < temp.cols; j++) {
double sum = 0;
for (int k = 0; k < a.cols; k++) {
sum += a.data[i][k] * b.data[k][j];
}
temp.data[i][j] = sum;
}
}
} else {
// return ParallelMatrixMultiplication.multiply(a, b);
ParallelThreadsCreator.multiply(a, b, temp);
}
return temp;
}
public void multiply(Matrix a) {
for (int i = 0; i < a.rows; i++) {
for (int j = 0; j < a.cols; j++) {
this.data[i][j] *= a.data[i][j];
}
}
}
public void multiply(double a) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
this.data[i][j] *= a;
}
}
}
public void sigmoid() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++)
this.data[i][j] = 1 / (1 + Math.exp(-this.data[i][j]));
}
}
public Matrix dsigmoid() {
Matrix temp = new Matrix(rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++)
temp.data[i][j] = this.data[i][j] * (1 - this.data[i][j]);
}
return temp;
}
}
class ParallelThreadsCreator {
// creating 10 threads and waiting for them to complete then again repeat steps.
public static void multiply(Matrix matrix1, Matrix matrix2, Matrix result) {
List<Thread> threads = new ArrayList<>();
int rows1 = matrix1.rows;
for (int i = 0; i < rows1; i++) {
RowMultiplyWorker task = new RowMultiplyWorker(result, matrix1, matrix2, i);
Thread thread = new Thread(task);
thread.start();
threads.add(thread);
if (threads.size() % 10 == 0) {
waitForThreads(threads);
}
}
}
private static void waitForThreads(List<Thread> threads) {
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
threads.clear();
}
}
class WorkerThread extends Thread {
private int row;
private int col;
private int[][] A;
private int[][] B;
private int[][] C;
public WorkerThread(int row, int col, int[][] A, int[][] B, int[][] C) {
this.row = row;
this.col = col;
this.A = A;
this.B = B;
this.C = C;
}
public void run() {
C[row][col] = (A[row][0] * B[0][col]) + (A[row][1] * B[1][col]);
}
}
class RowMultiplyWorker implements Runnable {
private final Matrix result;
private Matrix matrix1;
private Matrix matrix2;
private final int row;
public RowMultiplyWorker(Matrix result, Matrix matrix1, Matrix matrix2, int row) {
this.result = result;
this.matrix1 = matrix1;
this.matrix2 = matrix2;
this.row = row;
}
@Override
public void run() {
for (int i = 0; i < matrix2.data[0].length; i++) {
result.data[row][i] = 0;
for (int j = 0; j < matrix1.data[row].length; j++) {
result.data[row][i] += matrix1.data[row][j] * matrix2.data[j][i];
}
}
}
}