-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMultiSequence.cpp
644 lines (550 loc) · 17.4 KB
/
MultiSequence.cpp
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
/*
Author: Adriaan Tijsseling (AGT)
Copyright: (c) Copyright 2002-3 Adriaan Tijsseling. All rights reserved.
Description: Class implementing a training procedure for incremental learning of
multiple offline sequences. See MultiOffline.cpp for usage.
*/
#include "MultiSequence.h"
extern SequenceAPI* gSequenceAPI;
MultiSequence::MultiSequence( void )
{
mPatterns = NULL;
mContexts = NULL;
mCues = NULL;
mPatLabels = NULL;
mContextLabels = NULL;
mCueLabels = NULL;
mNumContexts = NULL;
mStats = new StatSpec[gSequenceAPI->SequenceGetNumFiles()];
}
MultiSequence::~MultiSequence()
{
if ( mPatterns != NULL ) DisposeMatrix( mPatterns, mNumPatterns );
if ( mContexts != NULL ) DisposeMatrix( mContexts, mTotalContexts );
if ( mCues != NULL ) DisposeMatrix( mCues, mNumCues );
if ( mPatLabels != NULL ) delete[] mPatLabels;
if ( mContextLabels != NULL ) delete[] mContextLabels;
if ( mCueLabels != NULL ) delete[] mCueLabels;
if ( mNumContexts != NULL ) delete[] mNumContexts;
if ( mStats != NULL ) delete[] mStats;
}
void MultiSequence::SetPatternsFile( char* filename )
{
strcpy( mPatternsFile, gSequenceAPI->SequenceGetDirectory() );
strcat( mPatternsFile, "/" );
strcat( mPatternsFile, filename );
}
void MultiSequence::SetContextsFile( char* filename )
{
strcpy( mContextsFile, gSequenceAPI->SequenceGetDirectory() );
strcat( mContextsFile, "/" );
strcat( mContextsFile, filename );
}
void MultiSequence::SetCuesFile( char* filename )
{
strcpy( mCuesFile, gSequenceAPI->SequenceGetDirectory() );
strcat( mCuesFile, "/" );
strcat( mCuesFile, filename );
}
// We may want to test recalls for partial context and pattern cues.
// For this we load three different files:
// a contexts file, a cues file and a pattern list file
// Note that the patterns, cues and contexts files have labels!
bool MultiSequence::LoadTestFiles( void )
{
ifstream infile;
int i;
int layerSize = gSequenceAPI->SequenceGetLayerSize();
// make sure working directory is correct
gSequenceAPI->SequenceDirectory( kOriginalDir );
// open the patterns file
infile.open( mPatternsFile );
if ( infile.fail() )
{
FileOpenError( mPatternsFile );
return false;
}
// read the number of patterns
SkipComments( &infile );
infile >> mNumPatterns;
// create the labels storage
mPatLabels = new char[mNumPatterns];
// create the storage matrix
mPatterns = CreateMatrix( 0.0, mNumPatterns, layerSize );
for ( i = 0; i < mNumPatterns; i++ )
{
SkipComments( &infile );
infile >> mPatLabels[i];
for ( int j = 0; j < layerSize; j++ )
{
SkipComments( &infile );
infile >> mPatterns[i][j];
}
}
infile.close();
// open the contexts file
infile.open( mContextsFile );
if ( infile.fail() )
{
FileOpenError( mContextsFile );
return false;
}
// read the number of patterns
SkipComments( &infile );
infile >> mTotalContexts;
// create the labels storage
mContextLabels = new char[mTotalContexts];
// create the storage matrix
mContexts = CreateMatrix( 0.0, mTotalContexts, layerSize );
for ( i = 0; i < mTotalContexts; i++ )
{
SkipComments( &infile );
infile >> mContextLabels[i];
for ( int j = 0; j < layerSize; j++ )
{
SkipComments( &infile );
infile >> mContexts[i][j];
}
}
infile.close();
// open the cues file
infile.open( mCuesFile );
if ( infile.fail() )
{
FileOpenError( mCuesFile );
return false;
}
// read the number of patterns
SkipComments( &infile );
infile >> mNumCues;
// create the labels storage
mCueLabels = new char[mNumCues];
// create the number of contexts indicator for each cue
mNumContexts = new int[mNumCues];
// create the storage matrix
mCues = CreateMatrix( 0.0, mNumCues, layerSize );
for ( i = 0; i < mNumCues; i++ )
{
SkipComments( &infile );
infile >> mCueLabels[i];
SkipComments( &infile );
infile >> mNumContexts[i];
for ( int j = 0; j < layerSize; j++ )
{
SkipComments( &infile );
infile >> mCues[i][j];
}
}
infile.close();
// move working directory back to log dir
gSequenceAPI->SequenceDirectory( kLogDir );
return true;
}
// Core routine for training multiple sequences
bool MultiSequence::RunMultiSequenceSimulation( void )
{
int seqErr; // any errors passed from API (currently nothing...)
data_type* errorDB;
int* array;
data_type recallError = 1.0, tmpErr = 1.0;
int i, j, ite, idx, epochCtr = 0;
bool done = false;
bool retVal = false;
int currentFileIdx = gSequenceAPI->SequenceGetFileIndex();
// buffer for recall errors
errorDB = new data_type[gSequenceAPI->SequenceGetNumFiles()];
for ( i = 0; i < gSequenceAPI->SequenceGetNumFiles(); i++ ) errorDB[i] = 1.0;
if ( gSequenceAPI->SequenceGetOrder() == kPermutedOrder ) // permuted order
{
array = new int[gSequenceAPI->SequenceGetNumFiles()]; // array for permuted patterns
for ( i = 0; i < gSequenceAPI->SequenceGetNumFiles(); i++ ) array[i] = i;
Permute( array, gSequenceAPI->SequenceGetNumFiles() ); // permute indices
cout << "order of sequence presentation will be:\t";
for ( int i = 0; i < gSequenceAPI->SequenceGetNumFiles(); i++ ) cout << array[i] << " ";
cout << endl;
}
// make sure stats data are initialized
ClearStats( gSequenceAPI->SequenceGetNumFiles() );
// specify simulation
cout << "\nTraining multiple sequences from patterns " << gSequenceAPI->SequenceGetBasename() << endl;
// set formatting for cout
AdjustStream( cout, 3, 7, kLeft, true );
while ( true )
{
// start training a set containing the first sequence, and then increment
for ( i = 0; i <= currentFileIdx; i++ )
{
// the sequence added is indicated differently
// based on permuted or linear presentation
if ( gSequenceAPI->SequenceGetOrder() == kPermutedOrder )
idx = array[i];
else
idx = i;
if ( gSequenceAPI->SequenceGetVerbosity() & O_MULTI ) cout << "\n\nSEQUENCE:\t" << idx; // update to log file
// load the patterns
seqErr = gSequenceAPI->SequenceLoadPatterns( idx );
if ( seqErr != kNoErr ) goto bail;
// set indicated sequence type. To use sequence type indicated in
// pattern file, pass '-1' to this function
gSequenceAPI->SequenceSetType();
// check if recall is ok
if ( gSequenceAPI->SequenceGetVerbosity() & O_MULTI ) cout << "\nRECALL: ";
switch ( gSequenceAPI->SequenceGetType() )
{
case O_NOISE:
case O_END:
// we recall twice to check for transients
RecallSequences( gSequenceAPI->SequenceNumPatterns()-1, &recallError );
if ( gSequenceAPI->SequenceGetVerbosity() & O_MULTI ) cout << endl;
RecallSequences( gSequenceAPI->SequenceNumPatterns()-1, &tmpErr );
if ( tmpErr < recallError ) recallError = tmpErr;
break;
case O_INF:
RecallSequences( gSequenceAPI->SequenceGetRecallLen(), &recallError );
break;
}
// add error to db
errorDB[i] = recallError;
mStats[i].sRecallCounter += 1;
mStats[i].sErrAverage += recallError;
// if the error is bad, train this pattern, otherwise check all recall errors
if ( errorDB[i] > gSequenceAPI->SequenceGetRecallCrit() )
{
if ( gSequenceAPI->SequenceGetVerbosity() & O_MULTI ) cout << "\nTRAINING: ";
TrainCurrentSequence( gSequenceAPI->SequenceGetIterations(), &ite );
mStats[i].sTrainCounter += 1;
mStats[i].sLRAverage += gSequenceAPI->SequenceGetAlpha();
mStats[i].sIteAverage += ite;
}
else
{
// check if all patterns have correct recall
done = true;
for ( j = 0; j <= currentFileIdx; j++ )
{
if ( errorDB[j] > gSequenceAPI->SequenceGetRecallCrit() )
{
done = false;
break;
}
}
// when done, add a new sequence or terminate. Else: just repeat
// also stop when #epochs > some criterion (set to 500). Latter value
// observed to be the number of epochs after which termination is unlikely
// to occur. We check if adding a new sequence will help learning
if ( done )
{
// prepare to move to the next sequence, if present
currentFileIdx += 1;
// write current stats
cout << endl;
PrintStats( currentFileIdx, epochCtr );
// if all sequences trained, bail out
if ( currentFileIdx >= gSequenceAPI->SequenceGetNumFiles() )
{
retVal = true;
goto bail;
}
// otherwise add a new sequence
cout << "\n___ ADDING SEQUENCE ";
if ( gSequenceAPI->SequenceGetOrder() == kPermutedOrder )
cout << array[currentFileIdx]+1 << " ___";
else
cout << currentFileIdx << " ___";
epochCtr = 0;
ClearStats( gSequenceAPI->SequenceGetNumFiles() );
}
}
// each time we're back at the initial sequence, it is recorded as an epoch
if ( i == 0 ) epochCtr += 1;
}
if ( epochCtr > gSequenceAPI->SequenceGetEpochs() )
{
cout << endl;
PrintStats( currentFileIdx, epochCtr ); // write current stats
retVal = true;
goto bail;
}
}
bail:
// clean up the mess
delete[] errorDB;
if ( gSequenceAPI->SequenceGetOrder() == kPermutedOrder ) delete[] array;
if ( epochCtr > gSequenceAPI->SequenceGetEpochs() )
{
cout << "\nNumber of epochs exceeded\n" << endl;
return false;
}
else return retVal;
}
void MultiSequence::TrainCurrentSequence( int num_iterations, int *final_ite )
{
int ite;
// Train the sequence
for ( ite = 0; ite < num_iterations; ite++ )
{
// train single pass through sequence
gSequenceAPI->SequenceTrainFile();
// check on lr and err
// the lr is the average over all patterns (see SequenceTrainFile)
if ( gSequenceAPI->SequenceGetVerbosity() & O_MULTI )
{
AdjustStream( cout, 2, 5, kLeft, true );
cout << gSequenceAPI->SequenceGetAlpha() << " ";
AdjustStream( cout, 0, 1, kLeft, true );
}
if ( gSequenceAPI->SequenceGetAlpha() <= gSequenceAPI->SequenceGetAlphaCrit() ) /* && gSequenceAPI->SequenceGetError() <= gSequenceAPI->SequenceGetErrCrit() */
break;
}
if ( gSequenceAPI->SequenceGetVerbosity() & O_MULTI ) cout << "\nfinished at " << ite << " iterations" << endl;
*final_ite = ite;
}
void MultiSequence::RecallSequences( int num_iterations, data_type *recall_error )
{
int i;
int newState = -1;
data_type err = 0.0;
gSequenceAPI->SequenceClearErr(); // clear mErrs and mFreq from gPatterns
// obtain the first pattern in the sequence
gSequenceAPI->SequenceGetInput( 0 );
// Set the context
gSequenceAPI->SequenceSetContext( kOffline );
// Observe the frequency distribution of correctly recalled sequences
SequenceErrors( 0 ); // reset state information
// loop for a while...
for ( i = 0; i < num_iterations; i++ )
{
gSequenceAPI->SequenceRecall();
if ( gSequenceAPI->SequenceGetType() == O_INF )
{
newState = SequenceErrors( 1 );
if ( newState != -1 ) gSequenceAPI->SequenceSetFreq( newState );
}
else
{
gSequenceAPI->SequenceSetErr( i+1 );
if ( gSequenceAPI->SequenceGetErr( i+1 ) < 0.2 ) gSequenceAPI->SequenceSetFreq( i+1 );
}
}
// average and scale errors
if ( gSequenceAPI->SequenceGetType() == O_INF )
{
data_type avg = 0.0;
data_type scale = (data_type)num_iterations;
scale = scale / (data_type)(gSequenceAPI->SequenceNumPatterns());
for ( i = 0; i < gSequenceAPI->SequenceNumPatterns(); i++ )
{
avg = (data_type)(gSequenceAPI->SequenceGetFreq(i))/scale - 1.0;
err += ( avg * avg );
}
err = sqrt( err )/(data_type)(gSequenceAPI->SequenceNumPatterns());
}
else
{
for ( i = 1; i < gSequenceAPI->SequenceNumPatterns(); i++ )
{
err += gSequenceAPI->SequenceGetErr(i);
if ( gSequenceAPI->SequenceGetVerbosity() & O_MULTI ) cout << " " << gSequenceAPI->SequenceGetErr(i) << " ";
}
err = err/(data_type)(gSequenceAPI->SequenceNumPatterns()-1);
}
if ( gSequenceAPI->SequenceGetVerbosity() & O_MULTI )
{
AdjustStream( cout, 4, 6, kLeft, true );
cout << err << " ";
AdjustStream( cout, 0, 1, kLeft, true );
for ( i = 0; i < gSequenceAPI->SequenceNumPatterns(); i++ ) cout << gSequenceAPI->SequenceGetFreq(i) << " ";
}
*recall_error = err;
}
// display recall frequency distribution
int MultiSequence::SequenceErrors( int noReset )
{
static int first_state = 0;
static int prev_state = 0;
if ( noReset == 0 )
{
first_state = 0;
prev_state = 0;
return 0;
}
int idx = 0;
bool display = 0;
if ( display ) cout << endl;
for ( int i = 0; i < gSequenceAPI->SequenceNumPatterns(); i++ )
{
gSequenceAPI->SequenceSetErr( i );
if ( gSequenceAPI->SequenceGetErr(i) <= gSequenceAPI->SequenceGetErr(idx) ) idx = i;
}
if ( gSequenceAPI->SequenceGetErr( idx ) < 0.4 ) // 0.4 criterion arbitrary.
{
prev_state = idx;
if ( display )
{
AdjustStream( cout, 0, 3, kLeft, true );
cout << idx+1 << " ";
AdjustStream( cout, 0, 5, kLeft, true );
cout << gSequenceAPI->SequenceGetErr(idx);
SetStreamDefaults( cout );
}
if ( first_state == 0 ) first_state = 1;
return idx;
}
else
{
if ( first_state == 1 )
{
if ( display )
{
AdjustStream( cout, 0, 3, kLeft, true );
cout << prev_state+1 << " ";
AdjustStream( cout, 0, 5, kLeft, true );
cout << gSequenceAPI->SequenceGetErr(idx);
SetStreamDefaults( cout );
}
return prev_state;
}
else
{
if ( display )
{
AdjustStream( cout, 0, 3, kLeft, true );
cout << -1 << " " << 100.0;
SetStreamDefaults( cout );
}
return -1;
}
}
return idx;
}
void MultiSequence::ClearStats( int num )
{
for ( int i = 0; i < num; i++ )
{
mStats[i].sTrainCounter = 0;
mStats[i].sRecallCounter = 0;
mStats[i].sIteAverage = 0.0;
mStats[i].sErrAverage = 0.0;
mStats[i].sLRAverage = 0.0;
}
}
void MultiSequence::PrintStats( int patIdx, int epochCtr )
{
cout << "\ncurrent stats up to " << patIdx << " sequence";
if ( patIdx > 1 ) cout << "s";
cout << endl;
cout << "number of epochs: " << epochCtr << endl;
// % max epoch calculation
cerr << epochCtr << "\t" << patIdx << "\t";
for ( int i = 0; i < patIdx; i++ )
{
// print the % epochs
if ( mStats[i].sTrainCounter != 0 )
cerr << (((data_type)mStats[i].sTrainCounter/(data_type)epochCtr) * 100.0) << "\t";
else
cerr << 0 << "\t";
// log entries
cout << "sequence: " << i << endl;
cout << "number of recall trials:\t";
AdjustStream( cout, 0, 3, kLeft, true );
cout << mStats[i].sRecallCounter << endl;
SetStreamDefaults( cout );
cout << "average recall error:\t";
AdjustStream( cout, 3, 6, kLeft, true );
cout << ( mStats[i].sErrAverage / mStats[i].sRecallCounter ) << endl;
SetStreamDefaults( cout );
cout << "number of training trials:\t";
AdjustStream( cout, 0, 3, kLeft, true );
cout << mStats[i].sTrainCounter << endl;
SetStreamDefaults( cout );
cout << "average iterations trained:\t";
AdjustStream( cout, 3, 6, kLeft, true );
cout << ( mStats[i].sIteAverage / mStats[i].sTrainCounter ) << endl;
SetStreamDefaults( cout );
cout << "average learning rate:\t";
AdjustStream( cout, 3, 6, kLeft, true );
cout << ( mStats[i].sLRAverage / mStats[i].sTrainCounter ) << endl;
SetStreamDefaults( cout );
}
cout << endl;
cerr << endl;
}
// test recalls for each cue in mCues and each context in mContexts
// compare output with patterns specified in mPatterns
void MultiSequence::TestRecall( int cur_run )
{
data_type sum, err, act1, act2;
int i, j, k, idx, run, layerSize = gSequenceAPI->SequenceGetLayerSize();
int startCtxt, endCtxt;
ofstream orbfile;
char orbname[256];
char basename[256];
char stridx[5];
sprintf( stridx, "%d", cur_run );
strcpy( basename, gSequenceAPI->SequenceGetDirectory() );
strcat( basename, "/" );
strcat( basename, "orb" );
strcat( basename, stridx );
strcat( basename, "-ctx" );
// loop for each context and each cue
for ( k = 0; k < mNumCues; k++ )
{
if ( k == 0 )
startCtxt = 0;
else
startCtxt = mNumContexts[k-1];
endCtxt = startCtxt + mNumContexts[k];
for ( j = startCtxt; j < endCtxt; j++ )
{
// clean activations and coincidence detector activations
// gSequenceAPI->SequenceReset( O_CD | O_ACT );
cout << "\nRecall with context \'" << mContextLabels[j];
cout << "\' and cue \'" << mCueLabels[k] << "\'\n";
strcpy( orbname, basename );
sprintf( (char*)stridx, "%d", j+1 );
strcat( (char*)orbname, stridx );
strcat( (char*)orbname, "cue" );
sprintf( (char*)stridx, "%d", k+1 );
strcat( (char*)orbname, stridx );
orbfile.open( orbname );
run = 0;
redo:
run++;
// set context and cue
for ( i = 0; i < layerSize; i++ )
gSequenceAPI->SequenceSetContext( i, mContexts[j][i] );
gSequenceAPI->SequenceSetContext( kOnline );
for ( i = 0; i < layerSize; i++ )
gSequenceAPI->SequenceSetInput( i, mCues[k][i] );
// recall for a while...
sum = 0.0;
AdjustStream( cout, 3, 6, kLeft, true );
for ( i = 0; i < gSequenceAPI->SequenceGetRecallLen(); i++ )
{
gSequenceAPI->SequenceRecall();
err = gSequenceAPI->SequenceCompareOutput( mPatterns, mNumPatterns, &idx );
sum += err;
if ( idx != -1 )
cout << " " << mPatLabels[idx] << " ";
else
cout << " - ";
cout << err << endl;
if ( i == 0 )
act2 = gSequenceAPI->SequenceData( kModuleHidden );
else
{
act1 = act2;
act2 = gSequenceAPI->SequenceData( kModuleHidden );
orbfile << act1 << "\t" << act2 << endl;
}
}
cout << "Average error: " << sum/gSequenceAPI->SequenceGetRecallLen() << endl;
orbfile << endl;
// for terminating sequences we run this a second time to get rid
// of residual activations from past sequences
if ( run == 1 && gSequenceAPI->SequenceGetOverrideType() != O_INF ) goto redo;
orbfile.close();
}
cout << endl;
}
}