script/wordvec.pl untested

filter: Statementstmt 0.0% 0 / 279 Branchbran 0.0% 0 / 140 Conditioncond 0.0% 0 / 58 MC/DCmcdc 0.0% 0 / 35 Subroutinesub 0.0% 0 / 4 Podpod 0.0% 0 / 3 totaltotal 0.0% 0 / 519 CC 1 SCAR 6.9
CC
1
Cov
0%
showminimal
2.0
showhelp
2.0
showversion
2.0
CRAP 2.0
1 #!/usr/local/bin/perl -w
2  
3 =head1 NAME
4  
5 wordvec.pl - Construct word vectors from bigram or co-occurrence matrices
6  
7 =head1 SYNOPSIS
8  
9 wordvec.pl [OPTIONS] WORD_PAIRS
10  
11 =head1 DESCRIPTION
12  
13 Constructs word vectors from the given WORD_PAIRS.
14  
15 =head1 INPUT
16  
17 =head2 Required Arguments:
18  
19 =head4 WORD_PAIRS
20  
21 WORD_PAIRS should be a bigram or co-occurrence pair file as created by
22 programs count.pl, statistic.pl or combig.pl from the N-gram Statistics
23 package.
24  
25 Various ways to create WORD_PAIRS are -
26  
27 =over
28  
29 =item 1. Run count.pl alone
30  
31 (WORD_PAIRS show bigram frequency counts)
32  
33 =item 2. Run count.pl followed by combig.pl
34  
35 (WORD_PAIRS show co-occurrence pair frequency counts)
36  
37 =item 3. Run count.pl followed by statistic.pl
38  
39 (WORD_PAIRS show test of association scores of bigrams)
40  
41 =item 4. Run count.pl followed by combig.pl followed by statistic.pl
42  
43 (WORD_PAIRS show test of association scores of co-occurrence pairs)
44  
45 =back
46  
47 Cases 1 and 2 will create WORD_PAIRS in format -
48  
49 word1<>word2<>n11 n1p np1
50  
51 where n11 shows the joint bigram or co-occurrence frequency count
52  
53 Cases 3 and 4 will create WORD_PAIRS in format -
54  
55 word1<>word2<>rank score n11 n1p np1
56  
57 where 'score' shows the test of association score of a bigram/co-occurrence
58 pair.
59  
60 =head2 Optional Arguments:
61  
62 =head4 --wordorder WORDORD
63  
64 Allows to retain or ignore the order of the words in the WORD_PAIRS.
65 The possible options for the value of --wordorder are -
66  
67 =over 4
68  
69 =item * nocare
70  
71 Select --wordorder = nocare when WORD_PAIRS do not show any particular order
72 of words. This is applicable only when WORD_PAIRS are created using combig.pl
73 as suggested by cases 2 and 4 in the previous section. This tells wordvec
74 that WORD_PAIRS show the joint co-occurrence scores of the word pairs.
75  
76 With wordorder = nocare, wordvec won't allow word pairs in both orders, meaning,
77 if the pair word1<>word2 appears in the WORD_PAIRS file, pair word2<>word1
78 won't be allowed.
79  
80 =item * follow [default]
81  
82 Set --wordorder = follow if WORD_PAIRS are bigrams as created with cases
83 1 and 3 shown in the previous section.
84  
85 For every word pair word1<>word2, word1 will be assigned a single feature index
86 and will represent a row in the output word matrix at that index while word2
87 will be assigned a single dimension index and will represent a column in the
88 output word matrix at that index. Assumming that word1 is assigned a feature
89 index i and represents ith row and word2 is assigned a dimension index j and
90 represents jth column, the matrix cell at [i][j] will show the frequency of
91 the bigram word1<>word2.
92  
93 =item * precede
94  
95 WORD_PAIRS are bigrams same as in --wordorder = follow, however, for every word
96 pair word1<>word2, word1 is assigned a dimension index and represents a column
97 (as against to representing a row/feature when --wordorder=follow) while word2
98 is assigned a feature index and represents a row (as against to representing
99 a dimension/column in --wordorder=follow). Assumming that word1 is assigned a
100 dimension index i and represents the ith column, while word2 is assigned a
101 feature index j and represents the jth row, frequency score of bigram
102 word1<>word2 is shown in the matrix cell at [j][i].
103  
104 Thus, the output word matrix created by --wordorder = precede is a transpose of
105 that created by --wordorder = follow.
106  
107 =back
108  
109 =head4 --binary
110  
111 Creates binary word vectors that show mere presence (by 1) or absence (by 0) of
112 the feature-dimension pairs. By default, wordvec creates frequency vectors
113 that show the frequency scores of the word pairs as given in the WORD_PAIRS
114 file.
115  
116 =head4 --dense
117  
118 Creates dense word vectors. By default, output of wordvec will show
119 sparse word vectors.
120  
121 =head4 --feats FEATFILE
122  
123 Specifies the name of the feature file that lists the words that represent the
124 rows of the output word association matrix.
125  
126 If the FEATFILE exists, words listed in this file define the rows of
127 the output word matrix. Thus, the FEATFILE specifies the feature words for
128 which the word vectors are to be created.
129  
130 If the FEATFILE doesn't exist, it is created by wordvec and shows the
131 words that represent the rows of the output word matrix.
132  
133 =head4 --dims DIMFILE
134  
135 DIMFILE is created by wordvec and reports the words that represent the
136 columns/dimensions of the output word matrix.
137  
138 =head4 --target TARGET_REGEX
139  
140 Specifies a file containing Perl regex/s that define the target word. By
141 default, target.regex file is assumed to exist in the current directory.
142 This is only required if --extarget is selected.
143  
144 =head4 --extarget
145  
146 This will ignore WORD_PAIRS in which either of the constituent words is a
147 target word. Target word can be defined by specifying a target regex file
148 via --target option or by copying target.regex file to current directory.
149  
150 =head4 --format FORM
151  
152 Specifies numeric format for representing each word vector entry.
153  
154 Possible values of FORM are
155  
156 iN -> integer format allocating total N bytes/digits for each entry
157  
158 fN.M -> floating point format allocating total N bytes/digits for each entry of which last M digits show fractional part.
159  
160 When --binary is ON, default format is i2 and otherwise default is f16.10.
161  
162 =head3 Other Options :
163  
164 =head4 --help
165  
166 Displays this message.
167  
168 =head4 --version
169  
170 Displays the version information.
171  
172 =head1 OUTPUT
173  
174 Consider the following illustration -
175  
176 Sample WORD_PAIRS input =>
177  
178 stir<>soup<>5 21 64
179 soup<>plate<>8 70 14
180 hot<>soup<>12 173 64
181 hot<>plate<>9 173 29
182 salt<>pepper<>42 124 121
183 taste<>salt<>18 83 84
184 add<>salt<>12 157 84
185 stir<>lemon<>2 21 53
186 lemon<>juice<>2 10 2
187 add<>lemon<>3 157 53
188 lemon<>pepper<>3 67 120
189 stir<>juice<>2 21 27
190  
191 =over
192  
193 =item 1. --wordorder = follow or default
194  
195 Given WORD_PAIRS are treated as bigrams and the order of the words is
196 retained such that the 1st word in the bigrams becomes a feature and
197 is assigned a unique row index while the 2nd word becomes a dimension and
198 is assigned a single column index in the output word matrix.
199  
200 case (1) Feature file provided via --feats FEATFILE doesn't exist
201  
202 Feature file is automatically created by wordvec and lists all the word types
203 that appear as the 1st words in the given bigrams. i.e. -
204  
205 stir<>
206 soup<>
207 hot<>
208 salt<>
209 taste<>
210 add<>
211 lemon<>
212  
213 The dimension file created with --dims option will list all the word types
214 that appear as the 2nd words in the given bigrams. i.e. -
215  
216 soup<>
217 plate<>
218 pepper<>
219 salt<>
220 lemon<>
221 juice<>
222  
223 Thus, the bigrams listed in the given WORD_PAIRS file can be viewed in a
224 matrix form as -
225  
226 soup<> plate<> pepper<> salt<> lemon<> juice<>
227 stir<> 5 0 0 0 2 2
228 soup<> 0 8 0 0 0 0
229 hot<> 12 9 0 0 0 0
230 salt<> 0 0 42 0 0 0
231 taste<> 0 0 0 18 0 0
232 add<> 0 0 0 12 3 0
233 lemon<> 0 0 3 0 0 2
234  
235 whose rows represent the feature words and columns represent the dimension
236 words.
237  
238 =over
239  
240 =item a. --dense not used
241  
242 By default, the output word matrix is created in sparse format in which
243 the first line shows
244  
245 #rows #cols #nnz
246  
247 i.e. number of rows, number of columns and total number of non-zero entries
248 separated by space.
249  
250 Each line thereafter shows a sparse word vector of the feature shown on
251 the corresponding line in the feature file.
252  
253 A sparse word vector lists pairs of numbers separated by space such that the
254 first number in a pair indicates the column index of a non-zero value
255 and the second number is the value itself that appears at that index.
256  
257 Thus, the output of wordvec for the above example, created with --wordorder =
258 follow or un-specified will be =>
259  
260 7 6 12
261 1 5 5 2 6 2
262 2 8
263 1 12 2 9
264 3 42
265 4 18
266 4 12 5 3
267 3 3 6 2
268  
269 where the 1st line "7 6 12" shows that there are total 7 word vectors
270 represented using 6 dimensions with 12 non-zero entries.
271  
272 Each row thereafter indicates a word vector in sparse format. e.g. 2nd line
273 shows the word vector of feature stir<>. This vector has total 3 non-zero
274 values 5, 2, 2 that occur at indices 1, 5, 6 resp.
275  
276 Column index counting starts from 1 to be consistent with Cluto's matrix format.
277  
278 =item b. --dense used
279  
280 When --dense is used, output will show the word matrix in dense format as
281  
282 7 6
283 5 0 0 0 2 2
284 0 8 0 0 0 0
285 12 9 0 0 0 0
286 0 0 42 0 0 0
287 0 0 0 18 0 0
288 0 0 0 12 3 0
289 0 0 3 0 0 2
290  
291 where the first line shows that there are 7 word vectors represented using 6
292 dimensions.
293  
294 =item c. --binary used
295  
296 When --binary is used, all non-zero bigram scores will be set to 1.
297  
298 Thus, when --dense is used, output will show
299  
300 7 6
301 1 0 0 0 1 1
302 0 1 0 0 0 0
303 1 1 0 0 0 0
304 0 0 1 0 0 0
305 0 0 0 1 0 0
306 0 0 0 1 1 0
307 0 0 1 0 0 1
308  
309 Otherwise, binary sparse vectors will look like -
310  
311 7 6 12
312 1 1 5 1 6 1
313 2 1
314 1 1 2 1
315 3 1
316 4 1
317 4 1 5 1
318 3 1 6 1
319  
320 =back
321  
322 case (2) Feature file provided via the '--feats FEATFILE' option exists
323 and lists the features for which the vectors are to be created.
324  
325 Suppose the FEATFILE contains -
326  
327 taste<>
328 hot<>
329 lemon<>
330 salt<>
331  
332 Then, for each bigram word1<>word2, if word1 is one of the above words listed
333 in the FEATFILE, a unique row index say i is assigned to word1 and a unique
334 column index say j is assigned to word2. The matrix entry at [i][j] then
335 indicates the score of the bigram word1<>word2. Thus, for the above example,
336 the word matrix can be viewed as -
337  
338 soup plate pepper salt juice
339 taste 0 0 0 18 0
340 hot 12 9 0 0 0
341 lemon 0 0 3 0 2
342 salt 0 0 42 0 0
343  
344 The dimension file created with --dims option will show the words that
345 represent the columns -
346  
347 soup<>
348 plate<>
349 pepper<>
350 salt<>
351 juice<>
352  
353 The output of wordvec created with --dense option will look as -
354  
355 4 5
356 0 0 0 18 0
357 12 9 0 0 0
358 0 0 3 0 2
359 0 0 42 0 0
360  
361 where, the first line shows that there are 4 features and 5 dimensions.
362 Each line thereafter shows the word vector of the corresponding feature word.
363  
364 The following shows the sparse representation of the same matrix when --dense
365 is not used -
366  
367 4 5 6
368 4 18
369 1 12 2 9
370 3 3 5 2
371 3 42
372  
373 where the first line indicates that there are total 4 features, 5 dimensions
374 and total 6 non-zero entries in the output matrix. Each row after that shows
375 the 'index value' pair for each non-zero entry at that row, where column
376 indices start with 1s.
377  
378 =item 2. --wordorder = precede
379  
380 Order of words in bigram pairs is retained such that 2nd word becomes a feature
381 and represents a row while the 1st word becomes a dimension and represents a
382 column of the output word matrix. The word matrix thus shows the transpose
383 of the bigram matrix created by --wordorder = follow and the cell values
384 show how frequently a dimension word precedes a feature word.
385  
386 The feature file created with --feats option shows the word types that
387 appear as the 2nd words in the given bigrams. i.e.
388  
389 soup<>
390 plate<>
391 pepper<>
392 salt<>
393 lemon<>
394 juice<>
395  
396 while the dimension file created with dims option shows the word types that
397 appear as the 1st words in the bigrams. i.e.
398  
399 stir<>
400 soup<>
401 hot<>
402 salt<>
403 taste<>
404 add<>
405 lemon<>
406  
407 Thus, the word matrix can be seen as
408  
409 stir<> soup<> hot<> salt<> taste<> add<> lemon<>
410 soup<> 5 0 12 0 0 0 0
411 plate<> 0 8 9 0 0 0 0
412 pepper<> 0 0 0 42 0 0 3
413 salt<> 0 0 0 0 18 12 0
414 lemon<> 2 0 0 0 0 3 0
415 juice<> 2 0 0 0 0 0 2
416  
417 When --dense is selected, word vectors displayed on stdout will look as -
418  
419 6 7
420 5 0 12 0 0 0 0
421 0 8 9 0 0 0 0
422 0 0 0 42 0 0 3
423 0 0 0 0 18 12 0
424 2 0 0 0 0 3 0
425 2 0 0 0 0 0 2
426  
427 while by default, output will be sparse as shown by -
428  
429 6 7 12
430 1 5 3 12
431 2 8 3 9
432 4 42 7 3
433 5 18 6 12
434 1 2 6 3
435 1 2 7 2
436  
437 If the feature file is provided, vectors are created for the given feature
438 words only and dimensions show the words that precede them.
439  
440 =item 3. --wordorder = nocare
441  
442 When wordorder is nocare, given WORD_PAIRS are treated as co-occurrence pairs
443 and the order of words is ignored.
444  
445 case (1) Feature file provided via '--feats FEATFILE' option doesnt exist.
446  
447 In this case, feature and dimension files will be same and will show all
448 unique word types encountered in the WORD_PAIRS file irrespective of the
449 positions of the words. Each word type in WORD_PAIRS is assigned a unique index
450 and represents the row and column of the output word matrix at that index.
451 Thus, the output word co-occurrence matrix is square and symmetric.
452  
453 Feature and dimension files for above example will show =>
454  
455 stir<>
456 soup<>
457 plate<>
458 hot<>
459 salt<>
460 pepper<>
461 taste<>
462 add<>
463 lemon<>
464 juice<>
465  
466 while the word matrix can be seen as
467  
468 stir<> soup<> plate<> hot<> salt<> pepper<> taste<> add<> lemon<> juice<>
469 stir<> 0 5 0 0 0 0 0 0 2 2
470 soup<> 5 0 8 12 0 0 0 0 0 0
471 plate<> 0 8 0 9 0 0 0 0 0 0
472 hot<> 0 12 9 0 0 0 0 0 0 0
473 salt<> 0 0 0 0 0 42 18 12 0 0
474 pepper<> 0 0 0 0 42 0 0 0 3 0
475 taste<> 0 0 0 0 18 0 0 0 0 0
476 add<> 0 0 0 0 12 0 0 0 3 0
477 lemon<> 2 0 0 0 0 3 0 3 0 2
478 juice<> 2 0 0 0 0 0 0 0 2 0
479  
480 Output word matrix shown on stdout will look as =>
481  
482 10 10 24
483 2 5 9 2 10 2
484 1 5 3 8 4 12
485 2 8 4 9
486 2 12 3 9
487 6 42 7 18 8 12
488 5 42 9 3
489 5 18
490 5 12 9 3
491 1 2 6 3 8 3 10 2
492 1 2 9 2
493  
494 Or as
495  
496 10 10
497 0 5 0 0 0 0 0 0 2 2
498 5 0 8 12 0 0 0 0 0 0
499 0 8 0 9 0 0 0 0 0 0
500 0 12 9 0 0 0 0 0 0 0
501 0 0 0 0 0 42 18 12 0 0
502 0 0 0 0 42 0 0 0 3 0
503 0 0 0 0 18 0 0 0 0 0
504 0 0 0 0 12 0 0 0 3 0
505 2 0 0 0 0 3 0 3 0 2
506 2 0 0 0 0 0 0 0 2 0
507  
508 when --dense is ON.
509  
510 case (2) Feature file provided via '--feats FEATFILE' exists and lists
511 the feature words for which the vectors are to be created.
512  
513 In this case, the feature and dimension files won't be same, neither the
514 output matrix will be square and symmetric, unless the FEATFILE is exactly
515 same like the one automatically created by wordvec as in case (1) above.
516 For each bigram word1<>word2 that is encountered in the WORD_PAIRS file,
517 we check if word1 is listed in the given FEATFILE. If so, word2 is assigned a
518 unique dimension index say j and the score of the bigram word1<>word2 is
519 assigned to the matrix entry at [i][j], if word1 occurs at the ith position in
520 the given FEATFILE.
521 Then, we check if word2 is listed in the given FEATFILE and if it is and
522 appears at the kth position in the FEATFILE, we assign a unique dimension
523 (column) index say l to word1 and set the matrix entry at [k][l] to the
524 co-occurrence score of the pair word1<>word2.
525  
526 For example, if the FEATFILE contains -
527  
528 soup<>
529 hot<>
530 salt<>
531 lemon<>
532 pepper<>
533  
534 then, the word matrix with --wordorder = nocare can be viewed as -
535  
536 stir plate soup hot pepper salt taste add juice lemon
537 soup<> 5 8 0 12 0 0 0 0 0 0
538 hot<> 0 9 12 0 0 0 0 0 0 0
539 salt<> 0 0 0 0 42 0 18 12 0 0
540 lemon<> 2 0 0 0 3 0 0 3 2 0
541 pepper<> 0 0 0 0 0 42 0 0 0 3
542  
543 Output will display only the word matrix as
544  
545 5 10
546 5 8 0 12 0 0 0 0 0 0
547 0 9 12 0 0 0 0 0 0 0
548 0 0 0 0 42 0 18 12 0 0
549 2 0 0 0 3 0 0 3 2 0
550 0 0 0 0 0 42 0 0 0 3
551  
552 with --dense ON
553  
554 and
555  
556 5 10 14
557 1 5 2 8 4 12
558 2 9 3 12
559 5 42 7 18 8 12
560 1 2 5 3 8 3 9 2
561 6 42 10 3
562  
563 without --dense
564  
565 The dimension file created with --dims will show -
566  
567 stir<>
568 plate<>
569 soup<>
570 hot<>
571 pepper<>
572 salt<>
573 taste<>
574 add<>
575 juice<>
576 lemon<>
577  
578 =back
579  
580 =head1 SYSTEM REQUIREMENTS
581  
582 =over
583 =item Ngram Statistics Package - L<http://search.cpan.org/dist/Text-NSP>
584 =back
585  
586 =head1 AUTHORS
587  
588 Amruta Purandare, University of Pittsburgh.
589  
590 Ted Pedersen, University of Minnesota, Duluth
591 tpederse at d.umn.edu
592  
593 =head1 COPYRIGHT
594  
595 Copyright (c) 2002-2008, Amruta Purandare and Ted Pedersen
596  
597 This program is free software; you can redistribute it and/or modify it under
598 the terms of the GNU General Public License as published by the Free Software
599 Foundation; either version 2 of the License, or (at your option) any later
600 version.
601  
602 This program is distributed in the hope that it will be useful, but WITHOUT
603 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
604 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
605  
606 You should have received a copy of the GNU General Public License along with
607 this program; if not, write to
608  
609 The Free Software Foundation, Inc.,
610 59 Temple Place - Suite 330,
611 Boston, MA 02111-1307, USA.
612  
613 =cut
614  
615 ###############################################################################
616  
617 # THE CODE STARTS HERE
618  
619 ###############################################################################
620  
621 # ================================
622 # COMMAND LINE OPTIONS AND USAGE
623 # ================================
624  
625 # command line options
626 use Getopt::Long;
627 GetOptions ("help","version","wordorder=s","binary","dense","dims=s","feats=s","format=s","target=s","extarget");
628 # show help option
629 if(defined $opt_help)
630 {
631 $opt_help=1;
632 &showhelp();
633 exit;
634 }
635  
636 # show version information
637 if(defined $opt_version)
638 {
639 $opt_version=1;
640 &showversion();
641 exit;
642 }
643  
644 # show minimal usage message if less arguments
645 if($#ARGV<0)
646 {
647 &showminimal();
648 exit;
649 }
650  
651 # default wordorder is follow
652 # word vectors show bigram scores feature<>dimension
653 if(!defined $opt_wordorder)
654 {
655 $opt_wordorder="follow";
656 }
657  
658 #############################################################################
659  
660 # ================================
661 # INITIALIZATION AND INPUT
662 # ================================
663  
664 #$0 contains the program name along with
665 #the complete path. Extract just the program
666 #name and use in error messages
667 $0=~s/.*\/(.+)/$1/;
668  
669 if($opt_wordorder !~ /(precede)|(follow)|(nocare)/)
670 {
671 print STDERR "ERROR($0):
672 --wordorder must be precede/follow/nocare.\n";
673 exit;
674 }
675  
676 # ----------------
677 # WORD_PAIRS file
678 # ----------------
679 if(!defined $ARGV[0])
680 {
681 print STDERR "ERROR($0):
682 Please specify the WORD_PAIRS file ...\n";
683 exit;
684 }
685  
686 $pairsfile=$ARGV[0];
687 if(!-e $pairsfile)
688 {
689 print STDERR "ERROR($0):
690 WORD_PAIRS file <$pairsfile> doesn't exist...\n";
691 exit;
692 }
693 open(PAIRS,$pairsfile) || die "Error($0):
694 Error(code=$!) in opening <$pairsfile> file.\n";
695  
696 # format for printing output
697 if(defined $opt_format)
698 {
699 # integer
700 if($opt_format=~/^i(\d+)$/)
701 {
702 $format_string="%$1d";
703 $lower_format="-";
704 while(length($lower_format)<($1-1))
705 {
706 $lower_format.="9";
707 }
708 if($lower_format eq "-")
709 {
710 $lower_format="0";
711 }
712 $upper_format="";
713 while(length($upper_format)<($1-1))
714 {
715 $upper_format.="9";
716 }
717 }
718 # float
719 elsif($opt_format=~/^f(\d+)\.(\d+)$/)
720 {
721 $format_string="%$1\.$2f";
722 $lower_format="-";
723 while(length($lower_format)<($1-$2-2))
724 {
725 $lower_format.="9";
726 }
727 $lower_format.=".";
728 while(length($lower_format)<($1-1))
729 {
730 $lower_format.="9";
731 }
732
733 $upper_format="";
734 while(length($upper_format)<($1-$2-2))
735 {
736 $upper_format.="9";
737 }
738 $upper_format.=".";
739 while(length($upper_format)<($1-1))
740 {
741 $upper_format.="9";
742 }
743  
744 }
745 else
746 {
747 print STDERR "ERROR($0):
748 Wrong format value --format=$opt_format.\n";
749 exit;
750 }
751 }
752 # default is f16.10 for non-binary
753 # and i2 for binary
754 else
755 {
756 if(defined $opt_binary)
757 {
758 $format_string="%2d";
759 $lower_format="0";
760 $upper_format="1";
761 }
762 else
763 {
764 $format_string="%16.10f";
765 $lower_format="-999.9999999999";
766 $upper_format="9999.9999999999";
767 }
768 }
769  
770 # -------------------
771 # Target Word regex
772 # -------------------
773  
774 #file containing regex/s that define the target word
775 if(defined $opt_extarget)
776 {
777 if(defined $opt_target)
778 {
779 $target_file=$opt_target;
780 if(!(-e $target_file))
781 {
782 print STDERR "ERROR($0):
783 Target regex file <$target_file> doesn't exist.\n";
784 exit;
785 }
786 }
787 else
788 {
789 $target_file="target.regex";
790 if(!-e $target_file)
791 {
792 print STDERR "ERROR($0):
793 Please copy the target.regex file into the current directory or specify
794 the target regex file via --target option.\n";
795 exit;
796 }
797 }
798  
799 # ------------------------
800 # creating target regex
801 # ------------------------
802  
803 open(REG,$target_file) || die "ERROR($0):
804 Error(error code=$!) in opening the target regex file <$target_file>.\n";
805  
806 while(<REG>)
807 {
808 chomp;
809 s/^\s+//g;
810 s/\s+$//g;
811 if(/^\s*$/)
812 {
813 next;
814 }
815 if(/^\//)
816 {
817 s/^\///;
818 }
819 else
820 {
821 print STDERR "ERROR($0):
822 Regular Expression <$_> should start with '/'\n";
823 exit;
824 }
825 if(/\/$/)
826 {
827 s/\/$//;
828 }
829 else
830 {
831 print STDERR "ERROR($0):
832 Regular Expression <$_> should end with '/'\n";
833 exit;
834 }
835 $target.="(".$_.")|";
836 }
837  
838 if(!defined $target)
839 {
840 print STDERR "ERROR($0):
841 No valid Perl regular expression found in the target regex file
842 <$target_file>.\n";
843 exit;
844 }
845 else
846 {
847 chop $target;
848 }
849 }
850  
851 if(defined $opt_feats)
852 {
853 $featfile=$opt_feats;
854 if(-e $featfile)
855 {
856 open(FEAT,$featfile) || die "Error($0):
857 Error(code=$!) in opening Feature file <$featfile>.\n";
858 $line_num=0;
859 while(<FEAT>)
860 {
861 $line_num++;
862 # trimming extra spaces
863 chomp;
864 # handling non-unigram lines
865 if(/^[\s\d]*$/ || ($_=~/^@/ && $_!~/<>/))
866 {
867 next;
868 }
869  
870 # --------------------------------
871 # Checking for valid unigram file
872 # --------------------------------
873 $check_unigram=$_;
874 $cnt=0;
875 #count how many times <> occurs
876 while($check_unigram=~/<>/)
877 {
878 $cnt++;
879 $check_unigram=$';
880 }
881 #should be 1 for unigrams
882 if($cnt!=1)
883 {
884 print STDERR "ERROR($0):
885 Given Feature file <$featfile> is not a valid Unigram output of NSP
886 at line <$line_num>.\n";
887 exit;
888 }
889 # storing feature words
890 if(/^(.*)<>\d*\s*$/)
891 {
892 push @features,$1;
893 $feature_index{$1}=scalar(@features);
894 }
895 else
896 {
897 print STDERR "ERROR($0):
898 Given Feature file <$featfile> is not a valid Unigram output of NSP
899 at line <$line_num>.\n";
900 exit;
901 }
902 }
903 }
904 }
905  
906  
907 ##############################################################################
908  
909 # =====================================
910 # Construct a Co-occurrence Table
911 # from the Bigram file
912 # =====================================
913  
914 # read each entry in bigram file
915 $line_num=0;
916 while(<PAIRS>)
917 {
918 $line_num++;
919 # trimming extra spaces
920 chomp;
921 # handling non-bigram lines
922 if(/^[\s\d]*$/ || ($_=~/^@/ && $_!~/<>/))
923 {
924 next;
925 }
926  
927 # ------------------------------
928 # Checking for Valid bigram file
929 # ------------------------------
930 $check_bigram=$_;
931 $cnt=0;
932 #count how many times <> occurs
933 while($check_bigram=~/<>/)
934 {
935 $cnt++;
936 $check_bigram=$';
937 }
938 #should be 2 for bigrams
939 if($cnt!=2)
940 {
941 print STDERR "ERROR($0):
942 Given WORD_PAIRS file <$pairsfile> is not a valid Bigram output of NSP
943 at line <$line_num>.\n";
944 exit;
945 }
946  
947 # --------------------------------------------------
948 # Extracting words and their Co-occurrence scores
949 # --------------------------------------------------
950  
951 # output created by count.pl or combig.pl
952 if(/^(.*)<>(.*)<>(\d+)\s+\d+\s+\d+\s*$/)
953 {
954 $word1=$1;
955 $word2=$2;
956 $score=$3;
957 }
958 # output created by statistic.pl
959 elsif(/^(.*)<>(.*)<>\d+\s+(\-?\d*\.?\d+)\s+\d+\s+\d+\s+\d+\s*$/)
960 {
961 $word1=$1;
962 $word2=$2;
963 $score=$3;
964 }
965 else
966 {
967 print STDERR "ERROR($0):
968 Given WORD_PAIRS file <$pairsfile> is not a valid Bigram output of NSP
969 at line <$line_num>.\n";
970 exit;
971 }
972
973 # ignore pair if either of the features is a target word
974 if(defined $opt_extarget && ($word1=~/^$target$/ || $word2=~/^$target$/))
975 {
976 next;
977 }
978  
979 # added by AKK 21st Feb 2005
980 # skip the word-pairs with 0 score
981 # and the word-pairs whose score become 0 after formatting
982 $value=sprintf $format_string,$score;
983
984 # for binary representation
985 if(defined $opt_binary && $value != 0)
986 {
987 $value = 1;
988 }
989  
990 if($value<$lower_format)
991 {
992 print STDERR "ERROR($0):
993 Floating point underflow.
994 Value <$value> can't be represented with format $format_string.\n";
995 exit 1;
996 }
997 if($value>$upper_format)
998 {
999 print STDERR "ERROR($0):
1000 Floating point overflow.
1001 Value <$value> can't be represented with format $format_string.\n";
1002 exit 1;
1003 }
1004 if($value==0)
1005 {
1006 next;
1007 }
1008 # end by AKK
1009  
1010 # wordorder = nocare when order of words in WORD_PAIRS file
1011 # doesn't matter
1012 # every word type is a feature as well as dimension
1013 if($opt_wordorder =~ /nocare/)
1014 {
1015 if(defined $featfile && -e $featfile)
1016 {
1017 if(defined $feature_index{$word1})
1018 {
1019 if(!defined $dimension_index{$word2})
1020 {
1021 push @dimensions, $word2;
1022 $dimension_index{$word2}=scalar(@dimensions);
1023 }
1024 $index1=$feature_index{$word1};
1025 $index2=$dimension_index{$word2};
1026
1027 if(defined $coctable{$index1}{$index2})
1028 {
1029 print STDERR "ERROR($0):
1030 Pair \"$word1<>$word2\" is repeated in the WORD_PAIRS file <$pairsfile>.\n";
1031 exit;
1032 }
1033 if(defined $opt_binary)
1034 {
1035 $coctable{$index1}{$index2}=1;
1036 }
1037 else
1038 {
1039 $coctable{$index1}{$index2}=$score;
1040 }
1041 $nnz++;
1042 }
1043 if(($word1 ne $word2) && defined $feature_index{$word2})
1044 {
1045 if(!defined $dimension_index{$word1})
1046 {
1047 push @dimensions, $word1;
1048 $dimension_index{$word1}=scalar(@dimensions);
1049 }
1050 $index1=$feature_index{$word2};
1051 $index2=$dimension_index{$word1};
1052
1053 if(defined $coctable{$index1}{$index2})
1054 {
1055 print STDERR "ERROR($0):
1056 Pair \"$word1<>$word2\" is repeated in the WORD_PAIRS file <$pairsfile>.\n";
1057 exit;
1058 }
1059 if(defined $opt_binary)
1060 {
1061 $coctable{$index1}{$index2}=1;
1062 }
1063 else
1064 {
1065 $coctable{$index1}{$index2}=$score;
1066 }
1067 $nnz++;
1068 }
1069 }
1070 else
1071 {
1072 # assigning numeric index to each feature/dimension
1073 if(!defined $index{$word1})
1074 {
1075 push @features,$word1;
1076 push @dimensions,$word1;
1077 $index{$word1}=scalar(@features);
1078 }
1079 if(!defined $index{$word2})
1080 {
1081 push @features,$word2;
1082 push @dimensions,$word2;
1083 $index{$word2}=scalar(@features);
1084 }
1085
1086 $index1=$index{$word1};
1087 $index2=$index{$word2};
1088
1089 # pair already seen
1090 if(defined $coctable{$index1}{$index2} || defined $coctable{$index2}{$index1})
1091 {
1092 print STDERR "ERROR($0):
1093 Pair \"$word1<>$word2\" is repeated in the WORD_PAIRS file <$pairsfile>.\n";
1094 exit;
1095 }
1096 if(!defined $opt_binary)
1097 {
1098 $coctable{$index1}{$index2}=$score;
1099 $coctable{$index2}{$index1}=$score;
1100 }
1101 else
1102 {
1103 $coctable{$index1}{$index2}=1;
1104 $coctable{$index2}{$index1}=1;
1105 }
1106 if($word1 ne $word2)
1107 {
1108 $nnz+=2;
1109 }
1110 else
1111 {
1112 $nnz++;
1113 }
1114 }
1115 }
1116 # wordorder = precede
1117 elsif($opt_wordorder =~ /precede/)
1118 {
1119 if(defined $featfile && -e $featfile && !defined $feature_index{$word2})
1120 {
1121 next;
1122 }
1123 # with wordorder = precede,
1124 # word2 is a feature and
1125 # word1 is a dimension
1126 if(!defined $feature_index{$word2})
1127 {
1128 push @features,$word2;
1129 $feature_index{$word2}=scalar(@features);
1130 }
1131 if(!defined $dimension_index{$word1})
1132 {
1133 push @dimensions,$word1;
1134 $dimension_index{$word1}=scalar(@dimensions);
1135 }
1136
1137 $index1=$feature_index{$word2};
1138 $index2=$dimension_index{$word1};
1139  
1140 if(defined $coctable{$index1}{$index2})
1141 {
1142 print STDERR "ERROR($0):
1143 Pair \"$word1<>$word2\" is repeated in WORD_PAIRS file <$pairsfile>.\n";
1144 exit;
1145 }
1146 if(!defined $opt_binary)
1147 {
1148 $coctable{$index1}{$index2}=$score;
1149 }
1150 else
1151 {
1152 $coctable{$index1}{$index2}=1;
1153 }
1154 $nnz++;
1155 }
1156 # wordorder = follow
1157 elsif($opt_wordorder =~ /follow/)
1158 {
1159 if(defined $featfile && -e $featfile && !defined $feature_index{$word1})
1160 {
1161 next;
1162 }
1163 # with wordorder = follow
1164 # word1 is a feature and
1165 # word2 is a dimension
1166 if(!defined $feature_index{$word1})
1167 {
1168 push @features,$word1;
1169 $feature_index{$word1}=scalar(@features);
1170 }
1171 if(!defined $dimension_index{$word2})
1172 {
1173 push @dimensions,$word2;
1174 $dimension_index{$word2}=scalar(@dimensions);
1175 }
1176  
1177 $index1=$feature_index{$word1};
1178 $index2=$dimension_index{$word2};
1179
1180 if(defined $coctable{$index1}{$index2})
1181 {
1182 print STDERR "ERROR($0):
1183 Pair \"$word1<>$word2\" is repeated in WORD_PAIRS file <$pairsfile>.\n";
1184 exit;
1185 }
1186 if(!defined $opt_binary)
1187 {
1188 $coctable{$index1}{$index2}=$score;
1189 }
1190 else
1191 {
1192 $coctable{$index1}{$index2}=1;
1193 }
1194 $nnz++;
1195 }
1196 }
1197  
1198 ##############################################################################
1199  
1200 # =========================
1201 # Printing Word Vectors
1202 # =========================
1203  
1204 print scalar(@features) . " " . scalar(@dimensions);
1205  
1206 if(!defined $opt_dense)
1207 {
1208 print " $nnz";
1209 }
1210 print "\n";
1211  
1212 # for each feature
1213 foreach $row (1..scalar(@features))
1214 {
1215 if(defined $opt_dense)
1216 {
1217 # for each dimension
1218 foreach $col (1..scalar(@dimensions))
1219 {
1220 # checking if feature-dimension co-occur
1221 # according to the bigram file
1222 if(defined $coctable{$row}{$col})
1223 {
1224 $value=sprintf $format_string,$coctable{$row}{$col};
1225 if($value<$lower_format)
1226 {
1227 print STDERR "ERROR($0):
1228 Floating point underflow.
1229 Value <$value> can't be represented with format $format_string.\n";
1230 exit 1;
1231 }
1232 if($value>$upper_format)
1233 {
1234 print STDERR "ERROR($0):
1235 Floating point overflow.
1236 Value <$value> can't be represented with format $format_string.\n";
1237 exit 1;
1238 }
1239 }
1240 else
1241 {
1242 $value=sprintf($format_string,0);
1243 }
1244 print $value;
1245 }
1246 }
1247 # print sparse word vectors
1248 else
1249 {
1250 @sparse_cols=keys %{$coctable{$row}};
1251 @sorted_sparse_cols=sort {$a <=> $b} @sparse_cols;
1252 foreach $sparse_col (@sorted_sparse_cols)
1253 {
1254 # added by AKK on 21st Feb 2005
1255 # filter out the 0 valued scores
1256 #$val = $coctable{$row}{$sparse_col};
1257 $val=sprintf $format_string,$coctable{$row}{$sparse_col};
1258 # if($val != 0)
1259 # {
1260 # print "$sparse_col $coctable{$row}{$sparse_col} ";
1261 print "$sparse_col $val ";
1262 # }
1263 }
1264 }
1265  
1266 print "\n";
1267 }
1268  
1269 undef $opt_extarget;
1270 ##############################################################################
1271  
1272 # =====================================
1273 # Reporting Features and Dimensions
1274 # =====================================
1275  
1276 # -------------
1277 # Feature file
1278 # -------------
1279 if(defined $featfile && !-e $featfile)
1280 {
1281 open(FEAT,">$featfile") || die "ERROR($0):
1282 Error(code=$!) in opening Feature file <$featfile>.\n";
1283 foreach (@features)
1284 {
1285 print FEAT "$_<>\n";
1286 }
1287 }
1288  
1289 # ----------------
1290 # Dimension file
1291 # ----------------
1292 if(defined $opt_dims)
1293 {
1294 $dimfile=$opt_dims;
1295 if(-e $dimfile)
1296 {
1297 print STDERR "Warning($0):
1298 Dimension file <$dimfile> already exists, overwrite (y/n)? ";
1299 $ans=<STDIN>;
1300 }
1301 if(!-e $dimfile || $ans=~/Y|y/)
1302 {
1303 open(DIM,">$dimfile") || die "ERROR($0):
1304 Error(code=$!) in opening Dimension file <$dimfile>.\n";
1305 foreach (@dimensions)
1306 {
1307 print DIM "$_<>\n";
1308 }
1309 }
1310 }
1311  
1312 ##############################################################################
1313  
1314 # ==========================
1315 # SUBROUTINE SECTION
1316 # ==========================
1317  
1318 #-----------------------------------------------------------------------------
1319 #show minimal usage message
1320 sub showminimal()
1321 {
1322 print "Usage: wordvec.pl [OPTIONS] WORD_PAIRS";
1323 print "\nTYPE wordvec.pl --help for help\n";
1324 }
1325  
1326 #-----------------------------------------------------------------------------
1327 #show help
1328 sub showhelp()
1329 {
1330 print "Usage: wordvec.pl [OPTIONS] WORD_PAIRS
1331  
1332 Converts the given NSP output into a word-by-word association matrix.
1333  
1334 WORD_PAIRS
1335 Should be a bigram/co-occurrence score file as created by programs
1336 count.pl, combig.pl or statistics.pl from the NSP.
1337  
1338 OPTIONS:
1339  
1340 --wordorder WORDORD
1341 Specifies whether wordvec should retain or ignore the order of words
1342 in the WORD_PAIRS file.
1343  
1344 The possible values of WORDORD are -
1345  
1346 nocare - order of words in WORD_PAIRs is ignored.
1347 WORD_PAIRS are co-occurrence pairs created using
1348 combig.pl program from NSP
1349  
1350 follow - WORD_PAIRS are bigrams and word vectors show how
1351 frequently a dimension word (2nd word) follows a
1352 feature word (1st word) [Default]
1353  
1354 precede - WORD_PAIRS are bigrams and word vectors show how
1355 frequently a dimension word (1st word) precedes a
1356 feature word (2nd word)
1357  
1358 --binary
1359 Creates binary word vectors.
1360  
1361 --dense
1362 Creates dense word vectors. By default, output word vectors are sparse.
1363  
1364 --feats FEATFILE
1365 If the FEATFILE exists, features are extracted from this file,
1366 otherwise, automatically extracted features are written into the
1367 FEATFILE.
1368  
1369 --dims DIMFILE
1370 Writes extracted dimensions to DIMFILE.
1371  
1372 --target TARGET_REGEX
1373 Specifies a file containing Perl regex/s that define the target word.
1374 By default, target.regex is assumed to exist in current directory.
1375 --target is ignored unless --extarget is used.
1376  
1377 --extarget
1378 Ignores WORD_PAIRS in which either of the constituent words is a target
1379 word as specified via --target option or default target.regex file.
1380  
1381 --format FORM
1382 Specifies the numeric format for output representation. Default format
1383 for binary word vectors is i2 and for non-binary frequency vectors
1384 default format is f16.10.
1385
1386 --help
1387 Displays this message.
1388  
1389 --version
1390 Displays the version information.
1391  
1392 Type 'perldoc wordvec.pl' to view detailed documentation of wordvec.\n";
1393 }
1394  
1395 #------------------------------------------------------------------------------
1396 #version information
1397 sub showversion()
1398 {
1399 print '$Id: wordvec.pl,v 1.24 2008/03/30 04:40:58 tpederse Exp $';
1400 print "\nCreate word vectors from Text-NSP output\n";
1401 # print "wordvec.pl - Version 0.4\n";
1402 # print "Builds word vectors.\n";
1403 # print "Copyright (c) 2002-2005, Amruta Purandare, Anagha Kulkarni & Ted Pedersen.\n";
1404 # print "Date of Last Update: 03/04/2005\n";
1405 }
1406  
1407 #############################################################################
1408