-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBBHMPerceptron.m
355 lines (295 loc) · 11.3 KB
/
BBHMPerceptron.m
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
/**********************************************************************
This source file belongs to the seqlearning library: a sequence learning objective-c library.
Copyright (C) 2008 Roberto Esposito
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***********************************************************************/
//
// BBHMPerceptron.m
// SeqLearning
//
// Created by Roberto Esposito on 21/7/06.
// Copyright 2006 __MyCompanyName__. All rights reserved.
//
#import <SeqLearning/BBHMPerceptron.h>
#import <SeqLearning/BBViterbiClassifier.h>
#import <SeqLearning/BBCarpeDiemClassifier.h>
#import <SeqLearning/BBFeature.h>
#import <SeqLearning/BBMutableDouble.h>
NSString* BBHMPerceptronFinishedIterationNotification = @"BBHMPerceptronFinishedIterationNotification";
NSString* BBHMPerceptronFinishedSequenceNotification = @"BBHMPerceptronFinishedSequenceNotification";
NSString* BBHMPerceptronStartedSequenceNotification = @"BBHMPerceptronStartedSequenceNotification";
NSString* BBHMPerceptronNumberOfIterationsOption = @"Number of Iterations";
NSString* BBHMPerceptronViterbiClassifierClassOption = @"Viterbi Classifier";
NSString* BBHMPerceptronUseAveragingParametersOption = @"Use Averaging Parameters";
NSString* BBHMPerceptronViterbiBeamSizeOption = @"Beam size (if applicable)";
NSString* BBHMPerceptronErrorEvaluatorClassOption = @"Error evaluator class name";
#define SAVE_DEBUG_DATA 0
#if SAVE_DEBUG_DATA
// TO BE DELETED
static int tot_chances_for_update = 0;
static int num_sequence = 0;
static int num_iteration = 0;
int counters[255];
FILE* files[255];
//
#endif
@implementation BBHMPerceptron
-(id) init {
if( (self=[super init]) ) {
[_options setObject: [NSNumber numberWithInt:5]
forKey:BBHMPerceptronNumberOfIterationsOption];
[_options setObject: @"BBCarpeDiemClassifier"
forKey:BBHMPerceptronViterbiClassifierClassOption];
[_options setObject: @"YES"
forKey:BBHMPerceptronUseAveragingParametersOption];
[_options setObject: [NSNumber numberWithDouble:0.2]
forKey: BBHMPerceptronViterbiBeamSizeOption];
[_options setObject: @"BBErrorEvaluator" forKey:BBHMPerceptronErrorEvaluatorClassOption];
}
return self;
}
-(NSString*) fileNameForFeature:(BBFeature*) feature {
static int feature_no = 0;
NSDictionary* parameters = [feature parameters];
NSEnumerator* keys = [parameters keyEnumerator];
NSString* key;
NSMutableString* featureDes = [NSMutableString stringWithString:@"/Users/esposito/tmp/experiments/data/"];
[featureDes appendString:[feature className]];
while( (key = [keys nextObject]) ) {
if( [parameters objectForKey:key] == nil )
[featureDes appendFormat:@"_%@_", key];
else
[featureDes appendFormat:@"_%@_%@", key, [parameters objectForKey:key]];
}
[featureDes appendFormat:@"_%d", ++feature_no];
return featureDes;
}
-(void) incrementAssertedFeaturesOnSequence:(BBSequence*) sequence andTime:(unsigned int) t by:(int) incr {
int feature_count=[_features count];
int i;
for(i=0; i<feature_count; ++i) {
@try {
if( [(BBFeature*)[_features objectAtIndex:i] evalOnSequence:sequence forTime:t] ) {
[[_weights objectAtIndex:i] setDouble:[[_weights objectAtIndex:i] doubleValue]+incr];
#if SAVE_DEBUG_DATA
// // TO BE DELETED
counters[i]++;
fprintf(files[i],
"%d %d %d %d %d\n",
tot_chances_for_update,
counters[i],
num_sequence,
num_iteration,
(int) [[_weights objectAtIndex:i] doubleValue]);
//
#endif
}
} @catch (NSException* exception) {
@throw [NSException exceptionWithName:[exception name]
reason:[NSString stringWithFormat:@"Error analyzing testing feature number:%d at time:%d reason:%@",
i, t, [exception reason]]
userInfo:[exception userInfo]];
}
}
}
-(void) trainClassifier:(BBViterbiClassifier*) classifier
onSequence:(BBSequence*) sequence
targetLabeling:(NSArray*) sequence_labels {
NSArray* predicted_labels = [classifier labelsForSequence:sequence];
int T=[sequence length];
int t;
for(t=0; t<T; ++t) {
@try {
#if SAVE_DEBUG_DATA
// TO BE DELETED
++tot_chances_for_update;
//
#endif
if([_errorEvaluator prediction: [predicted_labels objectAtIndex:t]
differsFrom: [sequence_labels objectAtIndex:t]]) {
// if(![[predicted_labels objectAtIndex:t] isEqual:[sequence_labels objectAtIndex:t]]) {
// **** wrong classification ***
// first we decrement each feature asserted for the incorrect label
[sequence setLabel:[predicted_labels objectAtIndex:t] forTime:t];
[self incrementAssertedFeaturesOnSequence: sequence andTime:t by:-1];
// then we restore the correct label
[sequence clearLabelAtTime: t];
// and increment each feature asserted for the correct label
[self incrementAssertedFeaturesOnSequence: sequence andTime:t by:1];
}
} @catch (id exception) {
// Debugger();
NSLog(@"Exception catched during -trainClassifier, reason:%@", [exception reason]);
@throw;
}
}
}
-(void) copyWeightsIntoVector:(double*) vector {
int i;
int weights_count = [_weights count];
for(i=0; i<weights_count; ++i) {
vector[i] = [[_weights objectAtIndex:i] doubleValue];
}
}
-(void) updateWeightsAccordingToWeightsHistory:(double**) weightsHistory
numIterations:(int) num_iterations {
int i,n;
int weights_count = [_weights count];
for(i=0; i<weights_count; ++i) {
double cur_average = 0;
for(n=0; n<num_iterations; ++n) {
cur_average+=weightsHistory[n][i];
}
[[_weights objectAtIndex:i] setDouble:cur_average/num_iterations];
}
}
-(NSObject<BBSequenceClassifying>*) learn:(BBSeqSet*) ss {
NSAssert( _features!=nil,
@"Cannot learn without using any feature" );
#if SAVE_DEBUG_DATA
// TO BE DELETED
int f;
for(f=0; f<[_features count]; ++f) {
counters[f]=0;
files[f] = fopen( [[self fileNameForFeature:[_features objectAtIndex:f]] cString], "w" );
if( files[f]==NULL ) {
NSAssert(FALSE, @"should not be reached!");
@throw [NSException exceptionWithName:@"FileOpenError"
reason:[NSString stringWithFormat:@"Cannot open file named:%@", [_features objectAtIndex:f]]
userInfo:nil];
}
else {
fprintf(files[f],"# tot_potential_updates tot_updates seq_num iteration weight\n0 0 0 0 0\n");
}
}
//
#endif
int num_repetitions =
[[[self options] objectForKey:BBHMPerceptronNumberOfIterationsOption] intValue];
BOOL useAveragingParameters =
[[[self options] objectForKey:BBHMPerceptronUseAveragingParametersOption] isEqualToString:@"YES"];
double** weightsHistory;
if( useAveragingParameters )
weightsHistory = (double**) calloc( num_repetitions, sizeof(double*) );
unsigned int features_count = [_features count];
_weights = [NSMutableArray arrayWithCapacity:features_count];
int i;
for(i=0; i<features_count; ++i) {
[_weights addObject:[BBMutableDouble numberWithDouble:0.0]];
}
Class errorEvaluatorClass = NSClassFromString([_options objectForKey:BBHMPerceptronErrorEvaluatorClassOption]);
_errorEvaluator = [[[errorEvaluatorClass alloc] init] autorelease];
Class classifierClass = NSClassFromString([_options objectForKey:BBHMPerceptronViterbiClassifierClassOption]);
BBViterbiClassifier* classifier = [[[classifierClass alloc] init] autorelease];
if( [classifier respondsToSelector: @selector(setBeamSizeUsingNSNumber:)] ) {
[classifier performSelector:@selector(setBeamSize:) withObject:[_options objectForKey:BBHMPerceptronViterbiBeamSizeOption] ];
}
[classifier setFeaturesManager:_featuresManager];
[classifier setFeatures:_features];
[classifier setWeights:_weights];
_correct_labels = [[NSMutableArray alloc] initWithCapacity:[ss count]];
int seq_num;
for(seq_num=0; seq_num<[ss count]; ++seq_num) {
[_correct_labels addObject:[[ss sequenceNumber:seq_num] labels]];
}
int num;
for(num=0; num<num_repetitions; ++num) {
#if SAVE_DEBUG_DATA
// TO BE DELETED
num_iteration = num;
//
#endif
NSEnumerator* sequenceEnumerator = [ss sequenceEnumerator];
BBSequence* sequence;
seq_num=0;
while( (sequence=[sequenceEnumerator nextObject]) ) {
#if SAVE_DEBUG_DATA
// TO BE DELETED
num_sequence = seq_num;
//
#endif
NSAutoreleasePool* autoreleasePool = [[NSAutoreleasePool alloc] init];
[[NSNotificationCenter defaultCenter] postNotificationName:BBHMPerceptronStartedSequenceNotification
object:self
userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:seq_num+1],@"number",
classifier, @"classifier",
NULL]];
@try {
[self trainClassifier:classifier
onSequence:sequence
targetLabeling:[_correct_labels objectAtIndex:seq_num]];
} @catch (NSException* exception) {
if(useAveragingParameters) {
// thrashing partially allocated vectors
int i;
for(i=0; i<num; ++i) {
free(weightsHistory[i]);
}
free(weightsHistory);
}
// rethrowing the exception
@throw [NSException exceptionWithName:[exception name]
reason:[NSString stringWithFormat:@"Error analyzing sequence number %d, reason:%@",
seq_num, [exception reason]]
userInfo:[exception userInfo]];
}
[[NSNotificationCenter defaultCenter] postNotificationName:BBHMPerceptronFinishedSequenceNotification
object:self
userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:seq_num+1],@"number",
classifier, @"classifier",
NULL]];
[autoreleasePool release];
++seq_num;
}
// storing actual contents of the weights vector
if(useAveragingParameters) {
weightsHistory[num] = (double*) malloc( sizeof(double) * [_weights count] );
[self copyWeightsIntoVector:weightsHistory[num]];
}
[[NSNotificationCenter defaultCenter] postNotificationName:BBHMPerceptronFinishedIterationNotification
object:self
userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:num+1],@"number",
classifier, @"classifier",
NULL]];
}
if(useAveragingParameters) {
[self updateWeightsAccordingToWeightsHistory:weightsHistory
numIterations:num_repetitions];
int i;
for(i=0; i<num_repetitions; ++i) {
free(weightsHistory[i]);
}
free(weightsHistory);
}
// cleaning up
[_correct_labels release];
_weights=nil;
_errorEvaluator = nil;
#if SAVE_DEBUG_DATA
// TO BE DELETED
for(f=0; f<[_features count]; ++f) {
fclose( files[f] );
}
#endif
return classifier;
}
-(void) setFeaturesManager:(BBFeaturesManager *)featuresManager {
[_featuresManager autorelease];
_featuresManager = [featuresManager retain];
}
-(BBFeaturesManager*) featuresManager {
return _featuresManager;
}
@end