-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNeuralNetwork.java
More file actions
487 lines (409 loc) · 16.4 KB
/
NeuralNetwork.java
File metadata and controls
487 lines (409 loc) · 16.4 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
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
package assignment3part4;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class NeuralNetwork {
private class Record
{
private double[] input; //iputs of record
private double[] output; //outputs of record
//Construcotr of record
private Record(double[] input, double[] output)
{
this.input = input;
this.output = output;
}
}
private int numberRecords; //number of training records
private int numberInputs; //number of inputs
private int numberOutputs; //number of outputs
private int numberMiddle; //numbner of hidden nodes
private int numberIterations; //number of iterations
private double rate; //learning rate
private ArrayList<Record> records; //list of training records
private double[] input; //inputs
private double[] output; //outputs at output nodes
private double[] middle; //outputs at hidden nodes
private double[] errorMiddle; //error at hidden nodes
private double[] errorOut; //errors at output nodes
private double[]thetaMiddle; //thetas at hidden nodes
private double[] thetaOut; //thetas at output nodes
private double[][] matrixMiddle; //weights between input/hidden nodes
private double[][] matrixOut; //meights between hidden / ouput nodes
private final int COLUMN1MAX = 880;
private final int COLUMN1MIN = 510;
private final int COLUMN2MAX = 89;
private final int COLUMN2MIN = 31;
private final int COLUMN3MAX = 79;
private final int COLUMN3MIN = 30;
//Constructor of neural network
public NeuralNetwork()
{
//parameters are zero
numberRecords = 0;
numberInputs = 0;
numberOutputs = 0;
numberMiddle = 0;
numberIterations = 0;
rate = 0;
//array are empty
records = null;
input = null;
middle = null;
output = null;
errorMiddle = null;
errorOut = null;
thetaMiddle = null;
thetaOut = null;
matrixMiddle = null;
matrixOut = null;
}
//Method loads training recotrds from training file
public void loadTrainingData(String trainingFile) throws IOException
{
Scanner inFile = new Scanner(new File(trainingFile));
//read number of records, inputs, outputs
numberRecords = inFile.nextInt();
numberInputs = inFile.nextInt();
numberOutputs = inFile.nextInt();
//empty list of records
records = new ArrayList<Record>();
//for each training record
for (int i = 0; i < numberRecords; i++)
{
//read inputs
double[] input = new double[numberInputs];
String[] inputS = new String[numberInputs];
for (int j = 0; j < numberInputs; j++)
{
if (0 <= j && j < 3) {
input[j] = inFile.nextDouble();
input[j] = normalize(input[j], j);
}
else
{
inputS[j] = inFile.next();
if (inputS[j].equals("male"))
input[j] = 1;
else if (inputS[j].equals("female"))
input[j] = 0;
else if (inputS[j].equals("single"))
input[j] = 0;
else if (inputS[j].equals("divorced"))
input[j] = .5;
else if (inputS[j].equals("married"))
input[j] = 1;
}
}
//read ouputs
double[] output = new double[numberOutputs];
String[] outputS = new String[numberOutputs];
for (int j = 0; j < numberOutputs; j++){
outputS[j] = inFile.next();
if (outputS[j].equals("high"))
output[j] = .25;
else if (outputS[j].equals("low"))
output[j] = .5;
else if (outputS[j].equals("medium"))
output[j] = .75;
else if (outputS[j].equals("undetermined"))
output[j] = 1;
}
//create training record record
Record record = new Record(input, output);
//add record to list
records.add(record);
}
inFile.close();
}
//Method for normalizing data from input file
private double normalize(double value, int column)
{
double temp = value;
if (column == 0)
value = (value - COLUMN1MIN)/(COLUMN1MAX - COLUMN1MIN);
if (column == 1)
value = (value - COLUMN2MIN)/(COLUMN2MAX - COLUMN2MIN);
if (column == 2)
value = (value - COLUMN3MIN)/(COLUMN3MAX - COLUMN3MIN);
if (value < 0 || value > 1)
System.out.println();
return value;
}
//Method sets parameters of neural network
public void setParameters(int numberMiddle, int numberIterations, int seed, double rate)
{
//set hidden nodes, iterations, rate
this.numberMiddle = numberMiddle;
this.numberIterations = numberIterations;
this.rate = rate;
//initialize random number generation
Random rand = new Random(seed);
//create input/output arrays
input = new double[numberInputs];
output = new double[numberOutputs];
middle = new double[numberMiddle];
//create error arrays
errorMiddle = new double[numberMiddle];
errorOut = new double[numberOutputs];
//initialize thetas at hedden nodes
thetaMiddle = new double[numberMiddle];
for (int i = 0; i < numberMiddle; i++)
thetaMiddle[i] = 2 * rand.nextDouble() - 1;
//initialize thetas at output nodes
thetaOut = new double[numberOutputs];
for (int i = 0; i < numberOutputs; i++)
thetaOut[i] = 2 * rand.nextDouble() - 1;
//initialize weights between input/hidden nodes
matrixMiddle = new double[numberInputs][numberMiddle];
for (int i = 0; i < numberInputs; i++)
for (int j = 0; j < numberMiddle; j++)
matrixMiddle[i][j] = 2 * rand.nextDouble() - 1;
//initialize weights between hidden/ouput nodes
matrixOut = new double[numberMiddle][numberOutputs];
for (int i = 0; i < numberMiddle; i++)
for (int j = 0; j < numberOutputs; j++)
matrixOut[i][j] = 2 * rand.nextDouble() - 1;
}
//Method trains neural network
public void train()
{
//repeat iteration number of times
for (int i = 0; i < numberIterations; i++)
//for each training record
for (int j = 0; j < numberRecords; j++)
{
//calculate input/output
forwardCalculation(records.get(j).input);
//compute errors, pudate weights/thetas
backwardCalculation(records.get(j).output);
}
}
//Method performs forward pass - computes input / output
// private void forwardCalculation(double[] trainingInput)
// {
// //feed inputs of record
// for (int i = 0; i < numberInputs; i++)
// input[i] = trainingInput[i];
//
// //for each hidden node
// for (int i = 0; i < numberMiddle; i++)
// {
// double sum = 0;
//
// //compute input at hidden node
// for (int j = 0; j < numberInputs; j++)
// sum += input[j] * matrixMiddle[j][i];
//
// //add theta
// sum += thetaMiddle[i];
//
// //compute output at hedden node
// middle[i] = 1/(1 + Math.exp(-sum));
// }
//
// //for each output node
// for (int i = 0; i < numberOutputs; i++)
// {
// double sum = 0;
//
// //compute input at output node
// for (int j = 0; j < numberMiddle; j++)
// sum += middle[j] * matrixOut[j][i];
//
// //add theta
// sum += thetaOut[i];
//
// //compute output at output node
// output[i] = 1/(1 + Math.exp(-sum));
// }
// }
private double forwardCalculation(double[] trainingInput)
{
for (int i = 0; i < numberInputs; i++)
{
input[i] = trainingInput[i];
}
for (int i = 0; i < numberMiddle; i++)
{
double sum = 0;
for (int j = 0; j < numberInputs; j++)
{
sum += input[j]*matrixMiddle[j][i];
}
sum += thetaMiddle[i];
middle[i] = 1/(1 + Math.exp(-sum));
}
for (int i = 0; i < numberOutputs; i++)
{
}
}
//Method performs backward pass - computes errors, updates weights / thetas
private void backwardCalculation(double[] trainingOutput)
{
//compute error at each output node
for (int i = 0; i < numberOutputs; i++)
errorOut[i] = output[i] * (1 - output[i]) * (trainingOutput[i] - output[i]);
//compute error at each hidden node
for (int i = 0; i < numberMiddle; i++)
{
double sum = 0;
for (int j = 0; j < numberOutputs; j++)
sum += matrixOut[i][j] * errorOut[j];
errorMiddle[i] = middle[i] * (1 - middle[i]) * sum;
}
//update weights between hidden / output nodes
for (int i = 0; i < numberMiddle; i++)
for (int j = 0; j < numberOutputs; j++)
matrixOut[i][j] += rate * middle[i] * errorOut[j];
//update weights between input / hidden nodes
for (int i = 0; i < numberInputs; i++)
for (int j = 0; j < numberMiddle; j++)
matrixMiddle[i][j] += rate * input[i] * errorMiddle[j];
//update thetas at output nodes
for (int i = 0; i < numberOutputs; i++)
thetaOut[i] += rate * errorOut[i];
//update thetas at hedden nodes
for (int i = 0; i < numberMiddle; i++)
thetaMiddle[i] += rate * errorMiddle[i];
}
//Method computes output of an input
private double[] test(double[] input)
{
//forward pass input
forwardCalculation(input);
//return output produced
return output;
}
//Method reads inputs from input file and writes outputs to output file
public void testData(String inputFile, String outputFile) throws IOException
{
Scanner inFile = new Scanner(new File(inputFile));
PrintWriter outFile = new PrintWriter(new FileWriter(outputFile));
int numberRecords = inFile.nextInt();
//for each record
for (int i = 0; i < numberRecords; i++)
{
//read inputs
double[] input = new double[numberInputs];
String[] inputS = new String[numberInputs];
for (int j = 0; j < numberInputs; j++)
{
if (0 <= j && j < 3) {
input[j] = inFile.nextDouble();
input[j] = normalize(input[j], j);
}
else
{
inputS[j] = inFile.next();
if (inputS[j].equals("male"))
input[j] = 1;
else if (inputS[j].equals("female"))
input[j] = 0;
else if (inputS[j].equals("single"))
input[j] = 0;
else if (inputS[j].equals("divorced"))
input[j] = .5;
else if (inputS[j].equals("married"))
input[j] = 1;
}
}
//find ouput using neural network
double[] output = test(input);
//write ouput to ouput file
for (int j = 0; j < numberOutputs; j++)
{
output[j] = output[j] * (1 - .25) + .25;
outFile.print(output[j] + " ");
}
outFile.println();
}
inFile.close();
outFile.close();
}
//method calidates the network using the data from a file
public void validate(String validationFile) throws IOException
{
Scanner inFile = new Scanner(new File(validationFile));
int numberRecords = inFile.nextInt();
//for each record
for (int i = 0; i < numberRecords; i++)
{
double[] input = new double[numberInputs];
String[] inputS = new String[numberInputs];
for (int j = 0; j < numberInputs; j++)
{
if (0 <= j && j < 3) {
input[j] = inFile.nextDouble();
input[j] = normalize(input[j], j);
}
else
{
inputS[j] = inFile.next();
if (inputS[j].equals("male"))
input[j] = 1;
else if (inputS[j].equals("female"))
input[j] = 0;
else if (inputS[j].equals("single"))
input[j] = 0;
else if (inputS[j].equals("divorced"))
input[j] = .5;
else if (inputS[j].equals("married"))
input[j] = 1;
}
}
//read ouputs
double[] actualOutput = new double[numberOutputs];
String[] outputS = new String[numberOutputs];
for (int j = 0; j < numberOutputs; j++){
outputS[j] = inFile.next();
if (outputS[j].equals("high"))
actualOutput[j] = 0;
else if (outputS[j].equals("low"))
actualOutput[j] = .25;
else if (outputS[j].equals("medium"))
actualOutput[j] = .5;
else if (outputS[j].equals("undetermined"))
actualOutput[j] = .75;
}
//read inputs
// double[] input = new double[numberInputs];
// for (int j = 0; j < numberInputs; j++)
// input[j] = inFile.nextDouble();
//
// //read actual outputs
// double[] actualOutput = new double[numberOutputs];
// for (int j = 0; j < numberOutputs; j++)
// actualOutput[j] = inFile.nextDouble();
//
// if (i == 11)
// System.out.println();
//find predicted output
double[] predictedOutput = test(input);
// for (int j = 0; j < numberOutputs; j++) {
// predictedOutput[j] = predictedOutput[j] * (1 - .25) + .25;
// actualOutput[j] = predictedOutput[j] * (1 - .25) + .25;
//
// if (predictedOutput[j] > )
// }
//write actual and predicted outputs
for (int j = 0; j < numberOutputs; j++)
System.out.println(actualOutput[j] + " " + predictedOutput[j]);
}
inFile.close();
}
//Method finds root mean square error between actual and predicted output
private double computeError(double[] actualOutput, double[] predictedOutput)
{
double error = 0;
//sum of squares of errors
for (int i = 0; i < actualOutput.length; i++)
error += Math.pow(actualOutput[i] - predictedOutput[i], 2);
//root mean square error
return Math.sqrt(error / actualOutput.length);
}
}