-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNeural.java
97 lines (91 loc) · 2.73 KB
/
Neural.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
// Evolve deep random projection neural network class
// Example. Not part of Data Reservoir Compute AI.
package s6regen;
public class Neural {
final int vecLen;
final int density;
final int depth;
final int precision;
final long hash;
float parentCost;
float[][][] weights;
float[][][] mWeights;
float[] workA;
float[] workB;
float[] workC;
float[] workD;
RNG rnd;
// vecLen must be 2,4,8,16,32.....
public Neural(int vecLen, int density, int depth,int precision) {
this.vecLen=vecLen;
this.density=density;
this.depth=depth;
this.precision=precision;
parentCost=Float.POSITIVE_INFINITY;
weights=new float[depth][density][vecLen];
mWeights=new float[depth][density][vecLen];
workA=new float[vecLen];
workB=new float[vecLen];
workC=new float[vecLen];
workD=new float[vecLen];
rnd=new RNG();
hash=rnd.nextLong();
for (int i=0; i<depth; i++) {
for (int j=0; j<density; j++) {
for (int k=0; k<vecLen; k++) {
weights[i][j][k]=rnd.nextFloatSym();
}
}
}
float sc=1f/(float)Math.sqrt(density);
for (int j=0; j<density; j++) {
VecOps.scale(weights[depth-1][j], weights[depth-1][j], sc);
}
}
void recall(float[] resultVec, float[] inVec) {
VecOps.adjust(workA, inVec);
long h=hash;
for (int i=0; true; i++) {
System.arraycopy(workA, 0, workB, 0, vecLen);
java.util.Arrays.fill(resultVec, 0f);
for (int j=0; j<density; j++) {
WHT.fastRP(workA, h++);
WHT.fastRP(workB, h++);
VecOps.multiply(workC, workA, workB);
WHT.fastRP(workC, h++);
VecOps.multiplyAddTo(resultVec, workC, weights[i][j]);
}
if (i==depth-1) break;
VecOps.adjust(workA, resultVec);
}
}
// the elements of targetVecs should have a magnitude of around 0 to 1.
void train(float[][] targetVecs, float[][] inputVecs) {
for (int i=0; i<depth; i++) { // create mutated weights
for (int j=0; j<density; j++) {
for (int k=0; k<vecLen; k++) {
mWeights[i][j][k]=rnd.mutateXSym(weights[i][j][k], precision);
}
}
}
float[][][] t=weights; // swap the weights with the mutated weights
weights=mWeights;
mWeights=t;
float cCost=0f; //evaluate the cost of the mutated weights.
for (int i=0; i<targetVecs.length; i++) {
recall(workD, inputVecs[i]);
VecOps.subtract(workD, targetVecs[i], workD);
cCost+=VecOps.sumSq(workD);
}
if (cCost<=parentCost) {
parentCost=cCost; // keep the mutated weights as new parent
} else { // else swap back the old unmutated parent weights
t=weights;
weights=mWeights;
mWeights=t;
}
}
float getCost(){
return parentCost;
}
}