blib/lib/Algorithm/Viterbi.pm untested

filter: Statementstmt 0.0% 0 / 111 Branchbran 0.0% 0 / 22 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 0.0% 0 / 11 Podpod 0.0% 0 / 8 totaltotal 0.0% 0 / 152 CC 12 SCAR 22.5
CC
12
Cov
0%
get_emission
20.0
new
12.0
forward_viterbi
12.0
CRAP 9.5
1 #Algorithm::Viterbi
2 #Copyright (c) 2006 Koen Dejonghe. All rights reserved.
3 #This program is free software; you can redistribute it and/or
4 #modify it under the same terms as Perl itself.
5 package Algorithm::Viterbi;
6
7 use vars qw/$VERSION/;
8 $VERSION = '0.01';
9
10 =head1 NAME
11
12 Algorithm::Viterbi - Compute Viterbi path and probability
13
14 =head1 SYNOPSIS
15
16 use Algorithm::Viterbi;
17
18 my $start_probability = { 'Rainy'=> 0.6, 'Sunny'=> 0.4 };
19
20 my $transition_probability = {
21 'Rainy' => {'Rainy'=> 0.7, 'Sunny'=> 0.3},
22 'Sunny' => {'Rainy'=> 0.4, 'Sunny'=> 0.6},
23 };
24
25 my $emission = {
26 'shop' => { 'Sunny' => '0.3', 'Rainy' => '0.4' },
27 'walk' => { 'Sunny' => '0.6', 'Rainy' => '0.1' },
28 'clean' => { 'Sunny' => '0.1', 'Rainy' => '0.5' }
29 };
30
31 my $v = Algorithm::Viterbi->new();
32 $v->start($start_probability);
33 $v->transition($transition_probability);
34 $v->emission($emission_probability);
35
36 my $observations = [ 'walk', 'shop', 'clean' ];
37
38 my ($prob, $v_path, $v_prob) = $v->forward_viterbi($observations);
39
40 -- or --
41
42 my $training_data = [
43 [ 'walk', 'Sunny' ],
44 [ 'walk', 'Sunny' ],
45 [ 'walk', 'Rainy' ],
46 [ 'shop', 'Rainy' ],
47 [ 'clean', 'Rainy' ],
48 [ 'clean', 'Rainy' ],
49 ...
50 ];
51
52 $v->train($training_data);
53 my ($prob, $v_path, $v_prob) = $v->forward_viterbi($observations);
54
55 =head1 DESCRIPTION
56
57 Algorithm::Viterbi computes the forward probability, the Viterbi path
58 and the Viterbi probability of a sequence of observations, based on
59 a given start, emission and transition probability.
60 Alternatively, the start, emission and transition probability can be
61 computed from a set of training data.
62
63 The whole idea of this module is inspired by an article on the Viterbi
64 algorithm in Wikipedia, the free encyclopedia. Rather than copying all
65 text, I'm just including the link to the Wikipedia page:
66 L<http://en.wikipedia.org/wiki/Viterbi_algorithm>.
67 I think the page is well-written and I see no need to repeat the theory
68 here. Reading it may clarify the documentation below.
69
70 =cut
71
72 use strict;
73 use warnings;
74
75 =head1 METHODS
76
77 =over 8
78
79 =item new
80
81 Creates a new C<Algorithm::Viterbi> object.
82 The following attributes can be set with the constructor:
83
84 my $v = Algorthm::Viterbi->new(
85 start_state => '$',
86 unknown_emission_prob => undef,
87 unknown_transition_prob => 0);
88
89 The values of the attributes in the example are the default values.
90 For a detailed description and use of these attributes, see below.
91
92 =cut
93
94 sub new
95 {
96 my $class = shift;
97 my $self = {@_};
98 bless $self, $class;
99
100 $self->{unknown_transition_prob} = 0 if (!defined($self->{unknown_transition_prob}));
101 $self->{start_state} = '$' if (!defined($self->{start_state}));
102
103 return $self;
104 }
105
106 =item train
107
108 This method computes the start, emission and transition probabilities
109 from a set of observations and their associated states.
110 The probabilities are simple averages of the passed observations,
111 so if you require sophisticated smoothing on the emission, start and/or
112 transition, then you're better off rolling your own.
113
114 The value of member start_state is a bogus state used to define the begin state of the first transition.
115 By default, this state is set to '$'. You can change this by setting the variable in the constructor
116 or later by accessing the member directly. See example below.
117
118 This state can also be used as a separator between the beginning and end of a sequence of observations.
119 For example, you could assign this state (tag) to every end-of-sentence symbol when training on a
120 pre-tagged corpus.
121
122 The set of observations is passed as a reference to an array as shown in the following example:
123
124 use strict;
125 use Algorithm::Viterbi;
126 use Data::Dumper;
127
128 my $observations = [
129 [ 'work', 'rainy' ],
130 [ 'work', 'sunny' ],
131 [ 'walk', 'sunny' ],
132 [ 'walk', 'rainy' ],
133 [ 'shop', 'rainy' ],
134 [ 'work', 'rainy' ],
135 ];
136
137 my $v = Algorithm::Viterbi->new(start_state => '###');
138 $v->train($observations);
139
140 print Dumper($v);
141
142 will produce:
143
144 $VAR1 = bless( {
145 'transition' => {
146 'sunny' => {
147 'sunny' => '0.5',
148 'rainy' => '0.25'
149 },
150 'rainy' => {
151 'sunny' => '0.5',
152 'rainy' => '0.5'
153 },
154 '###' => {
155 'rainy' => '0.25'
156 }
157 },
158 'emission' => {
159 'shop' => {
160 'rainy' => '0.25'
161 },
162 'walk' => {
163 'sunny' => '0.5',
164 'rainy' => '0.25'
165 },
166 'work' => {
167 'sunny' => '0.5',
168 'rainy' => '0.5'
169 }
170 },
171 'start_state' => '###',
172 'states' => [
173 'sunny',
174 'rainy'
175 ],
176 'unknown_transition_prob' => 0,
177 'start' => {
178 'sunny' => '0.333333333333333',
179 'rainy' => '0.666666666666667'
180 }
181 }, 'Algorithm::Viterbi' );
182
183 =cut
184
185 sub train
186 {
187 my ($self, $training_data) = @_;
188
189 my $ep = {};
190 my $tp = {};
191 my $sp = {};
192
193 my $pt = $self->{start_state};
194
195 foreach my $o(@$training_data){
196 my ($a, $t) = @$o;
197 $ep->{$a}{$t}++;
198 $tp->{$pt}{$t}++;
199 $pt = $t;
200 $sp->{$t}++;
201 }
202
203 #emission
204 foreach my $a(keys %$ep){
205 foreach my $t(keys %{$ep->{$a}}){
206 $ep->{$a}{$t} /= $sp->{$t};
207 }
208 }
209
210 #transition
211 foreach my $pt(keys %$tp){
212 foreach my $t(keys %{$tp->{$pt}}){
213 $tp->{$pt}{$t} /= $sp->{$t};
214 }
215 }
216
217 #start
218 foreach my $t(keys %$sp){
219 $sp->{$t} /= @$training_data;
220 }
221
222 $self->start($sp);
223 $self->emission($ep);
224 $self->transition($tp);
225
226 return ($sp, $ep, $tp);
227 }
228
229 =item start
230
231 Initializes the start probabilities.
232 The start probabilities are passed as a reference to a hash, as shown in
233 this example:
234
235 my $start_probability = { 'Rainy'=> 0.6, 'Sunny'=> 0.4 };
236 my $v = Algorithm::Viterbi->new();
237 $v->start($start_probability);
238
239 From the start probabilities, all possible states are derived, by
240 copying the keys of the start hash. This list of states is used by the
241 forward_viterbi method. It is therefore important to mention all
242 possible states in the start hash.
243
244 Returns the start probabilities.
245
246 =cut
247
248 sub start
249 {
250 my $self = shift;
251 if (@_){
252 ($self->{start}) = @_;
253 @{$self->{states}} = keys %{$self->{start}};
254 }
255 return $self->{start};
256 }
257
258 =item emission
259
260 Initializes the emission probabilities.
261 The emission is passed as a reference to a hash, as shown in
262 this example:
263
264 my $emission_probability = {
265 'shop' => { 'Sunny' => '0.3', 'Rainy' => '0.4' },
266 'swim' => { 'Sunny' => '0.1' },
267 'walk' => { 'Sunny' => '0.5', 'Rainy' => '0.1' },
268 'clean' => { 'Sunny' => '0.1', 'Rainy' => '0.5' }
269 };
270 my $v = Algorithm::Viterbi->new();
271 $v->emission($emission_probability);
272
273 The keys of the emission hash constitute the dictionary, which is used to determine
274 whether an observation is a known or an unknown observation.
275
276 Returns the emission probabilities.
277
278 =cut
279
280 sub emission
281 {
282 my $self = shift;
283 ($self->{emission}) = @_ if (@_);
284 return $self->{emission};
285 }
286
287 =item transition
288
289 Initializes the transition probabilities.
290 The transition is passed as a reference to a hash, as shown in
291 this example:
292
293 my $transition_probability = {
294 'Rainy' => {'Rainy'=> 0.7, 'Sunny'=> 0.3},
295 'Sunny' => {'Rainy'=> 0.4, 'Sunny'=> 0.6},
296 };
297 my $v = Algorithm::Viterbi->new();
298 $v->transition($transition_probability);
299
300 The transition hash can be 'sparse': it is sufficient to include only known
301 transitions between states. See method get_transition.
302
303 Returns the transition probabilities.
304
305 =cut
306
307 sub transition
308 {
309 my $self = shift;
310 ($self->{transition}) = @_ if (@_);
311 return $self->{transition};
312 }
313
314 =item forward_viterbi
315
316 This method calculates the forward probability, the Viterbi path
317 and the Viterbi probability of a given sequence of observations.
318 For a detailed description of the Algorithm, see the Wikipedia page
319 L<http://en.wikipedia.org/wiki/Viterbi_algorithm>.
320
321 The difference with the algorithm described in the web page above,
322 is that the emission and the transition are calculated somewhat
323 differently. See methods get_emission and get_transition.
324
325 Example:
326
327 use strict;
328 use Algorithm::Viterbi;
329 use Data::Dumper;
330
331
332 my $observations = [ 'walk', 'shop', 'clean' ];
333 my $start = { 'Rainy'=> 0.6, 'Sunny'=> 0.4 };
334 my $transition = {
335 'Rainy' => {'Rainy'=> 0.7, 'Sunny'=> 0.3},
336 'Sunny' => {'Rainy'=> 0.4, 'Sunny'=> 0.6},
337 };
338
339 my $emission = {
340 'shop' => {
341 'Sunny' => '0.3',
342 'Rainy' => '0.4',
343 },
344
345 'walk' => {
346 'Sunny' => '0.6',
347 'Rainy' => '0.1'
348 },
349 'clean' => {
350 'Sunny' => '0.1',
351 'Rainy' => '0.5'
352 }
353 };
354
355 my $v = Algorithm::Viterbi->new();
356 $v->emission($emission);
357 $v->transition($transition);
358 $v->start($start);
359
360 print Dumper ($v->forward_viterbi($observations));
361
362 produces:
363
364 $VAR1 = '0.033612';
365 $VAR2 = [
366 'Sunny',
367 'Rainy',
368 'Rainy',
369 'Rainy'
370 ];
371 $VAR3 = '0.009408';
372
373 =cut
374
375 sub forward_viterbi
376 {
377 my ($self, $observation) = @_;
378
379 my $T = { };
380 foreach my $state (@{$self->{states}}) {
381 ## prob. V. path V. prob.
382 $T->{$state} = [ $self->{start}{$state}, [$state], $self->{start}{$state} ];
383 }
384
385 foreach my $output (@$observation) {
386 my $U = { };
387 foreach my $next_state (@{$self->{states}}) {
388 my $total = 0;
389 my $argmax = [ ];
390 my $valmax = 0;
391 foreach my $state (@{$self->{states}}) {
392 my ($prob, $v_path, $v_prob) = @{$T->{$state}};
393
394 my $e = $self->get_emission($output, $state);
395 my $t = $self->get_transition($state, $next_state);
396
397 my $p = $e * $t;
398 $prob *= $p;
399 $v_prob *= $p;
400 $total += $prob;
401
402 if ($v_prob > $valmax) {
403 $argmax = [ @$v_path, $next_state ];
404 $valmax = $v_prob;
405 }
406 }
407 $U->{$next_state} = [ $total, $argmax, $valmax ];
408 }
409 $T = $U;
410 }
411
412 ## apply sum/max to the final states
413 my $total = 0;
414 my $argmax = [];
415 my $valmax = 0;
416 foreach my $state (@{$self->{states}}) {
417 my ($prob, $v_path, $v_prob) = @{$T->{$state}};
418 $total += $prob;
419 if ($v_prob > $valmax) {
420 $argmax = $v_path;
421 $valmax = $v_prob;
422 }
423 }
424 return ($total, $argmax, $valmax);
425 }
426
427 =item get_emission
428
429 Usage: $v->get_emission($observation, $state);
430
431 Returns the emission probability for a given observation and state.
432 This method is primarily for internal usage and is called
433 by the forward_viterbi method.
434
435 The dictionary consists of the keys of the emission table, e.g. a list
436 of known observations.
437
438 If $observation is a known observation in the dictionary and $state
439 exists as a state for the observation in the emission table, then return
440 the probability associated with $observation and $state.
441
442 If the observation exists in the dictionary, but $state is a state not
443 connected to the observation, then return 0.
444
445 If the observation does not exist in the dictionary and $v->{unknown_emission_prob}
446 is defined, then return $v->{unknown_emission_prob}.
447 Setting $v->{unknown_emission_prob} = 1 actually means that you are returning all
448 possible states for an unknown observation.
449
450 If the observation is unknown in the dictionary and $v->{unknown_emission_prob}
451 is not defined, then return the start probability of $state.
452
453 Example:
454
455 my $emission = {
456 'shop' => {
457 'Sunny' => '0.3',
458 'Rainy' => '0.4'
459 },
460 'swim' => {
461 'Sunny' => '0.1'
462 },
463 'walk' => {
464 'Sunny' => '0.5',
465 'Rainy' => '0.1'
466 },
467 'clean' => {
468 'Sunny' => '0.1',
469 'Rainy' => '0.5'
470 }
471 };
472
473 my $start = { 'Rainy'=> 0.6, 'Sunny'=> 0.4 };
474
475 my $v = Algorithm::Viterbi->new();
476 $v->emission($emission);
477 $v->start($start);
478 my $e;
479 $e = get_emission('shop', 'Rainy'); # $e = 0.4
480 $e = get_emission('swim', 'Rainy'); # $e = 0
481 $e = get_emission('hack', 'Rainy'); # $e = 0.6
482 $v->{unknown_emission_prob} = 1;
483 $e = get_emission('hack', 'Rainy'); # $e = 1
484
485 =cut
486
487 sub get_emission
488 {
489 my ($self, $output, $state) = @_;
490
491 my $e = 0;
492 if (defined($self->{emission}{$output})){
493 if (defined($self->{emission}{$output}{$state})){
494 $e = $self->{emission}{$output}{$state};
495 }
496 else {
497 #output exists, but not for this state
498 $e = 0;
499 }
500 }
501 else {
502 if (defined($self->{unknown_emission_prob})){
503 $e = $self->{unknown_emission_prob};
504 }
505 else {
506 $e = $self->{start}{$state};
507 }
508 }
509 return $e;
510 }
511
512 =item get_transition
513
514 Usage: $v->get_transition($state, $next_state);
515
516 Returns the transition probability between a state and the next state.
517 This method is primarily for internal usage and is called
518 by the forward_viterbi method.
519
520 If the transition between $state and $next_state is defined, then return
521 the probability associated with it.
522
523 If the transition between $state and $next_state does not exist, then return
524 the value of $v->unknown_transition_prob, which will be 0 unless otherwise defined.
525 Setting this attribute to a very small value allows you to still obtain a Viterbi path,
526 although no suitable transitions were found between states of a given observation.
527
528 Example:
529
530 use Algorithm::Viterbi;
531
532 my $observations = [ 'walk', 'shop', 'read' ];
533
534 my $start = { 'Rainy'=> 0.5, 'Sunny'=> 0.4, 'Stormy'=> 0.1 };
535
536 my $transition = {
537 'Rainy' => {'Rainy'=> 0.7, 'Sunny'=> 0.3},
538 'Sunny' => {'Rainy'=> 0.4, 'Sunny'=> 0.5, 'Stormy'=>.1},
539 };
540
541 my $emission = {
542 'shop' => {
543 'Sunny' => '0.4',
544 'Rainy' => '0.9'
545 },
546 'read' => {
547 'Stormy' => '1'
548 },
549 'walk' => {
550 'Sunny' => '0.6',
551 'Rainy' => '0.1'
552 },
553 };
554
555 my $v = Algorithm::Viterbi->new();
556 $v->emission($emission);
557 $v->transition($transition);
558 $v->start($start);
559
560 my ($prob, $v_path, $v_prob) = $v->forward_viterbi($observations);
561 # returns 0, [], 0
562
563 $v->{unknown_transition_prob} = 1e-100;
564
565 ($prob, $v_path, $v_prob) = $v->forward_viterbi($observations);
566 # returns 1.62e-102, ['Sunny', 'Sunny', 'Stormy', 'Stormy' ], 4.8e-103;
567
568 =cut
569
570 sub get_transition
571 {
572 my ($self, $state, $next_state) = @_;
573
574 my $t = defined($self->{transition}{$state}{$next_state})
575 ? $self->{transition}{$state}{$next_state}
576 : $self->{unknown_transition_prob};
577
578 return $t;
579 }
580
581 =head1 AUTHOR
582
583 Koen Dejonghe koen@fietsoverland.com
584 Copyright (c) 2006 Koen Dejonghe. All rights reserved.
585 This program is free software; you can redistribute it and/or
586 modify it under the same terms as Perl itself.
587
588 =head1 VERSION
589
590 Version 0.01 (2006-Nov-07)
591
592 =cut
593
594 1;
595