Debian Codegraph @

current/ml/CellNet.java

raw symbols SCIP
1 package ml;
2
3 import java.util.ArrayList;
4 import java.util.Arrays;
5 import java.util.BitSet;
6 import java.util.Random;
7
8 import shared.Shared;
9 import shared.Tools;
10 import shared.Vector;
11 import structures.ByteBuilder;
12 import structures.FloatList;
13 import structures.IntList;
14
15 public class CellNet implements Cloneable, Comparable<CellNet> {
16
17 /*--------------------------------------------------------------*/
18 /*---------------- Initialization ----------------*/
19 /*--------------------------------------------------------------*/
20
21 public CellNet() {//Dummy network
22 seed=0;
23 dims=null;
24 density=1;
25 density1=0;
26 edgeBlockSize=1;
27 layers=0;
28 values=null;
29 weightsIn=weightsOut=null;
30 eOverNet=null;
31 list=null;
32 net=null;
33 finalLayer=null;
34 transposeCounter=null;
35 layerStart=null;
36 }
37
38 public CellNet(int[] dims_, long seed_, float density_, float density1_,
39 int edgeBlockSize_, ArrayList<String> commands_) {
40 seed=(seed_>=0 ? seed_ : new Random().nextLong()&Long.MAX_VALUE);
41 commands=commands_;
42 dims=dims_.clone();
43 density=density_;
44 density1=density1_;
45 edgeBlockSize=edgeBlockSize_;
46 layers=dims.length;
47 values=makeFloatMatrix(dims);
48 eOverNet=makeFloatMatrix(dims);
49
50 int cells=(int) shared.Vector.sum(dims);
51 list=new ArrayList<Cell>(cells+1);
52 transposeCounter=new int[cells+1];
53 net=makeNodes(dims, list, values, eOverNet);
54 finalLayer=net[layers-1];
55 layerStart=new int[dims.length];
56 layerStart[0]=1;
57 for(int i=1; i<layerStart.length; i++) {
58 layerStart[i]=layerStart[i-1]+dims[i-1];
59 }
60
61 // weights=makeWeightsMatrix();
62 // weightsOut=makeWeightsOutMatrix();
63 }
64
65 void makeWeightMatrices(){
66 // assert(check());
67 assert(weightsIn==null);
68 weightsIn=makeWeightsInMatrix();
69 weightsOut=makeWeightsOutMatrix();
70 edgesIn=makeEdgesInMatrix();
71 edgesOut=makeEdgesOutMatrix();
72 // assert(check());
73 }
74
75 private float[][][] makeWeightsInMatrix(){
76 float[][][] x=new float[dims.length][][];
77 for(int layer=1; layer<x.length; layer++) {
78 Cell[] currentLayer=net[layer];
79 float[][] y=x[layer]=new float[currentLayer.length][];
80 for(int i=0; i<y.length; i++) {
81 y[i]=currentLayer[i].weights;
82 }
83 }
84 return x;
85 }
86
87 private int[][][] makeEdgesInMatrix(){
88 int[][][] x=new int[dims.length][][];
89 for(int layer=1; layer<x.length; layer++) {
90 Cell[] currentLayer=net[layer];
91 int[][] y=x[layer]=new int[currentLayer.length][];
92 for(int i=0; i<y.length; i++) {
93 y[i]=currentLayer[i].inputs;
94 }
95 }
96 return x;
97 }
98
99 private float[][][] makeWeightsOutMatrix(){
100 float[][][] x=new float[dims.length][][];
101 for(int layer=0; layer<x.length-1; layer++) {
102 Cell[] current=net[layer];
103 Cell[] next=net[layer+1];
104 float[][] y=x[layer]=new float[current.length][];
105 if(DENSE) {
106 for(int i=0; i<y.length; i++) {
107 y[i]=new float[next.length];
108 }
109 }else {
110 for(int i=0; i<y.length; i++) {
111 assert(current[i].outputs!=null) : layer+", "+i+", "+current[i].id();
112 y[i]=new float[current[i].outputs.length];
113 }
114 }
115 }
116 return x;
117 }
118
119 private int[][][] makeEdgesOutMatrix(){
120 int[][][] x=new int[dims.length][][];
121 for(int layer=0; layer<x.length-1; layer++) {
122 Cell[] currentLayer=net[layer];
123 int[][] y=x[layer]=new int[currentLayer.length][];
124 for(int i=0; i<y.length; i++) {
125 y[i]=currentLayer[i].outputs;
126 }
127 }
128 return x;
129 }
130
131 public void randomize() {
132 {
133 Random randy=Shared.threadLocalRandom(seed);
134 if(DENSE) {
135 makeEdgesDense(net, randy, density, density1, edgeBlockSize);
136 // check();
137 }else {
138 makeEdgesSparse(net, randy, density, density1, edgeBlockSize);
139 // check();
140 }
141 makeWeightMatrices();
142 // check();
143 }
144 assert((Function.TYPE_RATES_CUM!=null)==(shared.Vector.sum(Function.TYPE_RATES)>0)) : Arrays.toString(Function.TYPE_RATES);
145 if(Function.TYPE_RATES_CUM!=null || Cell.randomTypeRate>0) {
146 Random randy=Shared.threadLocalRandom(seed);
147 if(Function.TYPE_RATES_CUM!=null) {
148 randomizeActivationA(net, list, randy, Function.TYPE_RATES_CUM);
149 }else{
150 randomizeActivationB(net, list, randy, Cell.randomTypeRate);
151 }
152 }
153 }
154
155 static void randomizeActivationA(Cell[][] net, ArrayList<Cell> list, Random randy, float[] cumRate) {
156 assert(cumRate!=null && cumRate[cumRate.length-1]==1) : Arrays.toString(cumRate);
157
158 for(int layerNum=1; layerNum<net.length-1; layerNum++) {//Only middle layers
159 Cell[] layer=net[layerNum];
160 for(Cell c : layer) {
161 // c.type=randomType(randy, cumRate);
162 c.function=Function.randomFunction(randy);
163 }
164 }
165 }
166
167 static void randomizeActivationB(Cell[][] net, ArrayList<Cell> list, Random randy, float rate) {
168 assert(rate>0);
169 // final int types=Cell.TYPES.length;
170 final int types=Tools.min(Cell.MAX_TYPE+1, Function.TYPES.length);
171 // assert(false) : types;
172 // System.err.println("types="+types);
173 for(int layerNum=1; layerNum<net.length-1; layerNum++) {//Only middle layers
174 Cell[] layer=net[layerNum];
175 for(Cell c : layer) {
176 if(randy.nextFloat()<rate) {
177 // int t=c.type;
178 // while(t==c.type) {t=randy.nextInt(types);}
179 // c.type=t;
180 Function f=c.function;
181 while(f==c.function) {f=Function.getFunction(randy.nextInt(types));}
182 c.function=f;
183 }
184 }
185 }
186 }
187
188 private static float[][] makeFloatMatrix(int[] dims){
189 //TODO: Note - these can be made 1 longer with a constant of 1 to include bias
190 float[][] matrix=new float[dims.length][];
191 for(int i=0; i<dims.length; i++) {
192 matrix[i]=new float[dims[i]];
193 }
194 return matrix;
195 }
196
197 private static Cell[][] makeNodes(int[] dims, ArrayList<Cell> list, float[][] values, float[][] eOverNext){
198 final Cell[][] net=new Cell[dims.length][];
199 assert(list.isEmpty());
200 list.add(null);
201 // int prevWidth=-1, width=dims[0], nextWidth;
202 int[] layerStart=new int[dims.length];
203 for(int i=0, sum=1; i<dims.length; i++) {
204 layerStart[i]=sum;
205 sum+=dims[i];
206 }
207 for(int layerNum=0; layerNum<dims.length; layerNum++) {
208 final int prevLayerStart=(layerNum==0 ? -1 : layerStart[layerNum-1]);
209 final int nextLayerStart=(layerNum>=dims.length-1 ? -1 : layerStart[layerNum+1]);
210 final int width=dims[layerNum];
211 final int type=(layerNum<dims.length-1) ? Cell.defaultActivationType : Cell.finalLayerType;
212 Cell[] layer=net[layerNum]=new Cell[width];
213 float[] lvals=values[layerNum];
214 float[] eons=eOverNext[layerNum];
215 assert(lvals.length==width) : layerNum+", "+lvals.length+", "+width;
216 for(int i=0; i<width; i++){
217 Cell c=new Cell(list.size(), type, i, layerNum, dims.length-1,
218 prevLayerStart, nextLayerStart, width, lvals, eons);
219 layer[i]=c;
220 list.add(c);
221 }
222 }
223 return net;
224 }
225
226 private static final float layerDensity(float density, float density1, int layer, int layers) {
227 return layer>=layers+1 ? 1f : (layer==1 && density1>0) ? density1 : density;
228 }
229
230 //Fully-connected, but weight 0 edges are not used
231 private static long makeEdgesDense(Cell[][] net, Random randy,
232 float density, float density1, int edgeBlockSize){
233 long numEdges=0;
234 for(int layerNum=1; layerNum<net.length; layerNum++) {
235 final float layerDensity=layerDensity(density, density1, layerNum, net.length);
236 Cell[] layer=net[layerNum], prev=net[layerNum-1];
237 final boolean finalLayer=(layerNum==net.length-1);
238 // final int minLen=Tools.mid(1, 5, prev.length/3);
239 for(Cell c : layer) {
240 assert(c.weights==null);
241 c.weights=new float[prev.length];
242 c.deltas=new float[prev.length];
243 c.setBias(randomBias(randy, 0.8f), true);//TODO: 0.8f should be a parameter
244 final float[] weights=c.weights;
245 // int nonzero=0;
246 // for(int attempt=0; attempt<10 && nonzero<minLen; attempt++) {
247 // nonzero=0;
248 // for(int i=0; i<weights.length; i++) {
249 // float w=randomWeight(randy, 0.5f);
250 // w=(finalLayer || randy.nextFloat()<=density ? w : 0);
251 // weights[i]=w;
252 // numEdges+=(w==0 ? 0 : 1);
253 // nonzero+=(w==0 ? 0 : 1);
254 // }
255 // }
256 if(finalLayer) {
257 for(int i=0; i<weights.length; i++) {
258 weights[i]=randomWeight(randy);
259 numEdges++;
260 }
261 }else {
262 BitSet bs=pickEdges(weights.length, edgeBlockSize, layerDensity, randy);
263 // System.err.println(bs);
264 for(int i=bs.nextSetBit(0); i>=0; i=bs.nextSetBit(i+1)) {
265 weights[i]=randomWeight(randy);
266 numEdges++;
267 }
268 }
269 // assert(false) : Arrays.toString(c.weights);
270 }
271 }
272 return numEdges;
273 }
274
275 private static long makeEdgesSparse(Cell[][] net, Random randy,
276 float density, float density1, int edgeBlockSize){
277 long numEdges=0;
278 for(int layerNum=1; layerNum<net.length; layerNum++) {
279 final float layerDensity=layerDensity(density, density1, layerNum, net.length);
280 Cell[] layer=net[layerNum], prev=net[layerNum-1];
281 final boolean finalLayer=(layerNum==net.length-1);
282 // final int minLen=Tools.mid(1, 5, prev.length/3);
283 for(Cell c : layer) {
284 assert(c.weights==null);
285 c.setBias(randomBias(randy, 0.8f), true);//TODO: 0.8f should be a parameter
286 if(finalLayer) {
287 c.inputs=new int[prev.length];
288 for(int i=0; i<c.inputs.length; i++) {c.inputs[i]=i;}
289 }else{
290 BitSet bs=pickEdges(prev.length, edgeBlockSize, layerDensity, randy);
291 // System.err.println(bs);
292 c.inputs=toArray(bs);
293 }
294 c.weights=new float[c.inputs.length];
295 c.deltas=new float[c.inputs.length];
296 for(int i=0; i<c.weights.length; i++) {
297 c.weights[i]=randomWeight(randy);
298 }
299 numEdges+=(c.weights.length);
300 }
301 }
302 makeOutputSets(net);
303 return numEdges;
304 }
305
306 private static BitSet pickEdges(int width, int edgeBlockSize, float density, Random randy) {
307 int toMake=0;
308 int min=Tools.mid(1, 5, width/3);
309 for(int i=0; i<width; i++) {
310 if(randy.nextFloat()<=density) {toMake++;}
311 }
312 toMake=Tools.max(toMake, min);
313 int mod=toMake%edgeBlockSize;
314 if(mod!=0) {toMake=Tools.min(width, toMake-mod+edgeBlockSize);}
315 BitSet bs=new BitSet(width);
316 int range=(width-1)/edgeBlockSize;
317 for(int made=0; made<toMake;) {
318 int start=randy.nextInt(range+1)*edgeBlockSize;
319 if(start<width && !bs.get(start)) {
320 for(int i=0; i<edgeBlockSize && i+start<width; i++) {
321 bs.set(i+start);
322 made++;
323 }
324 }
325 }
326 // System.err.println(bs);
327 return bs;
328 }
329
330 static int[] toArray(BitSet bs) {
331 int[] array=new int[bs.cardinality()];
332 for(int i=bs.nextSetBit(0), j=0; i>=0; i=bs.nextSetBit(i+1), j++) {
333 array[j]=i;
334 }
335 return array;
336 }
337
338 static void makeOutputSets(Cell[][] net) {
339 final int cells;
340 {
341 Cell[] lastLayer=net[net.length-1];
342 Cell c=lastLayer[lastLayer.length-1];
343 cells=c.id();
344 }
345 IntList[] map=new IntList[cells+1];
346 for(int lnum=0; lnum<net.length-1; lnum++) {
347 for(Cell c : net[lnum]) {
348 assert((c.inputs!=null || c.layer==0) && c.outputs==null);
349 map[c.id()]=new IntList();
350 }
351 }
352 for(int lnum=1; lnum<net.length; lnum++) {
353 for(Cell c : net[lnum]) {
354 for(int i : c.inputs) {
355 map[i+c.prevLayerStart].add(c.lpos);
356 }
357 }
358 }
359 for(int lnum=0; lnum<net.length-1; lnum++) {
360 for(Cell c : net[lnum]) {
361 c.outputs=map[c.id()].toArray();
362 // System.err.println("c"+c.id()+" outputs="+c.outputs.length);
363 }
364 }
365 }
366
367 private static float randomBias(Random randy, float probFlat) {
368 float weight=0;
369 while(Math.abs(weight)<=Float.MIN_NORMAL) {
370 if(randy.nextFloat()<=probFlat){
371 weight=(1-2*randy.nextFloat())*.25f;
372 }else{
373 weight=randy.nextFloat()*randy.nextFloat()*randy.nextFloat()*2*(randy.nextBoolean() ? 1 : -1);
374 }
375 }
376 return weight;
377 }
378
379 //Distributed between -2 and 2. probFlat=1 gives a uniform distribution from -1 to 1; 0 gives quadratic.
380 private static float randomWeight(Random randy) {
381 float weight=0;
382 while(Math.abs(weight)<=Float.MIN_NORMAL) {
383 final float f=randy.nextFloat();
384 if(f<=PROB_FLAT){
385 weight=(1-2*randy.nextFloat())*.25f;
386 }else if(f<=PROB_FLAT+PROB_EXP){
387 weight=(float)(Tools.exponential(randy, EXP_LAMDA)*(randy.nextBoolean() ? 1f : -1f));
388 }else{
389 weight=randy.nextFloat()*randy.nextFloat()*randy.nextFloat()*2*(randy.nextBoolean() ? 1f : -1f);
390 }
391 }
392 weight=Tools.mid(-RAND_WEIGHT_CAP, weight, RAND_WEIGHT_CAP);
393 return weight;
394 }
395
396 /*--------------------------------------------------------------*/
397 /*---------------- Methods ----------------*/
398 /*--------------------------------------------------------------*/
399
400
401 void anneal(float strength, Random randy) {
402 //assert(check());
403 for(Cell c : list) {
404 if(c!=null) {c.anneal(strength, randy);}
405 }
406
407 //assert(check());
408 }
409
410 public void processSample(Sample s, boolean backProp, float weightMult) {
411 //assert(check());
412
413 applyInput(s.in);
414 if(DENSE) {
415 feedForwardDense();
416 }else {
417 feedForwardSparse();
418 }
419
420 // s.errorValue=0;
421 for(int i=0; i<finalLayer.length; i++) {
422 s.result[i]=finalLayer[i].value();
423 // s.errorValue+=(s.result[i]-s.goal[i]);
424 }
425
426 s.calcError(weightMult);
427
428 if(!backProp) {return;}
429
430 // double error=calcError(s.goal);
431 // assert(error==s.errorMagnitude) : "\n"+s.result[0]+", "+s.goal[0]+", "+s.errorMagnitude+"\n"
432 // + finalLayer[0].value()+", "+s.goal[0]+", "+error+"\n";
433
434 // s.errorMagnitude=(float)error;
435 // s.weightedErrorMagnitude=(float)error*Cell.getWeightMultiplier(s.result[0], s.goal[0]);
436
437 // errorSum+=s.errorMagnitude;
438 // weightedErrorSum+=s.weightedErrorMagnitude;
439 if(DENSE) {
440 backPropDense(s.goal, weightMult);
441 }else {
442 backPropSparse(s.goal, weightMult);
443 }
444 //assert(check());
445 }
446
447 public void applyInput(FloatList valuesIn) {
448 //assert(check());
449 assert(valuesIn.size==dims[0]) : valuesIn.size+"; "+Arrays.toString(dims);
450 Vector.copy(values[0], valuesIn.array);
451 return;
452 }
453
454 public void applyInput(float[] valuesIn) {
455 //assert(check());
456 assert(valuesIn.length==dims[0]) : valuesIn.length+"; "+Arrays.toString(dims);
457 Vector.copy(values[0], valuesIn);
458 return;
459 }
460
461 public float feedForward() {
462 return (CellNet.DENSE ? feedForwardDense() : feedForwardSparse());
463 }
464
465 public float feedForwardSparse(){
466 //assert(check());
467 for(int lnum=1; lnum<layers; lnum++){
468 final float[] valuesIn=values[lnum-1];
469 Cell[] layer=net[lnum];
470 for(int cnum=0; cnum<layer.length; cnum++) {
471 Cell c=layer[cnum];
472 // //assert(c.check());
473 c.summateSparse(valuesIn, edgeBlockSize);
474 // //assert(c.check());
475 }
476 }
477 return finalLayer[0].value();
478 }
479
480 public float feedForwardDense(){
481 //assert(check());
482 for(int lnum=1; lnum<layers; lnum++){
483 final float[] valuesIn=values[lnum-1];
484 Cell[] layer=net[lnum];
485 if(SPECIAL_FMA) {
486 Vector.feedForwardDense(layer, valuesIn);
487 }else {
488 for(int cnum=0; cnum<layer.length; cnum++) {
489 Cell c=layer[cnum];
490 // //assert(c.check());
491 c.summateDense(valuesIn);
492 // //assert(c.check());
493 }
494 }
495 }
496 return finalLayer[0].value();
497 }
498
499 public void backPropSparse(float[] truth, float weightMult) {
500 //assert(check());
501 {
502 final float[] valuesIn=values[values.length-2];
503 for(int i=0; i<finalLayer.length; i++) {
504 final Cell c=finalLayer[i];
505 //Final layer is always dense
506 c.updateEdgesFinalLayerDense(truth[i], valuesIn, weightMult);
507 }
508 }
509
510 for(int lnum=layers-2; lnum>0; lnum--) {
511 final float[] valuesIn=values[lnum-1];
512 final float[] eOverNetNext=eOverNet[lnum+1];
513 Cell[] layer=net[lnum];
514 float[][] weightsOutLnum=weightsOut[lnum];
515
516 for(int i=0; i<layer.length; i++){
517 Cell c=layer[i];
518 //assert(c.check());
519 c.updateEdgesHiddenLayerSparse(valuesIn, eOverNetNext, weightsOutLnum[i], edgeBlockSize);
520 //assert(c.check());
521 }
522 }
523 //assert(check());
524 }
525
526 public void backPropDense(float[] truth, float weightMult) {
527 //assert(check());
528 {
529 final float[] valuesIn=values[values.length-2];
530 for(int i=0; i<finalLayer.length; i++) {
531 final Cell c=finalLayer[i];
532 //assert(c.check());
533 c.updateEdgesFinalLayerDense(truth[i], valuesIn, weightMult);
534 //assert(c.check());
535 }
536 }
537
538 for(int lnum=layers-2; lnum>0; lnum--) {
539 final float[] valuesIn=values[lnum-1];
540 final float[] eOverNetNext=eOverNet[lnum+1];
541 Cell[] layer=net[lnum];
542 float[][] weightsOutLnum=weightsOut[lnum];
543
544 if(SPECIAL_FMA) {Vector.backPropFma(layer, eOverNetNext, weightsOutLnum);}
545 for(int i=0; i<layer.length; i++){
546 Cell c=layer[i];
547 //assert(c.check());
548 c.updateEdgesHiddenLayerDense(valuesIn, eOverNetNext, weightsOutLnum[i]);
549 //assert(c.check());
550 }
551 }
552 //assert(check());
553 if(normalization_factor>0.0001f) {
554 if(NORMALIZE_BIAS) {normalizeBiasDense();}
555 if(NORMALIZE_WEIGHTS) {normalizeWeightsDense();}
556 normalization_factor*=normalization_shrink_rate;
557 }
558 }
559
560 /**
561 * Normalizes the biases of the dense layers in the network.
562 */
563 public void normalizeBiasDense() {
564 FloatList list=new FloatList();
565 for(int lnum=layers-2; lnum>0; lnum--) {
566 list.clear();
567 Cell[] layer=net[lnum];
568 for(int i=0; i<layer.length; i++){
569 Cell c=layer[i];
570 list.add(c.bias);
571 }
572 float mean=(float)list.mean();
573 float stdev=list.stdev();
574 if(stdev<0.001f) {stdev=0.001f;}//Avoid division by zero
575 float invStdev=1f/stdev;
576 for(int i=0; i<layer.length; i++){
577 Cell c=layer[i];
578 float f=c.bias;
579 float target=(f-mean)*invStdev;
580 f=(1f-normalization_factor)*f+normalization_factor*target;
581 c.bias=f;
582 }
583 }
584 }
585
586 public void normalizeWeightsDense() {
587 FloatList list=new FloatList();
588 for(int layer=0; layer<weightsIn.length-1; layer++) {
589 float[][] weightsInL=weightsIn[layer+1];
590 normalizeDense(weightsInL, list);
591 }
592 transposeDense();
593 }
594
595 public void normalizeDense(float[][] weights, FloatList list) {
596 if(weights==null) {return;}
597 list.clear();
598 for(float[] array : weights) {
599 for(float f : array) {
600 if(f!=0) {
601 list.add(f);
602 }
603 }
604 }
605 float mean=(float)list.mean();
606 float stdev=list.stdev();
607 if(stdev<0.001f) {stdev=0.001f;}
608 float invStdev=1f/stdev;
609 for(float[] array : weights) {
610 for(int i=0; i<array.length; i++) {
611 float f=array[i];
612 if(f!=0) {
613 float target=(f-mean)*invStdev;
614 f=(1f-normalization_factor)*f+normalization_factor*target;
615 array[i]=(Math.abs(f)<1e-12f) ? 1e-12f : f;
616 }
617 }
618 }
619 }
620
621 void transpose() {
622 if(DENSE) {transposeDense();}
623 else {transposeSparse();}
624 }
625
626 void transposeDense() {
627 for(int layer=0; layer<weightsIn.length-1; layer++) {
628 float[][] weightsInL=weightsIn[layer+1], weightsOutL=weightsOut[layer];
629 for(int lnum=0; lnum<weightsOutL.length; lnum++) {
630 float[] weightsOutC=weightsOutL[lnum];
631 for(int lnumOut=0; lnumOut<weightsInL.length; lnumOut++) {
632 weightsOutC[lnumOut]=weightsInL[lnumOut][lnum];
633 }
634 }
635 }
636 }
637
638 void transposeSparse() {
639 Arrays.fill(transposeCounter, 0);
640 for(int layer=0; layer<weightsIn.length-1; layer++) {
641 float[][] weightsInL=weightsIn[layer+1], weightsOutL=weightsOut[layer];
642 int[][] edgesOutL=edgesOut[layer];
643 for(int lnum=0; lnum<weightsOutL.length; lnum++) {
644 float[] weightsOutC=weightsOutL[lnum];
645 int[] outputs=edgesOutL[lnum];
646 assert(outputs.length==weightsOutC.length);
647 for(int i=0; i<outputs.length; i++) {
648 int lnumOut=outputs[i];
649 int cidOut=lnumOut+layerStart[layer+1];
650 // assert(false) : Arrays.toString(layerStart)+", "+layer+", "+lnumOut+", "+cidOut;
651 int inputNum=transposeCounter[cidOut];
652 transposeCounter[cidOut]++;
653 weightsOutC[i]=weightsInL[lnumOut][inputNum];
654 }
655 }
656 }
657 for(Cell c : list) {
658 assert(c==null || c.inputs==null || transposeCounter[c.id()]==c.inputs.length);
659 }
660 }
661
662 public void applyChanges(int samples, float alpha) {
663 //assert(check());
664 float invSamples=1f/samples;
665 assert(invSamples<=1) : samples+", "+invSamples;
666 for(Cell c : list) {
667 if(c!=null) {
668 c.applyUpdates(invSamples, alpha);
669 }
670 }
671 //assert(check());
672 epochsTrained++;
673 samplesTrained+=samples;
674 }
675
676 public float getOutput(int outnum){
677 return net[layers-1][outnum].value();
678 }
679
680 public float[] getOutput(){
681 Cell[] outLayer=net[layers-1];
682 float[] out=new float[outLayer.length];
683 for(int i=0; i<outLayer.length; i++) {
684 out[i]=outLayer[i].value();
685 }
686 return out;
687 }
688
689 @Deprecated
690 public double calcError(float[] truth){
691 double error=0;
692 for(int i=0; i<finalLayer.length; i++){
693 Cell c=finalLayer[i];
694 float t=truth[i];
695 float e=c.calcError(t);
696 error+=e;
697 }
698 return error;
699 }
700
701
702 /*--------------------------------------------------------------*/
703 /*---------------- X ----------------*/
704 /*--------------------------------------------------------------*/
705
706 public String toString() {
707 StringBuilder sb=new StringBuilder();
708 for(int layernum=0; layernum<layers; layernum++) {
709 Cell[] layer=net[layernum];
710 sb.append("\n* Layer "+layernum+", nodes="+layer.length+" *");
711 for(Cell c : layer) {
712 sb.append("\n"+c.toString());
713 }
714 }
715 return sb.toString();
716 }
717
718 public ByteBuilder header() {
719 ByteBuilder bb=new ByteBuilder();
720 bb.append("##bbnet").nl();
721 bb.append("#version ").append(version).nl();
722 if(CONCISE) {bb.append("#concise").nl();}
723 bb.append(OUT_DENSE ? "#dense" : OUT_SPARSE ? "#sparse" : DENSE ? "#dense" : "#sparse").nl();
724 bb.append("#density ").append(density, 8, true).nl();
725 if(density1>0 && density1!=density) {bb.append("#density1 ").append(density1, 8, true).nl();}
726 bb.append("#blocksize ").append(edgeBlockSize).nl();
727 bb.append("#seed ").append(seed).nl();
728 // if(annealSeed!=seed) {bb.append("#annealseed ").append(annealSeed).nl();}
729 bb.append("#layers ").append(layers).nl();
730 if(epochsTrained>0) {bb.append("#epochs ").append(epochsTrained).nl();}
731 if(samplesTrained>0) {bb.append("#samples ").append(samplesTrained).nl();}
732
733 bb.append("#dims");
734 for(int d : dims) {bb.space().append(d);}
735 bb.nl();
736 for(String s : commands) {bb.append(s).nl();}
737 if(lastStats!=null) {bb.append("##stats ").append(lastStats).nl();}
738 bb.append("##fpr ").append(fpRate, 6).nl();
739 bb.append("##fnr ").append(fnRate, 6).nl();
740 bb.append("##err ").append(errorRate, 6).nl();
741 bb.append("##wer ").append(weightedErrorRate, 6).nl();
742 bb.append("##ctf ").append(cutoff, 6).nl();
743 return bb;
744 }
745
746 public ByteBuilder toBytes() {
747
748 ByteBuilder bb=header();
749 bb.append("#edges ").append(countEdges()).nl();
750
751 lastLinesWritten=18;
752 long edgeCount=0;
753 assert(CONCISE);
754 for(int lnum=1; lnum<layers; lnum++) {
755 Cell[] layer=net[lnum];
756 Cell[] prev=net[lnum-1];
757 bb.append("##layer ").append(lnum).nl();
758 for(Cell c : layer){
759 if(DENSE) {
760 if(OUT_SPARSE) {
761 lastLinesWritten+=2;
762
763 if(OUT_HEX) {
764 bb.append('H').append(c.id()).space();
765 BitSet bs=new BitSet(c.weights.length);
766 for(int i=0; i<c.weights.length; i++) {
767 if(c.weights[i]!=0) {bs.set(i);}
768 }
769 toHex(bs, bb);
770 }else {
771 bb.append('I').append(c.id());
772 for(int i=0; i<c.weights.length; i++) {
773 if(c.weights[i]!=0) {
774 bb.space().append(i);
775 }
776 }
777 }
778 bb.nl();
779
780 bb.append('W').append(c.id()).space().append(c.typeString());
781 bb.space().append(c.bias(), 6, true);
782 for(int i=0; i<c.weights.length; i++) {
783 if(c.weights[i]!=0) {
784 bb.space().append(c.weights[i], 6, true);
785 edgeCount++;
786 }
787 }
788 bb.nl();
789 }else {
790 lastLinesWritten++;
791 bb.append('C').append(c.id()).space().append(c.typeString());
792 bb.space().append(c.bias(), 6, true);
793 for(int i=0; i<c.weights.length; i++) {bb.space().append(c.weights[i], 6, true);}
794 bb.nl();
795 edgeCount+=c.weights.length;
796 }
797 }else {
798 if(OUT_DENSE) {
799 lastLinesWritten++;
800 bb.append('C').append(c.id()).space().append(c.typeString());
801 bb.space().append(c.bias(), 6, true);
802 // for(int idx=0, nextInput=0; idx<c.inputs.length; idx++) {
803 // for(int inum=c.inputs[idx]; nextInput<inum; nextInput++) {
804 // bb.space().append(0);
805 // }
806 // bb.space().append(c.weights[idx], 6, true);
807 // nextInput++;
808 // }
809 int inum=0;
810 for(int idx=0; idx<c.inputs.length; inum++) {
811 if(inum==c.inputs[idx]) {
812 bb.space().append(c.weights[idx], 6, true);
813 idx++;
814 }else {
815 bb.space().append(0);
816 }
817 }
818 for(; inum<dims[c.layer-1]; inum++) {bb.space().append(0);}
819 bb.nl();
820 edgeCount+=c.weights.length;
821 }else {
822 lastLinesWritten+=2;
823 if(OUT_HEX) {
824 bb.append('H').append(c.id()).space();
825 toHex(c.inputs, bb);
826 }else {
827 bb.append('I').append(c.id());
828 for(int i=0; i<c.inputs.length; i++) {bb.space().append(c.inputs[i]);}
829 }
830 bb.nl();
831
832 bb.append('W').append(c.id()).space().append(c.typeString());
833 bb.space().append(c.bias(), 6, true);
834 for(int i=0; i<c.weights.length; i++) {bb.space().append(c.weights[i], 6, true);}
835 bb.nl();
836 edgeCount+=c.weights.length;
837 }
838 }
839 }
840 }
841 return bb;
842 }
843
844 static ByteBuilder toHex(int[] set, ByteBuilder bb) {
845 if(set==null || set.length==0) {return bb.append(0);}
846 final int max=set[set.length-1];
847 BitSet bs=new BitSet(max);
848 for(int e : set) {bs.set(e);}
849 return toHex(bs, bb);
850 }
851
852 static ByteBuilder toHex(BitSet bs, ByteBuilder bb) {
853 byte[] bytes=bs.toByteArray();
854 for(byte b : bytes) {
855 bb.append((byte)('0'+(b&15)));
856 bb.append((byte)('0'+((b>>4)&15)));
857 }
858 return bb;
859 }
860
861 static int[] fromHex(byte[] line, int start) {
862 byte[] bytes=new byte[(line.length-start)/2];
863 for(int i=start, j=0; i<line.length; i+=2, j++) {
864 byte a=line[i], b=line[i+1];
865 int x=((a-'0')&15)|(((b-'0')&15)<<4);
866 bytes[j]=(byte)x;
867 }
868 BitSet bs=BitSet.valueOf(bytes);
869 return toArray(bs);
870 }
871
872 public synchronized CellNet copy(boolean copyDelta) {
873 // assert(check());
874 CellNet copy=new CellNet(dims, seed, density, density1, edgeBlockSize, commands);
875 ArrayList<Cell> list2=copy.list;
876 for(int i=1; i<list.size(); i++) {
877 Cell c=list.get(i);
878 // assert(c.check());
879 Cell c2=list2.get(i);
880 c2.setFrom(c, copyDelta);
881 // System.err.println("Checking "+c.id()+": copyDelta="+copyDelta+", "+c.weights+", "+c.outputs
882 // +", "+c2.weights+", "+c2.outputs);
883 // assert(c2.check());
884 }
885 copy.makeWeightMatrices();
886 // assert(copy.check());
887 copy.commands=commands;
888 copy.errorRate=errorRate;
889 copy.weightedErrorRate=weightedErrorRate;
890 copy.fpRate=fpRate;
891 copy.fnRate=fnRate;
892 copy.tpRate=tpRate;
893 copy.tnRate=tnRate;
894 copy.cutoff=cutoff;
895 copy.alpha=alpha;
896 copy.annealStrength=annealStrength;
897 // copy.annealSeed=annealSeed;
898 copy.epoch=epoch;
899 copy.epochsTrained=epochsTrained;
900 copy.lastStats=lastStats;
901 copy.samplesTrained=samplesTrained;
902
903 // assert(copy.check());
904 return copy;
905 }
906
907 public CellNet setFrom(CellNet cn, boolean copyWeight2) {
908 //assert(cn.check());
909 //assert(check());
910 ArrayList<Cell> list2=cn.list;
911 for(int i=1; i<list.size(); i++) {
912 Cell c=list.get(i);
913 //assert(c.check());
914 Cell c2=list2.get(i);
915 c.setFrom(c2, copyWeight2);
916 }
917 //assert(cn.check());
918 //assert(check());
919 commands=cn.commands;
920 errorRate=cn.errorRate;
921 weightedErrorRate=cn.weightedErrorRate;
922 fpRate=cn.fpRate;
923 fnRate=cn.fnRate;
924 tpRate=cn.tpRate;
925 tnRate=cn.tnRate;
926 cutoff=cn.cutoff;
927 alpha=cn.alpha;
928 annealStrength=cn.annealStrength;
929 // annealSeed=cn.annealSeed;
930 epoch=cn.epoch;
931 epochsTrained=cn.epochsTrained;
932 lastStats=cn.lastStats;
933 samplesTrained=cn.samplesTrained;
934 return this;
935 }
936
937 public boolean check() {
938 for(int i=1; i<list.size(); i++) {
939 Cell c=list.get(i);
940 boolean b=c.check();
941 if(!b) {return false;}
942 }
943 return true;
944 }
945
946 public void addError(CellNet net2) {
947 // errorSum+=net2.errorSum;
948 // weightedErrorSum+=net2.weightedErrorSum;
949 for(int i=1; i<list.size(); i++) {
950 Cell c=list.get(i);
951 Cell c2=net2.list.get(i);
952 c.addError(c2);
953 }
954 }
955
956 public void accumulate(CellNet net2) {
957 synchronized(this) {
958 synchronized(net2) {
959 for(int i=1; i<list.size(); i++) {
960 Cell c=list.get(i);
961 Cell c2=net2.list.get(i);
962 // synchronized(c) {
963 c.accumulate(c2);
964 // }
965 }
966 }
967 }
968 }
969
970 synchronized public void clear() {
971 // errorSum=0;
972 // weightedErrorSum=0;
973 for(Cell c : list) {
974 if(c!=null) {c.clearTemp();}
975 }
976 }
977
978 /** Counts the total number of network edges via brute force,
979 * for a sparse or dense network. */
980 public long countEdges() {
981 long sum=0;
982 for(float[][] y : weightsIn) {
983 if(y!=null) {
984 for(float[] z : y) {
985 if(z!=null) {
986 for(float f : z) {
987 sum+=(f==0 ? 0 : 1);
988 }
989 }
990 }
991 }
992 }
993 return sum;
994 }
995
996 @Override
997 public int compareTo(CellNet b) {
998 if(b==null) {
999 return 1;
1000 }else if(compareCode==compareWER && weightedErrorRate!=b.weightedErrorRate) {
1001 return weightedErrorRate<b.weightedErrorRate ? 1 : -1;
1002 }else if(compareCode==compareERR && errorRate!=b.errorRate) {
1003 return errorRate<b.errorRate ? 1 : -1;
1004 }else if(compareCode==compareFNR && fnRate!=b.fnRate) {
1005 return fnRate<b.fnRate ? 1 : -1;
1006 }else if(compareCode==compareFPR && fpRate!=b.fpRate) {
1007 return fpRate<b.fpRate ? 1 : -1;
1008 }
1009
1010 if(weightedErrorRate!=b.weightedErrorRate) {
1011 return weightedErrorRate<b.weightedErrorRate ? 1 : -1;
1012 }else if(errorRate!=b.errorRate) {
1013 return errorRate<b.errorRate ? 1 : -1;
1014 }else if(fnRate!=b.fnRate) {
1015 return fnRate<b.fnRate ? 1 : -1;
1016 }else if(fpRate!=b.fpRate) {
1017 return fpRate<b.fpRate ? 1 : -1;
1018 }
1019
1020 return 0;
1021 }
1022
1023 final float pivot() {
1024 return compareCode==compareWER ? weightedErrorRate :
1025 compareCode==compareERR ? errorRate :
1026 compareCode==compareFNR ? fnRate :
1027 compareCode==compareFPR ? fpRate : weightedErrorRate;
1028 }
1029
1030 /*--------------------------------------------------------------*/
1031
1032 public int numLayers(){
1033 return dims.length;
1034 }
1035
1036 public int numInputs(){
1037 return dims[0];
1038 }
1039
1040 public int numOutputs(){
1041 return dims[dims.length-1];
1042 }
1043
1044 public void setCutoff(float f) {
1045 // System.err.println("Set cutoff from "+cutoff+" to "+f);
1046 cutoff=f;
1047 }
1048
1049 /*--------------------------------------------------------------*/
1050
1051 @Override
1052 public boolean equals(Object b) {
1053 return epoch==((CellNet)b).epoch;
1054 }
1055
1056 @Override
1057 public int hashCode() {return epoch;}
1058
1059 /*--------------------------------------------------------------*/
1060 /*---------------- Fields ----------------*/
1061 /*--------------------------------------------------------------*/
1062
1063 float errorRate=999, weightedErrorRate=999;
1064 float fpRate=999, fnRate=999, tpRate=-999, tnRate=-999;
1065 float alpha=-1, annealStrength=-1;
1066 public float cutoff=-1;
1067 int epoch=-1;
1068 int count=1; //for printing
1069
1070 long epochsTrained=0;
1071 long samplesTrained=0;
1072 String lastStats=null;
1073
1074 /*--------------------------------------------------------------*/
1075
1076 final long seed;
1077 final int layers;
1078 final int[] dims; //Stores widths of layers
1079 final float density;
1080 final float density1;
1081 final int edgeBlockSize;
1082 final Cell[][] net;
1083 final Cell[] finalLayer;
1084 final ArrayList<Cell> list;
1085
1086 final float[][] values;
1087 final float[][] eOverNet;
1088 /** [layer][lpos][input] */
1089 float[][][] weightsIn;
1090 float[][][] weightsOut;
1091 int[][][] edgesIn;
1092 int[][][] edgesOut;
1093 final int[] transposeCounter;//??
1094 final int[] layerStart;//??
1095
1096 /**
1097 * List of command lines used to produce this network.
1098 * As long as the same version is being used this can replicate a network.
1099 */
1100 public ArrayList<String> commands;
1101
1102 long lastLinesWritten=0;
1103
1104 /*--------------------------------------------------------------*/
1105
1106 public static final boolean SPECIAL_FMA=true;//~20% faster when true, but needs ml.Cell class
1107 public static boolean NORMALIZE_BIAS=false;
1108 public static boolean NORMALIZE_WEIGHTS=false;
1109 public static float normalization_factor=0.5f;
1110 public static float normalization_shrink_rate=0.999f;
1111 public static boolean CONCISE=true;
1112 public static boolean DENSE=true;
1113 public static boolean OUT_HEX=false;
1114 public static boolean OUT_DENSE=false;
1115 public static boolean OUT_SPARSE=false;
1116 public static boolean verbose=false;
1117 public static final int version=1;
1118
1119 public static float PROB_FLAT=0.3f;
1120 public static float PROB_EXP=0.4f;
1121 public static float EXP_LAMDA=5f;
1122 public static float RAND_WEIGHT_CAP=2.0f;
1123
1124 static int compareCode=0;
1125 final static int compareWER=0, compareERR=1, compareFNR=2, compareFPR=3;
1126
1127 /*--------------------------------------------------------------*/
1128
1129 }