-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
CRFClassifier.java
3103 lines (2785 loc) · 116 KB
/
CRFClassifier.java
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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// CRFClassifier -- a probabilistic (CRF) sequence model, mainly used for NER.
// Copyright (c) 2002-2016 The Board of Trustees of
// The Leland Stanford Junior University. All Rights Reserved.
//
// 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 2
// 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, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
// For more information, bug reports, fixes, contact:
// Christopher Manning
// Dept of Computer Science, Gates 1A
// Stanford CA 94305-9010
// USA
// Support/Questions: java-nlp-user@lists.stanford.edu
// Licensing: java-nlp-support@lists.stanford.edu
package edu.stanford.nlp.ie.crf;
import edu.stanford.nlp.ie.*;
import edu.stanford.nlp.io.IOUtils;
import edu.stanford.nlp.io.RuntimeIOException;
import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.math.ArrayMath;
import edu.stanford.nlp.objectbank.ObjectBank;
import edu.stanford.nlp.optimization.*;
import edu.stanford.nlp.optimization.Function;
import edu.stanford.nlp.sequences.*;
import edu.stanford.nlp.stats.ClassicCounter;
import edu.stanford.nlp.stats.Counter;
import edu.stanford.nlp.stats.TwoDimensionalCounter;
import edu.stanford.nlp.util.*;
import edu.stanford.nlp.util.logging.Redwood;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;
import java.util.regex.*;
import java.util.stream.Collectors;
import java.util.zip.GZIPOutputStream;
/**
* Class for sequence classification using a Conditional Random Field model.
* The code has functionality for different document formats, but when
* using the standard {@link edu.stanford.nlp.sequences.ColumnDocumentReaderAndWriter} for training
* or testing models, input files are expected to
* be one token per line with the columns indicating things like the word,
* POS, chunk, and answer class. The default for
* {@code ColumnDocumentReaderAndWriter} training data is 3 column input,
* with the columns containing a word, its POS, and its gold class, but
* this can be specified via the {@code map} property.
* </p><p>
* When run on a file with {@code -textFile} or {@code -textFiles},
* the file is assumed to be plain English text (or perhaps simple HTML/XML),
* and a reasonable attempt is made at English tokenization by
* {@link PlainTextDocumentReaderAndWriter}. The class used to read
* the text can be changed with -plainTextDocumentReaderAndWriter.
* Extra options can be supplied to the tokenizer using the
* -tokenizerOptions flag.
* </p><p>
* To read from stdin, use the flag -readStdin. The same
* reader/writer will be used as for -textFile.
* </p>
* <p><b>Typical command-line usage</b></p>
* <p>For running a trained model with a provided serialized classifier on a
* text file: </p>
* <p>
* {@code java -mx500m edu.stanford.nlp.ie.crf.CRFClassifier -loadClassifier
* conll.ner.gz -textFile sampleSentences.txt }
* </p>
* <p>
* When specifying all parameters in a properties file (train, test, or
* runtime):
* </p>
* <p>
* {@code java -mx1g edu.stanford.nlp.ie.crf.CRFClassifier -prop propFile }
* </p>
* <p>
* To train and test a simple NER model from the command line:</p>
* <p>
* {@code java -mx1000m edu.stanford.nlp.ie.crf.CRFClassifier
* -trainFile trainFile -testFile testFile -macro > output }
* </p>
* <p>
* To train with multiple files: </p>
* <p>
* {@code java -mx1000m edu.stanford.nlp.ie.crf.CRFClassifier
* -trainFileList file1,file2,... -testFile testFile -macro > output }
* </p>
* <p>
* To test on multiple files, use the -testFiles option and a comma
* separated list.
* </p>
* <p>
* Features are defined by a {@link edu.stanford.nlp.sequences.FeatureFactory}.
* {@link NERFeatureFactory} is used by default, and you should look
* there for feature templates and properties or flags that will cause
* certain features to be used when training an NER classifier. There
* are also various feature factories for Chinese word segmentation
* such as {@link edu.stanford.nlp.wordseg.ChineseSegmenterFeatureFactory}.
* Features are specified either
* by a Properties file (which is the recommended method) or by flags on the
* command line. The flags are read into a {@link SeqClassifierFlags} object,
* which the user need not be concerned with, unless wishing to add new
* features. </p> CRFClassifier may also be used programmatically. When creating
* a new instance, you <i>must</i> specify a Properties object. You may then
* call train methods to train a classifier, or load a classifier. The other way
* to get a CRFClassifier is to deserialize one via the static
* {@link CRFClassifier#getClassifier(String)} methods, which return a
* deserialized classifier. You may then tag (classify the items of) documents
* using either the assorted {@code classify()} methods here or the additional
* ones in {@link AbstractSequenceClassifier}.
* Probabilities assigned by the CRF can be interrogated using either the
* {@code printProbsDocument()} or {@code getCliqueTrees()} methods.
*
* @author Jenny Finkel
* @author Sonal Gupta (made the class generic)
* @author Mengqiu Wang (LOP implementation and non-linear CRF implementation)
*/
public class CRFClassifier<IN extends CoreMap> extends AbstractSequenceClassifier<IN> {
/** A logger for this class */
private static final Redwood.RedwoodChannels log = Redwood.channels(CRFClassifier.class);
// TODO(mengqiu) need to move the embedding lookup and capitalization features into a FeatureFactory
List<Index<CRFLabel>> labelIndices;
Index<String> tagIndex;
private Pair<double[][], double[][]> entityMatrices;
CliquePotentialFunction cliquePotentialFunction;
HasCliquePotentialFunction cliquePotentialFunctionHelper;
/** Parameter weights of the classifier. weights[featureIndex][labelIndex] */
double[][] weights;
/** index the features of CRF */
Index<String> featureIndex;
/** caches the featureIndex */
int[] map;
Random random = new Random(2147483647L);
Index<Integer> nodeFeatureIndicesMap;
Index<Integer> edgeFeatureIndicesMap;
private Map<String, double[]> embeddings; // = null;
/**
* Name of default serialized classifier resource to look for in a jar file.
*/
public static final String DEFAULT_CLASSIFIER = "/edu/stanford/nlp/models/ner/english.all.3class.distsim.crf.ser.gz";
private static final boolean VERBOSE = false;
/**
* Fields for grouping features
*/
private Pattern suffixPatt = Pattern.compile(".+?((?:-[A-Z]+)+)\\|.*C");
private Index<String> templateGroupIndex;
private Map<Integer, Integer> featureIndexToTemplateIndex;
// Label dictionary for fast decoding
private LabelDictionary labelDictionary;
// List selftraindatums = new ArrayList();
protected CRFClassifier() {
super(new SeqClassifierFlags());
}
public CRFClassifier(Properties props) {
super(props);
}
public CRFClassifier(SeqClassifierFlags flags) {
super(flags);
}
/**
* Makes a copy of the crf classifier
*/
public CRFClassifier(CRFClassifier<IN> crf) {
super(crf.flags);
this.windowSize = crf.windowSize;
this.featureFactories = crf.featureFactories;
this.pad = crf.pad;
if (crf.knownLCWords == null) {
this.knownLCWords = new MaxSizeConcurrentHashSet<>(crf.flags.maxAdditionalKnownLCWords);
} else {
this.knownLCWords = new MaxSizeConcurrentHashSet<>(crf.knownLCWords);
this.knownLCWords.setMaxSize(this.knownLCWords.size() + crf.flags.maxAdditionalKnownLCWords);
}
this.featureIndex = (crf.featureIndex != null) ? new HashIndex<>(crf.featureIndex.objectsList()) : null;
this.classIndex = (crf.classIndex != null) ? new HashIndex<>(crf.classIndex.objectsList()) : null;
if (crf.labelIndices != null) {
this.labelIndices = new ArrayList<>(crf.labelIndices.size());
for (int i = 0; i < crf.labelIndices.size(); i++) {
this.labelIndices.add((crf.labelIndices.get(i) != null) ? new HashIndex<>(crf.labelIndices.get(i).objectsList()) : null);
}
} else {
this.labelIndices = null;
}
this.cliquePotentialFunction = crf.cliquePotentialFunction;
}
/**
* Returns the total number of weights associated with this classifier.
*
* @return number of weights
*/
public int getNumWeights() {
if (weights == null) return 0;
int numWeights = 0;
for (double[] wts : weights) {
numWeights += wts.length;
}
return numWeights;
}
/**
* Get index of featureType for feature indexed by i. (featureType index is
* used to index labelIndices to get labels.)
*
* @param i Feature index
* @return index of featureType
*/
private int getFeatureTypeIndex(int i) {
return getFeatureTypeIndex(featureIndex.get(i));
}
/**
* Get index of featureType for feature based on the feature string
* (featureType index used to index labelIndices to get labels)
*
* @param feature Feature string
* @return index of featureType
*/
private static int getFeatureTypeIndex(String feature) {
if (feature.endsWith("|C")) {
return 0;
} else if (feature.endsWith("|CpC")) {
return 1;
} else if (feature.endsWith("|Cp2C")) {
return 2;
} else if (feature.endsWith("|Cp3C")) {
return 3;
} else if (feature.endsWith("|Cp4C")) {
return 4;
} else if (feature.endsWith("|Cp5C")) {
return 5;
} else {
throw new RuntimeException("Unknown feature type " + feature);
}
}
/**
* Scales the weights of this CRFClassifier by the specified weight.
*
* @param scale The scale to multiply by
*/
public void scaleWeights(double scale) {
for (int i = 0; i < weights.length; i++) {
for (int j = 0; j < weights[i].length; j++) {
weights[i][j] *= scale;
}
}
}
/**
* Combines weights from another crf (scaled by weight) into this CRF's
* weights (assumes that this CRF's indices have already been updated to
* include features/labels from the other crf)
*
* @param crf Other CRF whose weights to combine into this CRF
* @param weight Amount to scale the other CRF's weights by
*/
private void combineWeights(CRFClassifier<IN> crf, double weight) {
int numFeatures = featureIndex.size();
int oldNumFeatures = weights.length;
// Create a map of other crf labels to this crf labels
Map<CRFLabel, CRFLabel> crfLabelMap = Generics.newHashMap();
for (int i = 0; i < crf.labelIndices.size(); i++) {
for (int j = 0; j < crf.labelIndices.get(i).size(); j++) {
CRFLabel labels = crf.labelIndices.get(i).get(j);
int[] newLabelIndices = new int[i + 1];
for (int ci = 0; ci <= i; ci++) {
String classLabel = crf.classIndex.get(labels.getLabel()[ci]);
newLabelIndices[ci] = this.classIndex.indexOf(classLabel);
}
CRFLabel newLabels = new CRFLabel(newLabelIndices);
crfLabelMap.put(labels, newLabels);
int k = this.labelIndices.get(i).indexOf(newLabels); // IMPORTANT: the indexing is needed, even when not printed out!
// log.info("LabelIndices " + i + " " + labels + ": " + j +
// " mapped to " + k);
}
}
// Create map of featureIndex to featureTypeIndex
map = new int[numFeatures];
for (int i = 0; i < numFeatures; i++) {
map[i] = getFeatureTypeIndex(i);
}
// Create new weights
double[][] newWeights = new double[numFeatures][];
for (int i = 0; i < numFeatures; i++) {
int length = labelIndices.get(map[i]).size();
newWeights[i] = new double[length];
if (i < oldNumFeatures) {
assert (length >= weights[i].length);
System.arraycopy(weights[i], 0, newWeights[i], 0, weights[i].length);
}
}
weights = newWeights;
// Get original weight indices from other crf and weight them in
// depending on the type of the feature, different number of weights is
// associated with it
for (int i = 0; i < crf.weights.length; i++) {
String feature = crf.featureIndex.get(i);
int newIndex = featureIndex.indexOf(feature);
// Check weights are okay dimension
if (weights[newIndex].length < crf.weights[i].length) {
throw new RuntimeException("Incompatible CRFClassifier: weight length mismatch for feature " + newIndex + ": "
+ featureIndex.get(newIndex) + " (also feature " + i + ": " + crf.featureIndex.get(i) + ") " + ", len1="
+ weights[newIndex].length + ", len2=" + crf.weights[i].length);
}
int featureTypeIndex = map[newIndex];
for (int j = 0; j < crf.weights[i].length; j++) {
CRFLabel labels = crf.labelIndices.get(featureTypeIndex).get(j);
CRFLabel newLabels = crfLabelMap.get(labels);
int k = this.labelIndices.get(featureTypeIndex).indexOf(newLabels);
weights[newIndex][k] += crf.weights[i][j] * weight;
}
}
}
/**
* Combines weighted crf with this crf.
*
* @param crf Other CRF whose weights to combine into this CRF
* @param weight Amount to scale the other CRF's weights by
*/
public void combine(CRFClassifier<IN> crf, double weight) {
Timing timer = new Timing();
// Check the CRFClassifiers are compatible
if (!this.pad.equals(crf.pad)) {
throw new RuntimeException("Incompatible CRFClassifier: pad does not match");
}
if (this.windowSize != crf.windowSize) {
throw new RuntimeException("Incompatible CRFClassifier: windowSize does not match");
}
if (this.labelIndices.size() != crf.labelIndices.size()) {
// Should match since this should be same as the windowSize
throw new RuntimeException("Incompatible CRFClassifier: labelIndices length does not match");
}
this.classIndex.addAll(crf.classIndex.objectsList());
// Combine weights of the other classifier with this classifier,
// weighing the other classifier's weights by weight
// First merge the feature indices
int oldNumFeatures1 = this.featureIndex.size();
int oldNumFeatures2 = crf.featureIndex.size();
int oldNumWeights1 = this.getNumWeights();
int oldNumWeights2 = crf.getNumWeights();
this.featureIndex.addAll(crf.featureIndex.objectsList());
this.knownLCWords.addAll(crf.knownLCWords);
assert (weights.length == oldNumFeatures1);
// Combine weights of this classifier with other classifier
for (int i = 0; i < labelIndices.size(); i++) {
this.labelIndices.get(i).addAll(crf.labelIndices.get(i).objectsList());
}
log.info("Combining weights: will automatically match labelIndices");
combineWeights(crf, weight);
int numFeatures = featureIndex.size();
int numWeights = getNumWeights();
long elapsedMs = timer.stop();
log.info("numFeatures: orig1=" + oldNumFeatures1 + ", orig2=" + oldNumFeatures2 + ", combined="
+ numFeatures);
log.info("numWeights: orig1=" + oldNumWeights1 + ", orig2=" + oldNumWeights2 + ", combined=" + numWeights);
log.info("Time to combine CRFClassifier: " + Timing.toSecondsString(elapsedMs) + " seconds");
}
public void dropFeaturesBelowThreshold(double threshold) {
Index<String> newFeatureIndex = new HashIndex<>();
for (int i = 0; i < weights.length; i++) {
double smallest = weights[i][0];
double biggest = weights[i][0];
for (int j = 1; j < weights[i].length; j++) {
if (weights[i][j] > biggest) {
biggest = weights[i][j];
}
if (weights[i][j] < smallest) {
smallest = weights[i][j];
}
if (biggest - smallest > threshold) {
newFeatureIndex.add(featureIndex.get(i));
break;
}
}
}
int[] newMap = new int[newFeatureIndex.size()];
for (int i = 0; i < newMap.length; i++) {
int index = featureIndex.indexOf(newFeatureIndex.get(i));
newMap[i] = map[index];
}
map = newMap;
featureIndex = newFeatureIndex;
}
/**
* Convert a document List into arrays storing the data features and labels.
* This is used at test time.
*
* @param document Testing documents
* @return A Triple, where the first element is an int[][][] representing the
* data, the second element is an int[] representing the labels, and
* the third element is a double[][][] representing the feature values (optionally null)
*/
public Triple<int[][][], int[], double[][][]> documentToDataAndLabels(List<IN> document) {
int docSize = document.size();
// first index is position in the document also the index of the
// clique/factor table
// second index is the number of elements in the clique/window these
// features are for (starting with last element)
// third index is position of the feature in the array that holds them.
// An element in data[j][k][m] is the feature index of the mth feature occurring in
// position k of the jth clique
int[][][] data = new int[docSize][windowSize][];
double[][][] featureVals = new double[docSize][windowSize][];
// index is the position in the document.
// element in labels[j] is the index of the correct label (if it exists) at
// position j of document
int[] labels = new int[docSize];
if (flags.useReverse) {
Collections.reverse(document);
}
// log.info("docSize:"+docSize);
for (int j = 0; j < docSize; j++) {
CRFDatum<List<String>, CRFLabel> d = makeDatum(document, j, featureFactories);
List<List<String>> features = d.asFeatures();
List<double[]> featureValList = d.asFeatureVals();
for (int k = 0, fSize = features.size(); k < fSize; k++) {
Collection<String> cliqueFeatures = features.get(k);
data[j][k] = new int[cliqueFeatures.size()];
if(featureValList != null) { // CRFBiasedClassifier.makeDatum causes null
featureVals[j][k] = featureValList.get(k);
}
int m = 0;
for (String feature : cliqueFeatures) {
int index = featureIndex.indexOf(feature);
if (index >= 0) {
data[j][k][m] = index;
m++;
} else {
// this is where we end up when we do feature threshold cutoffs
}
}
if (m < data[j][k].length) {
int[] f = new int[m];
System.arraycopy(data[j][k], 0, f, 0, m);
data[j][k] = f;
if (featureVals[j][k] != null) {
double[] fVal = new double[m];
System.arraycopy(featureVals[j][k], 0, fVal, 0, m);
featureVals[j][k] = fVal;
}
}
}
IN wi = document.get(j);
labels[j] = classIndex.indexOf(wi.get(CoreAnnotations.AnswerAnnotation.class));
}
if (flags.useReverse) {
Collections.reverse(document);
}
return new Triple<>(data, labels, featureVals);
}
private int[][][] transformDocData(int[][][] docData) {
int[][][] transData = new int[docData.length][][];
for (int i = 0; i < docData.length; i++) {
transData[i] = new int[docData[i].length][];
for (int j = 0; j < docData[i].length; j++) {
int[] cliqueFeatures = docData[i][j];
transData[i][j] = new int[cliqueFeatures.length];
for (int n = 0; n < cliqueFeatures.length; n++) {
int transFeatureIndex; // initialized below;
if (j == 0) {
transFeatureIndex = nodeFeatureIndicesMap.indexOf(cliqueFeatures[n]);
if (transFeatureIndex == -1)
throw new RuntimeException("node cliqueFeatures[n]="+cliqueFeatures[n]+" not found, nodeFeatureIndicesMap.size="+nodeFeatureIndicesMap.size());
} else {
transFeatureIndex = edgeFeatureIndicesMap.indexOf(cliqueFeatures[n]);
if (transFeatureIndex == -1)
throw new RuntimeException("edge cliqueFeatures[n]="+cliqueFeatures[n]+" not found, edgeFeatureIndicesMap.size="+edgeFeatureIndicesMap.size());
}
transData[i][j][n] = transFeatureIndex;
}
}
}
return transData;
}
public void printLabelInformation(String testFile, DocumentReaderAndWriter<IN> readerAndWriter) throws Exception {
ObjectBank<List<IN>> documents = makeObjectBankFromFile(testFile, readerAndWriter);
for (List<IN> document : documents) {
printLabelValue(document);
}
}
public void printLabelValue(List<IN> document) {
if (flags.useReverse) {
Collections.reverse(document);
}
NumberFormat nf = new DecimalFormat();
List<String> classes = new ArrayList<>();
for (int i = 0; i < classIndex.size(); i++) {
classes.add(classIndex.get(i));
}
String[] columnHeaders = classes.toArray(new String[classes.size()]);
// log.info("docSize:"+docSize);
for (int j = 0; j < document.size(); j++) {
System.out.println("--== " + document.get(j).get(CoreAnnotations.TextAnnotation.class) + " ==--");
List<String[]> lines = new ArrayList<>();
List<String> rowHeaders = new ArrayList<>();
List<String> line = new ArrayList<>();
for (int p = 0; p < labelIndices.size(); p++) {
if (j + p >= document.size()) {
continue;
}
CRFDatum<List<String>, CRFLabel> d = makeDatum(document, j + p, featureFactories);
List<List<String>> features = d.asFeatures();
for (int k = p, fSize = features.size(); k < fSize; k++) {
Collection<String> cliqueFeatures = features.get(k);
for (String feature : cliqueFeatures) {
int index = featureIndex.indexOf(feature);
if (index >= 0) {
// line.add(feature+"["+(-p)+"]");
rowHeaders.add(feature + '[' + (-p) + ']');
double[] values = new double[labelIndices.get(0).size()];
for (CRFLabel label : labelIndices.get(k)) {
int[] l = label.getLabel();
double v = weights[index][labelIndices.get(k).indexOf(label)];
values[l[l.length - 1 - p]] += v;
}
for (double value : values) {
line.add(nf.format(value));
}
lines.add(line.toArray(new String[line.size()]));
line = new ArrayList<>();
}
}
}
// lines.add(Collections.<String>emptyList());
System.out.println(StringUtils.makeTextTable(lines.toArray(new String[lines.size()][0]), rowHeaders
.toArray(new String[rowHeaders.size()]), columnHeaders, 0, 1, true));
System.out.println();
}
// log.info(edu.stanford.nlp.util.StringUtils.join(lines,"\n"));
}
if (flags.useReverse) {
Collections.reverse(document);
}
}
/**
* Convert an ObjectBank to arrays of data features and labels.
* This version is used at training time.
*
* @return A Triple, where the first element is an int[][][][] representing the
* data, the second element is an int[][] representing the labels, and
* the third element is a double[][][][] representing the feature values
* which could be optionally left as null.
*/
public Triple<int[][][][], int[][], double[][][][]> documentsToDataAndLabels(Collection<List<IN>> documents) {
// first index is the number of the document
// second index is position in the document also the index of the
// clique/factor table
// third index is the number of elements in the clique/window these features
// are for (starting with last element)
// fourth index is position of the feature in the array that holds them
// element in data[i][j][k][m] is the index of the mth feature occurring in
// position k of the jth clique of the ith document
// int[][][][] data = new int[documentsSize][][][];
List<int[][][]> data = new ArrayList<>();
List<double[][][]> featureVal = new ArrayList<>();
// first index is the number of the document
// second index is the position in the document
// element in labels[i][j] is the index of the correct label (if it exists)
// at position j in document i
// int[][] labels = new int[documentsSize][];
List<int[]> labels = new ArrayList<>();
int numDatums = 0;
for (List<IN> doc : documents) {
Triple<int[][][], int[], double[][][]> docTriple = documentToDataAndLabels(doc);
data.add(docTriple.first());
labels.add(docTriple.second());
if (flags.useEmbedding)
featureVal.add(docTriple.third());
numDatums += doc.size();
}
log.info("numClasses: " + classIndex.size() + ' ' + classIndex);
log.info("numDocuments: " + data.size());
log.info("numDatums: " + numDatums);
log.info("numFeatures: " + featureIndex.size());
printFeatures();
double[][][][] featureValArr = null;
if (flags.useEmbedding)
featureValArr = featureVal.toArray(new double[data.size()][][][]);
return new Triple<>(
data.toArray(new int[data.size()][][][]),
labels.toArray(new int[labels.size()][]),
featureValArr);
}
/**
* Convert an ObjectBank to corresponding collection of data features and
* labels. This version is used at test time.
*
* @return A List of pairs, one for each document, where the first element is
* an int[][][] representing the data and the second element is an
* int[] representing the labels.
*/
public List<Triple<int[][][], int[], double[][][]>> documentsToDataAndLabelsList(Collection<List<IN>> documents) {
int numDatums = 0;
List<Triple<int[][][], int[], double[][][]>> docList = new ArrayList<>();
for (List<IN> doc : documents) {
Triple<int[][][], int[], double[][][]> docTriple = documentToDataAndLabels(doc);
docList.add(docTriple);
numDatums += doc.size();
}
log.info("numClasses: " + classIndex.size() + ' ' + classIndex);
log.info("numDocuments: " + docList.size());
log.info("numDatums: " + numDatums);
log.info("numFeatures: " + featureIndex.size());
return docList;
}
protected void printFeatures() {
if (flags.printFeatures == null) {
return;
}
try {
String enc = flags.inputEncoding;
if (flags.inputEncoding == null) {
log.info("flags.inputEncoding doesn't exist, using UTF-8 as default");
enc = "UTF-8";
}
PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream("features-" + flags.printFeatures
+ ".txt"), enc), true);
for (String feat : featureIndex) {
pw.println(feat);
}
pw.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
/**
* This routine builds the {@code labelIndices} which give the
* empirically legal label sequences (of length (order) at most
* {@code windowSize}) and the {@code classIndex}, which indexes
* known answer classes.
*
* @param ob The training data: Read from an ObjectBank, each item in it is a
* {@code List<CoreLabel>}.
*/
protected void makeAnswerArraysAndTagIndex(Collection<List<IN>> ob) {
boolean useFeatureCountThresh = flags.featureCountThresh > 1;
Set<String>[] featureIndices = new HashSet[windowSize];
Map<String, Integer>[] featureCountIndices = null;
for (int i = 0; i < windowSize; i++) {
featureIndices[i] = Generics.newHashSet();
}
if (useFeatureCountThresh) {
featureCountIndices = new HashMap[windowSize];
for (int i = 0; i < windowSize; i++) {
featureCountIndices[i] = Generics.newHashMap();
}
}
labelIndices = new ArrayList<>(windowSize);
for (int i = 0; i < windowSize; i++) {
labelIndices.add(new HashIndex<>());
}
Index<CRFLabel> labelIndex = labelIndices.get(windowSize - 1);
if (classIndex == null)
classIndex = new HashIndex<>();
// classIndex.add("O");
classIndex.add(flags.backgroundSymbol);
Set<String>[] seenBackgroundFeatures = new HashSet[2];
seenBackgroundFeatures[0] = Generics.newHashSet();
seenBackgroundFeatures[1] = Generics.newHashSet();
int wordCount = 0;
if (flags.labelDictionaryCutoff > 0) {
this.labelDictionary = new LabelDictionary();
}
for (List<IN> doc : ob) {
if (flags.useReverse) {
Collections.reverse(doc);
}
// create the full set of labels in classIndex
// note: update to use addAll later
for (IN token : doc) {
wordCount++;
String ans = token.get(CoreAnnotations.AnswerAnnotation.class);
if (ans == null || ans.isEmpty()) {
throw new IllegalArgumentException("Word " + wordCount + " (\"" + token.get(CoreAnnotations.TextAnnotation.class) + "\") has a blank answer");
}
classIndex.add(ans);
if (labelDictionary != null) {
String observation = token.get(CoreAnnotations.TextAnnotation.class);
labelDictionary.increment(observation, ans);
}
}
for (int j = 0, docSize = doc.size(); j < docSize; j++) {
CRFDatum<List<String>, CRFLabel> d = makeDatum(doc, j, featureFactories);
labelIndex.add(d.label());
List<List<String>> features = d.asFeatures();
for (int k = 0, fSize = features.size(); k < fSize; k++) {
Collection<String> cliqueFeatures = features.get(k);
if (k < 2 && flags.removeBackgroundSingletonFeatures) {
String ans = doc.get(j).get(CoreAnnotations.AnswerAnnotation.class);
boolean background = ans.equals(flags.backgroundSymbol);
if (k == 1 && j > 0 && background) {
ans = doc.get(j - 1).get(CoreAnnotations.AnswerAnnotation.class);
background = ans.equals(flags.backgroundSymbol);
}
if (background) {
for (String f : cliqueFeatures) {
if (useFeatureCountThresh) {
if (!featureCountIndices[k].containsKey(f)) {
if (seenBackgroundFeatures[k].contains(f)) {
seenBackgroundFeatures[k].remove(f);
featureCountIndices[k].put(f, 1);
} else {
seenBackgroundFeatures[k].add(f);
}
}
} else {
if (!featureIndices[k].contains(f)) {
if (seenBackgroundFeatures[k].contains(f)) {
seenBackgroundFeatures[k].remove(f);
featureIndices[k].add(f);
} else {
seenBackgroundFeatures[k].add(f);
}
}
}
}
} else {
seenBackgroundFeatures[k].removeAll(cliqueFeatures);
if (useFeatureCountThresh) {
Map<String, Integer> fCountIndex = featureCountIndices[k];
for (String f: cliqueFeatures) {
if (fCountIndex.containsKey(f))
fCountIndex.put(f, fCountIndex.get(f)+1);
else
fCountIndex.put(f, 1);
}
} else {
featureIndices[k].addAll(cliqueFeatures);
}
}
} else {
if (useFeatureCountThresh) {
Map<String, Integer> fCountIndex = featureCountIndices[k];
for (String f: cliqueFeatures) {
if (fCountIndex.containsKey(f))
fCountIndex.put(f, fCountIndex.get(f)+1);
else
fCountIndex.put(f, 1);
}
} else {
featureIndices[k].addAll(cliqueFeatures);
}
}
}
}
if (flags.useReverse) {
Collections.reverse(doc);
}
}
if (useFeatureCountThresh) {
int numFeatures = 0;
for (int i = 0; i < windowSize; i++) {
numFeatures += featureCountIndices[i].size();
}
log.info("Before feature count thresholding, numFeatures = " + numFeatures);
for (int i = 0; i < windowSize; i++) {
for(Iterator<Map.Entry<String, Integer>> it = featureCountIndices[i].entrySet().iterator(); it.hasNext(); ) {
Map.Entry<String, Integer> entry = it.next();
if(entry.getValue() < flags.featureCountThresh) {
it.remove();
}
}
featureIndices[i].addAll(featureCountIndices[i].keySet());
featureCountIndices[i] = null;
}
}
int numFeatures = 0;
for (int i = 0; i < windowSize; i++) {
numFeatures += featureIndices[i].size();
}
log.info("numFeatures = " + numFeatures);
featureIndex = new HashIndex<>();
map = new int[numFeatures];
if (flags.groupByFeatureTemplate) {
templateGroupIndex = new HashIndex<>();
featureIndexToTemplateIndex = new HashMap<>();
}
for (int i = 0; i < windowSize; i++) {
Index<Integer> featureIndexMap = new HashIndex<>();
featureIndex.addAll(featureIndices[i]);
for (String str : featureIndices[i]) {
int index = featureIndex.indexOf(str);
map[index] = i;
featureIndexMap.add(index);
// grouping features by template
if (flags.groupByFeatureTemplate) {
Matcher m = suffixPatt.matcher(str);
String groupSuffix = "NoTemplate";
if (m.matches()) {
groupSuffix = m.group(1);
}
groupSuffix += "-c:"+i;
int groupIndex = templateGroupIndex.addToIndex(groupSuffix);
featureIndexToTemplateIndex.put(index, groupIndex);
}
}
// todo [cdm 2014]: Talk to Mengqiu about this; it seems like it only supports first order CRF
if (i == 0) {
nodeFeatureIndicesMap = featureIndexMap;
// log.info("setting nodeFeatureIndicesMap, size="+nodeFeatureIndicesMap.size());
} else {
edgeFeatureIndicesMap = featureIndexMap;
// log.info("setting edgeFeatureIndicesMap, size="+edgeFeatureIndicesMap.size());
}
}
if (flags.numOfFeatureSlices > 0) {
log.info("Taking " + flags.numOfFeatureSlices + " out of " + flags.totalFeatureSlice + " slices of node features for training");
pruneNodeFeatureIndices(flags.totalFeatureSlice, flags.numOfFeatureSlices);
}
if (flags.useObservedSequencesOnly) {
for (int i = 0, liSize = labelIndex.size(); i < liSize; i++) {
CRFLabel label = labelIndex.get(i);
for (int j = windowSize - 2; j >= 0; j--) {
label = label.getOneSmallerLabel();
labelIndices.get(j).add(label);
}
}
} else {
for (int i = 0; i < labelIndices.size(); i++) {
labelIndices.set(i, allLabels(i + 1, classIndex));
}
}
if (VERBOSE) {
for (int i = 0, fiSize = featureIndex.size(); i < fiSize; i++) {
System.out.println(i + ": " + featureIndex.get(i));
}
}
if (labelDictionary != null) {
labelDictionary.lock(flags.labelDictionaryCutoff, classIndex);
}
}
protected static Index<CRFLabel> allLabels(int window, Index<String> classIndex) {
int[] label = new int[window];
// cdm 2005: array initialization isn't necessary: JLS (3rd ed.) 4.12.5
// Arrays.fill(label, 0);
int numClasses = classIndex.size();
Index<CRFLabel> labelIndex = new HashIndex<>();
OUTER: while (true) {
CRFLabel l = new CRFLabel(label);
labelIndex.add(l);
int[] label1 = new int[window];
System.arraycopy(label, 0, label1, 0, label.length);
label = label1;
for (int j = 0; j < label.length; j++) {
label[j]++;
if (label[j] >= numClasses) {
label[j] = 0;
if (j == label.length - 1) {
break OUTER;
}
} else {
break;
}
}
}
return labelIndex;
}
/**
* Makes a CRFDatum by producing features and a label from input data at a
* specific position, using the provided factory.
*
* @param info The input data. Particular feature factories might look for arbitrary keys in the IN items.
* @param loc The position to build a datum at
* @param featureFactories The FeatureFactories to use to extract features
* @return The constructed CRFDatum
*/
public CRFDatum<List<String>, CRFLabel> makeDatum(List<IN> info, int loc,
List<FeatureFactory<IN>> featureFactories) {
// pad.set(CoreAnnotations.AnswerAnnotation.class, flags.backgroundSymbol); // cdm: isn't this unnecessary, as this is how it's initialized in AbstractSequenceClassifier.reinit?
PaddedList<IN> pInfo = new PaddedList<>(info, pad);
ArrayList<List<String>> features = new ArrayList<>();
List<double[]> featureVals = new ArrayList<>();
// for (int i = 0; i < windowSize; i++) {
// List featuresC = new ArrayList();
// for (int j = 0; j < FeatureFactory.win[i].length; j++) {
// featuresC.addAll(featureFactory.features(info, loc,
// FeatureFactory.win[i][j]));
// }
// features.add(featuresC);
// }
// todo [cdm Aug 2012]: Since getCliques returns all cliques within its bounds, can't the for loop here be eliminated? But my first attempt to removed failed to produce identical results....
Collection<Clique> done = Generics.newHashSet();
for (int i = 0; i < windowSize; i++) {
List<String> featuresC = new ArrayList<>();
List<Clique> windowCliques = FeatureFactory.getCliques(i, 0);
windowCliques.removeAll(done);
done.addAll(windowCliques);
double[] featureValArr = null;
if (flags.useEmbedding && i == 0) { // only activated for node features
featureValArr = makeDatumUsingEmbedding(info, loc, featureFactories, pInfo, featuresC, windowCliques);
} else {
for (Clique c : windowCliques) {
for (FeatureFactory featureFactory : featureFactories) {
featuresC.addAll(featureFactory.getCliqueFeatures(pInfo, loc, c)); //todo useless copy because of typing reasons
}
}
}