-
Notifications
You must be signed in to change notification settings - Fork 2
/
role.py
executable file
·1806 lines (1490 loc) · 76.5 KB
/
role.py
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
# -*- coding: utf-8 -*-
# role.py
# rewrite of term_verb_count focusing on role detection rather than mutual information
# directory structure
# /home/j/anick/patent-classifier/ontology/creation/data/patents/ln-us-14-health/data/tv/act
# <root>/<corpus>/data/tv
# <year>.tf, terms, feats
# <year>.<act|pn>.tfc, tc, tcs, fc, fc_uc, fc_prob, fc_cat_prob, fc_kl,
# <year>.<act|pn>.cat.w<cutoff>.a, c, t, p, n
# TODO: add codecs to all writes
"""
Enclosed is documententation for preparing files to run role/polarity NB
Summary: The goal is to label NP's within a patent domain/year with one of the high level
"ACT" roles: attribute, component, task. Then to label the attributes with their polarity
(positive or negative). Input is two generic feature seed sets and the feature data from
our chunker for the domain/year.
The generic feature seed set is used to generate a set of labeled NP's in each new domain.
By default, we choose as training terms any NP's which occur with at least 2 labeled feature
occurrences and for which all labels are the same.
The resulting terms are then used to estimate parameters for NB classifier. We could also
try using them as a maxent training set, perhaps using the terms which contain a mix of feature
types as "other".
Open issues:
As of 7/9/2014 PGA
1. For polarity, we need a way to distinguish neutral attributes
2. It would be useful to normalize attributes syntactically, so that attributes with a
slot filler ("speed of the cpu") could be recognized as the same as NN compounds ("cpu speed").
Currently we lose the filler in the first case. However, we may not currently keep enough
info in the feature file to do this (as we only keep the head noun of phrases in a dependency
relationship).
3. Need to test on more domains
4. Need a larger evaluation, containing more examples of A and T, in order to compare alternative
variants, such as more/less restrictive cutoffs for the classifier categories. e.g. if scores
are very close, is it better to count polarity as neutral or to assume ambiguity between T and C?
Seed features are in code_dir as
seed.act.en.dat : ACT seed features
seed.pn.en.dat : Polarity seed features
canonicalized versions (converted from the above using canon_seed_set.py):
seed.pn.en.canon.dat
seed.act.en.canon.dat
########
function tf2tfc(corpus_root, corpus, year, fcat_file, cat_list, cat_type, subset):
cat_type: act, pn
fcat_file: no longer used
cat_list [a, c, t] or [p, n]
subset "a" (for attribute in polarity classification or "" for none, in ACT classification)
Input: .tf term + feature cooccurrences for a domain and year
output
<cat_type>.tfc: term feature category count
<cat_type>.tc: term category term_category_pair_frequency term_frequency probability
Note that a term can appear in multiple categories here.
########
function tc2tcs(corpus_root, corpus, year, min_prob, min_pair_freq, cat_type, subset)
min_prob : minimum class probability to select term as a seed for the class
1.0 means all features for this term are of the same class
min_pair_freq : minimum frequency of co-occurrence of term + feature
(e.g. 2. There must be 2 occurrences of the term and feature to use this feature as a diagnostic)
cat_type : act or pn
subset : a or ""
Input: .tc
Output:
<cat_type>.tcs : term category term_category_pair_count prob - these are seed terms for Naive Bayes training
#########
function: tcs2fc(corpus_root, corpus, year, cat_type, subset)
Input: .tcs, .tf
Output:
<cat_type>.fc : feature category
This contains one line for each occurrence of a feature with a term categorized in the seed term file (.tcs)
Thus the same feature can occur multiple times, possibly with different categories.
########
script: run_fc2fcuc.sh corpus_root corpus start_year end_year cat_type subset
Input: .fc
Output: .fc_uc feature category count
This just sums the count of feature category occurrences.
The same feature may appear with multiple categories.
#########
function: fcuc2attrs corpus_root, corpus, year, cat_type, subset
input: .fc_uc
output: .attrs attr max_cat total_count
Do feature selection on possible attributes, using a frequency cut-off and caterogy specificity cut-off. We
want to use as attributes only those terms which are very unevenly distributed among categories., e.g. 80% of
terms associated with the feaure are in the same category.
#########
function: fcuc2fcprob(corpus_root, corpus, year, cat_list, cat_type, subset)
Input: .fc_uc, .tcs
Output:
.fc_prob category term_cat_frequency cat_prob
.cat_prob feature category feature_category_pair_frequency feature_freq category_given_feature feature_given_category
.fc_kl feature, max_letter, max_cat, next_cat, feature_freq, kld, lcgf_prob_string, lfgc_prob_string
where max_letter is the highest scoring category, max_cat, next_cat are the direction of the divergence for the most divergent categories (written as <cat><+|->
By sorting on divergence(kld), we can see the effect of features compared to expected values of the prob distribution.
At this point we have all the files we need to run naive bayes (functions in nbayes.py)
"""
import pdb
import re
import glob
import os
import sys
import log
import math
import collections
from collections import defaultdict
import codecs
import putils
import pnames
import pickle
import roles_config
import prepare_mallet
import tf
# move corpus_root and code_root to a configuration parameter
#code_root = "/home/j/anick/patent-classifier/ontology/roles"
code_root = roles_config.CODE_ROOT
#corpus_root = "/home/j/anick/patent-classifier/ontology/creation/data/patents"
#corpus_root = "/home/j/anick/patent-classifier/ontology/roles/data/patents"
corpus_root = roles_config.CORPUS_ROOT
# pattern can contain alpha or blank, must be length >=2
re_alpha_phrase = re.compile('^[a-z ]{2,}$')
def alpha_phrase_p(term):
mat = bool(re_alpha_phrase.search(term))
return(mat)
# Given a set of terms, return a set of all pairs of terms, in which each pair is
# in alphabetical order.
def set2pairs_alpha(term_set):
l_pairs = []
l_sorted_terms = sorted(term_set)
while len(l_sorted_terms) > 1:
term1 = l_sorted_terms.pop(0)
for term2 in l_sorted_terms:
l_pairs.append(term1 + "|" + term2)
return(l_pairs)
# filename creator, based on naming conventions
"""
/home/j/anick/patent-classifier/ontology/creation/data/patents/ln-us-all-600k/data/tv
1997.act.cat.w0.2 => 1997.act.cat.w0.2
1997.act.cat.w0.3
1997.act.fc => 1997.f.act.fc
1997.act.fc.cat_prob => 1997.a.act.cat_prob
1997.act.fc.kl => 1997.a.act.fc_kl
1997.act.fc.prob => 1997.a.act.fc_prob
1997.act.fc.uc => 1997.a.act.fc_uc
1997.act.tc => 1997.a.act.tc
1997.act.tcs
1997.act.tfc
1997.feats => 1997.feats
1997.terms => 1997.terms
1997.tf = > 1997.tf
1997.tf.a => 1997.a.tf
1997.tf.t => 1997.t.tf
---
1997.act.fc => 1997.a.pn.fc
"""
# for creating a cat file_type based on a given cutoff value (e.g. "0.1")
def cat_cutoff_file_type(cutoff):
file_type = "cat.w" + str(cutoff)
return file_type
# K-L Divergence of two probability distributions, passed
# in as lists of probabilities.
# plist1 and plist2 must be the same length.
# plist2 should never contain a 0 probability
# plist2 is the unconditional prob for each category, as stored in
# 1997.fc.cat_prob.
# plist1 can contain a 0
def kl_div(plist1, plist2):
#pdb.set_trace()
div = 0
i = 0
while i < len(plist1):
if plist1[i] == 0:
div = div + 0
else:
# math.log with one argument computes the natural log
div = div + (math.log(plist1[i]/plist2[i])) * plist1[i]
i += 1
return(div)
def test_kl():
# totals in 1997
p2 = [0.020546, 0.885152, 0.020934, 0.073368]
# "comprises" in 1997
p_comprises = [0.000908, 0.988193, 0.000454, 0.010445]
p_having = [0.035375, 0.906816, 0.024590, 0.033218]
p_c = [0, 1, 0, 0]
p_a = [1, 0, 0, 0]
p_o = [0, 0, 1, 0]
p_t = [0, 0, 0, 1]
print "comprises: %f" % kl_div(p_comprises, p2)
print "having: %f" % kl_div(p_having, p2)
print "a,c,o,t: %f, %f, %f, %f" % (kl_div(p_a, p2), kl_div(p_c, p2), kl_div(p_o, p2), kl_div(p_t, p2))
# The list of files is taken
# to be all the files in a given directory.
# Each line in a file contains a term, a verb, and a count.
# creates pair_counts (document frequency of each pair), mi in outroot/year
# We assume inroot/year and outroot have been checked to exist at this point
# outfilename will the be value of the year
# convert term feature (.tf) info to term category info (.tc)
# also create .tfc (term, feature, cat)
def tf2tfc(corpus_root, corpus, year, fcat_file, cat_list, cat_type, subset):
yearfilename = str(year)
year_cat_name = yearfilename + "." + cat_type
# count of number of docs a term pair cooccurs in
d_pair_freq = collections.defaultdict(int)
d_term_freq = collections.defaultdict(int)
d_feature_freq = collections.defaultdict(int)
d_feature2cat = {}
# the tc means "term-category"
#infile = inroot + "/" + yearfilename + ".tf"
# note there is no cat_type in the file name for .tf file, so use ""
infile = pnames.tv_filepath(corpus_root, corpus, year, "tf" , subset, "")
"""
if subset != "":
infile = infile + "." + subset
"""
#tc_file = outroot + "/" + year_cat_name + ".tc"
tc_file = pnames.tv_filepath(corpus_root, corpus, year, "tc" , subset, cat_type)
#tfc_file = outroot + "/" + year_cat_name + ".tfc"
tfc_file = pnames.tv_filepath(corpus_root, corpus, year, "tfc" , subset, cat_type)
# load the feature categories for fcat_file
s_fcat_file = open(fcat_file)
for line in s_fcat_file:
line = line.strip()
#print "line: %s\n" % line
(fcat, feature) = line.split("\t")
# ignore categories that are not in cat_list
if fcat in cat_list:
d_feature2cat[feature] = fcat
s_fcat_file.close()
s_infile = codecs.open(infile, encoding='utf-8')
s_tfc_file = codecs.open(tfc_file, "w", encoding='utf-8')
for line in s_infile:
line = line.strip()
l_fields = line.split("\t")
term = l_fields[0]
feature = l_fields[1]
count = int(l_fields[2])
# process the term files
# PGA, on reviewing this, I am not sure these sets are needed, since
# we are in a loop for a single line, so we should never have more than one
# instance of a term or feature per line.
term_set = set()
feature_set = set()
pair_set = set()
s_infile = codecs.open(infile, encoding='utf-8')
# check if the feature has a category
# and replace it with the category.
# Otherwise ignore this pair.
if d_feature2cat.has_key(feature):
cat = d_feature2cat[feature]
# .tfc file is similar to .tf but only contains lines for labeled features and adds the category label
s_tfc_file.write("%s\t%s\t%s\t%i\n" % (term, feature, cat, count))
# record occurrences of terms and features within this doc
term_set.add(term)
feature_set.add(feature)
pair = term + "\t" + cat
pair_set.add(pair)
#print "[for .tfc]term_set len: %i, pair_set len: %i" % (len(term_set), len(pair_set))
s_infile.close()
# increment the doc_freq for terms and verbs in the doc
# By making the list a set, we know we are only counting each term or verb once
# per document
# NOTE: This may be unnecessary, since we only have one line (term) at a time at this point.
for term in term_set:
d_term_freq[term] += count
for feature in feature_set:
d_feature_freq[feature] += count
#print "d_verb_freq for %s: %i" % (verb, d_verb_freq[verb])
for pair in pair_set:
d_pair_freq[pair] += count
s_tfc_file.close()
s_tc_file = codecs.open(tc_file, "w", encoding='utf-8')
for pair in d_pair_freq.keys():
(term, cat) = pair.split("\t")
prob = float(d_pair_freq[pair]) / float(d_term_freq[term])
s_tc_file.write( "%s\t%s\t%i\t%i\t%f\n" % (term, cat, d_pair_freq[pair], d_term_freq[term], prob))
else:
pass
#print "omitting: %s, %s" % (term1, term2)
s_tc_file.close()
# generate a set of term category "seeds" for learning new diagnostic features
# .tc is of the form:
# acoustic devices c 2 2 1.000000
# As long as min_prob > .5, there will be one cat output for each term. We are simply choosing the one
# with highest probability and ignoring cases where the freq of the term feature pair <= min_pair_freq
def tc2tcs(corpus_root, corpus, year, min_prob, min_pair_freq, cat_type, subset):
# the tc means "term-category"
#infile = inroot + "/" + year_cat_name + ".tc"
infile = pnames.tv_filepath(corpus_root, corpus, year, "tc", subset, cat_type)
#outfile = outroot + "/" + year_cat_name + ".tcs"
tcs_file = pnames.tv_filepath(corpus_root, corpus, year, "tcs", subset, cat_type)
s_tcs_file = codecs.open(tcs_file, "w", encoding='utf-8')
s_infile = codecs.open(infile, encoding='utf-8')
for line in s_infile:
line = line.strip()
l_fields = line.split("\t")
term = l_fields[0]
cat = l_fields[1]
pair_count = int(l_fields[2])
prob = float(l_fields[4])
if pair_count >= min_pair_freq and prob >= min_prob:
s_tcs_file.write("%s\t%s\t%i\t%f\n" % (term, cat, pair_count, prob))
s_infile.close()
s_tcs_file.close()
# labels features found in .tf file with the category
# associated with any known seed term (in .tcs file)
def tcs2fc(corpus_root, corpus, year, cat_type, subset):
#seed_file = inroot + "/" + year_cat_name + ".tcs"
seed_file = pnames.tv_filepath(corpus_root, corpus, year, "tcs", subset, cat_type)
#term_feature_file = inroot + "/" + str(year) + ".tf"
# recall use "" for cat_type for .tf file
term_feature_file = pnames.tv_filepath(corpus_root, corpus, year, "tf", subset, "")
#outfile = outroot + "/" + year_cat_name + ".fc"
fc_file = pnames.tv_filepath(corpus_root, corpus, year, "fc", subset, cat_type)
d_seed = {}
s_fc_file = codecs.open(fc_file, "w", encoding='utf-8')
# read in all the seeds and their categories
s_seed_file = codecs.open(seed_file, encoding='utf-8')
for line in s_seed_file:
line = line.strip()
l_fields = line.split("\t")
term = l_fields[0]
cat = l_fields[1]
d_seed[term] = cat
s_seed_file.close()
#pdb.set_trace()
# create the output file of cat feature by substituting the
# category for any seed term encountered
s_term_feature_file = codecs.open(term_feature_file, encoding='utf-8')
for line in s_term_feature_file:
line = line.strip()
l_fields = line.split("\t")
term = l_fields[0]
feature = l_fields[1]
count = l_fields[2]
if d_seed.has_key(term):
cat = d_seed[term]
s_fc_file.write("%s\t%s\n" % (feature, cat))
#s_fc_file.write("%s\t%s\t%s\t%s\n" % (feature, cat, term, count))
s_term_feature_file.close()
s_fc_file.close()
# //// TBD
# attribute selection for NB classifier
def fcuc2attrs(corpus_root, corpus, year, cat_type, subset):
# We want to keep attributes for which at least 80% of the bootstrap terms are in a single category
min_cat_percent = .8
# We keep attributes which occur with at least 2 different bootstrap terms
min_diff_term_freq = 2
fc_uc_file = pnames.tv_filepath(corpus_root, corpus, year, "fc_uc", subset, cat_type)
attrs_file = pnames.tv_filepath(corpus_root, corpus, year, "attrs", subset, cat_type)
# read .fc_uc file into dictionaries
s_fc_uc_file = codecs.open(fc_uc_file, encoding='utf-8')
for line in s_fc_uc_file:
line = line.strip()
l_fields = line.split("\t")
feature = l_fields[0]
cat = l_fields[1]
count = int(l_fields[2])
# left over from copied code....///
# create a pair for dictionary key
pair = cat + "\t" + feature
pair_set.add(pair)
### /// check this logic
# increment the doc_freq for cats and features in the doc
# By making the pair list a set (above), we know we are only counting each cat or feature once
# per document
d_feature_cat_freq[cat] += count
d_feature_freq[feature] += count
d_pair_freq[pair] += count
instance_freq += count
s_fc_uc_file.close()
# convert feature category count (.fc_uc) info to feature category prob info (.fc_prob)
# cat_list is a list of category names (e.g., ["a", "c", "o", "t"]) used for computing
# K-L divergence between probability distributions. K-L div is computed between marginal probs for
# each class vs. conditional probs for each class given the feature.
# For applying Bayes rule, we also compute the log of prob of feature given a category, using +1
# smoothing.
def fcuc2fcprob(corpus_root, corpus, year, cat_list, cat_type, subset):
print "[fcuc2fcprob]cat_list: %s" % cat_list
yearfilename = str(year)
year_cat_name = yearfilename + "." + cat_type
# count of number of docs a feature-category pair cooccurs in
d_pair_freq = collections.defaultdict(int)
# accumulate feature_cat instances for each category
d_feature_cat_freq = collections.defaultdict(int)
# accumulate term_cat instances for each category
d_term_cat_freq = collections.defaultdict(int)
# accumulate freq for each feature
d_feature_freq = collections.defaultdict(int)
# overall prob for each category
d_cat_prob = collections.defaultdict(int)
# we will need a list of overall probs for input into kl_div
cat_prob_list = []
# capture the number of labeled instances to compute prior prob for each category
instance_freq = 0
# count total number of terms (denominator in computing prior prob)
term_count = 0
smoothing_parameter = 1
min_feature_freq = 10
##fc_uc_file = inroot + "/" + year_cat_name + ".fc_uc"
fc_uc_file = pnames.tv_filepath(corpus_root, corpus, year, "fc_uc", subset, cat_type)
# output file to store prob of category given the term
##prob_file = outroot + "/" + year_cat_name + ".fc.prob"
prob_file = pnames.tv_filepath(corpus_root, corpus, year, "fc_prob", subset, cat_type)
# output file to store prior probs of each category
##cat_prob_file = outroot + "/" + year_cat_name + ".fc.cat_prob"
cat_prob_file = pnames.tv_filepath(corpus_root, corpus, year, "cat_prob", subset, cat_type)
# tcs_file contains seed term and category
tcs_file = pnames.tv_filepath(corpus_root, corpus, year, "tcs", subset, cat_type)
s_cat_prob_file = codecs.open(cat_prob_file, "w", encoding='utf-8')
#kl_file = outroot + "/" + year_cat_name + ".fc.kl"
kl_file = pnames.tv_filepath(corpus_root, corpus, year, "fc_kl", subset, cat_type)
s_kl_file = codecs.open(kl_file, "w", encoding='utf-8')
# process the pairs
cat_set = set()
feature_set = set()
pair_set = set()
# compute prior probs (using the labeled seed terms)
# (replaces older version that computed priors based on feature-cat counts)
# tcs_file is .tcs
# We treat each seed term as a "document" represented by a weighted feature vector,
# where the weight is the doc freq of the feature across all instances of the seed term.
# This is analogous to document classification, in which a doc is represented as a word vector,
# weighted by the term freq of each word in the doc.
# Thus the prior probabilities are the proportion of terms in each category relative to all terms.
s_tcs_file = codecs.open(tcs_file, encoding='utf-8')
# <term> <category> <doc frequency> <prob of ?>
# graphical timelines c 2 1.000000
for line in s_tcs_file:
line = line.strip()
l_fields = line.split("\t")
term = l_fields[0]
cat = l_fields[1]
count = int(l_fields[2])
### /// check this logic
# increment the doc_freq for the cat, based on the cat for this term
d_term_cat_freq[cat] += count
term_count += count
s_tcs_file.close()
s_prob_file = codecs.open(prob_file, "w", encoding='utf-8')
# Compute prior prob distribution of categories
num_categories = len(cat_list)
for cat in cat_list:
#print "Compute prob distribution of categories"
#pdb.set_trace()
# compute the probability of the category
cat_prob = float(d_term_cat_freq[cat]) / float(term_count)
# add prob to a list for use in kl_div
# This is our actual prob distribution of categories
cat_prob_list.append(cat_prob)
d_cat_prob[cat] = cat_prob
s_cat_prob_file.write("%s\t%i\t%f\n" % (cat, d_term_cat_freq[cat], cat_prob))
# get feature data for use in kl-div
# infile is .fc_uc
s_fc_uc_file = codecs.open(fc_uc_file, encoding='utf-8')
for line in s_fc_uc_file:
line = line.strip()
l_fields = line.split("\t")
feature = l_fields[0]
cat = l_fields[1]
count = int(l_fields[2])
# create a pair for dictionary key
pair = cat + "\t" + feature
pair_set.add(pair)
### /// check this logic
# increment the doc_freq for cats and features in the doc
# By making the pair list a set (above), we know we are only counting each cat or feature once
# per document
d_feature_cat_freq[cat] += count
d_feature_freq[feature] += count
d_pair_freq[pair] += count
instance_freq += count
s_fc_uc_file.close()
"""
# old version that computed priors using feature freq
s_prob_file = codecs.open(prob_file, "w", encoding='utf-8')
# Compute prob distribution of categories
num_categories = len(cat_list)
for cat in cat_list:
#print "Compute prob distribution of categories"
#pdb.set_trace()
# compute the probability of the category
cat_prob = float(d_cat_freq[cat]) / float(instance_freq)
# add prob to a list for use in kl_div
# This is our actual prob distribution of categories
cat_prob_list.append(cat_prob)
d_cat_prob[cat] = cat_prob
s_cat_prob_file.write("%s\t%i\t%f\n" % (cat, d_cat_freq[cat], cat_prob))
"""
"""
# old version that does not compute kl-divergence
for pair in d_pair_freq.keys():
l_pair = pair.split("\t")
cat = l_pair[0]
feature = l_pair[1]
# prob of category given the feature
cgf_prob = float(d_pair_freq[pair]) / float(d_feature_freq[feature])
# prob of feature given the category
fgc_prob = float(d_pair_freq[pair]) / float(d_cat_freq[cat])
"""
# num_features is needed to compute smoothing in denominator of fgc probabilities
num_features = len(d_feature_freq.keys())
# track the total prob of fgc for each cat as a sanity check
d_cum_fgc_prob = collections.defaultdict(float)
for feature in d_feature_freq.keys():
# accumulate probs for each cat
cgf_prob_list = []
fgc_prob_list = []
cgf_prob_string = ""
fgc_prob_string = ""
# log of probs
lcgf_prob_list = []
lfgc_prob_list = []
lcgf_prob_string = ""
lfgc_prob_string = ""
feature_freq = d_feature_freq[feature]
# keep category and prob to sort to find max prob category and runner up
fcat_prob_list = []
for cat in cat_list:
# create the key needed for d_pair_freq
pair = cat + "\t" + feature
# prob of category given the feature
# We'll do +1 smoothing to avoid 0 probs.
#pdb.set_trace()
cgf_prob = float(d_pair_freq[pair] + smoothing_parameter) / float(feature_freq + (smoothing_parameter * num_categories))
lcgf_prob = math.log(cgf_prob)
fcat_prob_list.append([cat, cgf_prob])
cgf_prob_list.append(cgf_prob)
# smoothing denominator should include smoothing parameter (e.g. 1) times the number of observations.
# Number of observations is the number of types in the numerator.
# prob of feature given the category
fgc_prob = float(d_pair_freq[pair] + smoothing_parameter) / float(d_feature_cat_freq[cat] + (smoothing_parameter * num_features))
# accumulate the probs over all features to verify its total to 1.0
d_cum_fgc_prob[cat] += fgc_prob
lfgc_prob = math.log(fgc_prob)
# prob_list aligns with cats in cat_list
fgc_prob_list.append(fgc_prob)
lfgc_prob_list.append(lfgc_prob)
# write out each feature cat pair info separately
s_prob_file.write("%s\t%s\t%i\t%i\t%f\t%f\n" % (feature, cat, d_pair_freq[pair], feature_freq, cgf_prob, fgc_prob))
# also capture the conditional probs in a string for storage as a field in output file
cgf_prob_string = cgf_prob_string + " " + str(cgf_prob)
fgc_prob_string = fgc_prob_string + " " + str(fgc_prob)
lcgf_prob_string = lcgf_prob_string + " " + str(lcgf_prob)
lfgc_prob_string = lfgc_prob_string + " " + str(lfgc_prob)
# also compute kl divergence and write a summary line for each feature
#pdb.set_trace()
# if there are not any instances of a category in the .fc file, then we'll get a 0 in
#the cat_prob_list. Since we cannot divide by 0, print a warning and exit.
if 0 in cat_prob_list:
print "[fcuc2fcprob]Some category does not appear in the .fc file. Exiting. cat_prob_list: %s" % cat_prob_list
exit
kld = kl_div(cgf_prob_list, cat_prob_list)
# compute max and runner up prob categories
fcat_prob_list.sort(putils.list_element_2_sort)
#print "fcat_prob_list: %s" % fcat_prob_list
#pdb.set_trace()
max_cat = fcat_prob_list[0][0]
# keep the letter of the highest prob class for printing out.
# Note that the max class prob could be lower than expected prob if there are more
# than 2 classes. That is, the class could have the highest prob for this feature,
# but its probability could be lower than expected by chance. Hence we add a + or -
# symbol after max_cat to indicate this in the output
max_letter = max_cat
max_score = fcat_prob_list[0][1]
if max_score > d_cat_prob[max_cat]:
max_cat = max_cat + "+"
else:
max_cat = max_cat + "-"
next_cat = fcat_prob_list[1][0]
next_score = fcat_prob_list[1][1]
if next_score > d_cat_prob[next_cat]:
next_cat = next_cat + "+"
else:
next_cat = next_cat + "-"
"""
# if the runner-up exceeds a threshold, print it as well
if fcat_prob_list[1][1] >= .2:
next_cat = fcat_prob_list[1][0]
"""
if feature_freq >= min_feature_freq:
#print "%s\t%i\t%f\t%s\t%s" % (feature, feature_freq, kld, cgf_prob_string, fgc_prob_string)
s_kl_file.write("%s\t%s\t%s %s\t%i\t%f\t%s\t%s\n" % (feature, max_letter, max_cat, next_cat, feature_freq, kld, lcgf_prob_string, lfgc_prob_string))
for cat in d_cum_fgc_prob.keys():
print "[fcuc2fcprob]category: %s, cum_fgc_prob (should total to 1.0): %f" % (cat, d_cum_fgc_prob[cat])
s_prob_file.close()
s_cat_prob_file.close()
s_kl_file.close()
"""
# moved to tf.py
#---
# Create a single file of term feature count for each year (from the .xml extracts of phr_feats data)
# role.run_dir2features_count()
# modified 3/3/14 to take parameters from run_tf_steps
def run_dir2features_count(inroot, outroot, start_range, end_range):
#inroot = "/home/j/anick/patent-classifier/ontology/creation/data/patents/cs_500k/data/m1_term_verb_tas"
#inroot = "/home/j/anick/patent-classifier/ontology/creation/data/patents/ln-us-all-600k/data/term_features"
#outroot = "/home/j/anick/patent-classifier/ontology/creation/data/patents/ln-us-all-600k/data/tv"
#inroot = "/home/j/anick/patent-classifier/ontology/creation/data/patents/wos-cs-520k/data/term_features"
#outroot = "/home/j/anick/patent-classifier/ontology/creation/data/patents/wos-cs-520k/data/tv"
# cs
#inroot = "/home/j/anick/patent-classifier/ontology/creation/data/patents/ln-us-cs-500k/data/term_features"
#outroot = "/home/j/anick/patent-classifier/ontology/creation/data/patents/ln-us-cs-500k/data/tv"
# chemical
#inroot = "/home/j/anick/patent-classifier/ontology/creation/data/patents/ln-us-12-chemical/data/term_features"
#outroot = "/home/j/anick/patent-classifier/ontology/creation/data/patents/ln-us-12-chemical/data/tv"
# health
#inroot = "/home/j/anick/patent-classifier/ontology/creation/data/patents/ln-us-14-health/data/term_features"
#outroot = "/home/j/anick/patent-classifier/ontology/creation/data/patents/ln-us-14-health/data/tv"
# test (4 files from health 1997)
#inroot = "/home/j/anick/patent-classifier/ontology/creation/data/patents/test/data/term_features"
#outroot = "/home/j/anick/patent-classifier/ontology/creation/data/patents/test/data/tv"
# Chinese cs
#inroot = "/home/j/anick/patent-classifier/ontology/creation/data/patents/ln-cn-all-600k/data/term_features"
#outroot = "/home/j/anick/patent-classifier/ontology/creation/data/patents/ln-cn-all-600k/data/tv"
print "Output dir: %s" % outroot
# range should be start_year and end_year + 1
#for int_year in range(1981, 2008):
#for int_year in range(1995, 2008):
#for int_year in range(1997, 1998):
for int_year in range(start_range, end_range):
year = str(int_year)
inroot_year = inroot + "/" + year
print "Processing dir: %s" % inroot_year
dir2features_count(inroot_year, outroot, year)
print "Completed: %s" % year
"""
# moved here from nbayes.py and adapted to use output of mallet
# role.run_filter_tf_file("ln-us-A21-computers_test_pa", 2002, "500")
def run_filter_tf_file(corpus, year, cutoff="500"):
# corpus_root = "/home/j/anick/patent-classifier/ontology/creation/data/patents/"
#tv_loc = "/data/tv/"
#tv_root = outroot + corpus + tv_loc
#year = str(year)
# e.g., act file: 1997.act.cat.w0.2
#act_file = tv_root + year + ".act.cat.w" + cutoff
#act_file = pnames.tv_filepath(corpus_root, corpus, year, file_type, subset, cat_type=""):
#print "[run_filter_tf_file]Creating .tf.a and .tf.t from %s" % act_file
#filter_tf_file(tv_root, year, act_file)
act_file_type = cat_cutoff_file_type(cutoff)
filter_tf_file(corpus_root, corpus, year, act_file_type)
# create a.tf and t.tf by filtering out any terms not labeled as a or t in
# <year>.act.cat.w0.2
# We will use the output of the mallet NB classifier, formatted into lines of the form:
# term cat num_features score score {feature:count}*
# Currently the file is called:
# <year>res_summary.<num_attrs>
# where num_attrs is the number of attributes selected after pruning by info-gain.
# e.g. 2002.res_summary.500
# 12/9/14 using data computed externally and placed here: /home/j/llc/gititkeh/malletex/cs_tv_pre_20140705
# and renamed and copied into local directory.
# We renamed the file to match our old naming convetions:
# $ mv 2002.res_summary.500 2002.act.cat.w500
# so act_file_type is "cat.w500"
# min_feats is the minimum number of relevant features the term has. If it is 0, we
# may be using solely the prior probs to classify the term. So we often choose 1, meaning
# there is at least one feature used to set posterior prob of the category.
# role.filter_tf_file
def filter_tf_file(corpus_root, corpus, year, act_file_type, min_feats=1):
#tf_file = tv_root + str(year) + ".tf"
tfa_subset = "a"
tft_subset = "t"
tf_file = pnames.tv_filepath(corpus_root, corpus, year, "tf", "", cat_type="")
tfa_file = pnames.tv_filepath(corpus_root, corpus, year, "tf", tfa_subset, cat_type="")
tft_file = pnames.tv_filepath(corpus_root, corpus, year, "tf", tft_subset, cat_type="")
print "[filter_tf_file]Creating tfa_file: %s" % tfa_file
print "[filter_tf_file]Creating tft_file: %s" % tft_file
act_file = pnames.tv_filepath(corpus_root, corpus, year, act_file_type, "", "act")
print "[filter_tf_file]Reading from act_file: %s" % act_file
s_tfa = codecs.open(tfa_file, "w", encoding='utf-8')
s_tft = codecs.open(tft_file, "w", encoding='utf-8')
d_term2cat = defaultdict(str)
# store the category of each term labeled a and t
s_act_file = codecs.open(act_file, encoding='utf-8')
for line in s_act_file:
line = line.strip("\n")
l_fields = line.split("\t")
term = l_fields[0]
cat = l_fields[1]
num_feats = l_fields[2]
# ignore terms that don't have the minimum number of associated features
if num_feats >= min_feats:
d_term2cat[term] = cat
#print "term: %s, cat: %s" % (term, cat)
s_act_file.close()
# create subset files of .tf for the a and t terms
s_tf_file = codecs.open(tf_file, encoding='utf-8')
for line in s_tf_file:
# don't bother to strip off newline
# just grab the term
term = line.split("\t")[0]
cat = d_term2cat[term]
if cat == "a":
s_tfa.write(line)
elif cat == "t":
s_tft.write(line)
s_tf_file.close()
s_tfa.close()
s_tft.close()
# term feature to term feature category for terms whose feature appears in our seed list
# role.run_tf2tfc()
def run_tf2tfc(corpus_root, corpus, start_range, end_range, fcat_file, cat_list, cat_type, subset):
#inroot = "/home/j/anick/patent-classifier/ontology/creation/data/patents/ln-us-all-600k/data/tv"
#inroot = "/home/j/anick/patent-classifier/ontology/creation/data/patents/wos-cs-520k_old/data/tv"
#inroot = "/home/j/anick/patent-classifier/ontology/creation/data/patents/ln-us-cs-500k/data/tv"
#fcat_file = "/home/j/anick/patent-classifier/ontology/creation/feature.cat.en.canon.dat"
#fcat_file = "/home/j/anick/patent-classifier/ontology/creation/seed.cat.en.canon.dat"
# category r and n are useful but overlap with other cats. Better to work with them separately.
#cat_list = ["a", "b", "c", "p", "t", "o"]
#for int_year in range(1997, 1998):
for int_year in range(start_range, end_range):
year = str(int_year)
print "[run_tf2tfc]Processing dir: %s" % year
# cat_list allows discretion over the category set
tf2tfc(corpus_root, corpus, year, fcat_file, cat_list, cat_type, subset)
print "[run_tf2tfc]Completed: %s.tc" % (year)
# term category to seed terms
# role.run_tc2tcs()
def run_tc2tcs(corpus_root, corpus, start_range, end_range, cat_type, subset):
#inroot = "/home/j/anick/patent-classifier/ontology/creation/data/patents/ln-us-all-600k/data/tv"
#inroot = "/home/j/anick/patent-classifier/ontology/creation/data/patents/wos-cs-520k_old/data/tv"
#inroot = "/home/j/anick/patent-classifier/ontology/creation/data/patents/ln-us-cs-500k/data/tv"
#outroot = inroot
# cutoffs
# changed from .7 to 1 to avoid getting a lot of possibly ambiguous common terms into the seed list for training
min_prob = 1
# changed from 1 to 2 on 3/8/14 PGA. Files generated before this date will have used 1.
# changed to 3 on 3/11/14
# changed to 2 on 3/12 to boost output after raising min_prob to 1
min_pair_freq = 2
# note: To explore the actual term sets produced by different cutoffs, do e.g.
# cat 1997.act.tc | python $CDIR/filtergt.py 5 1 | python $CDIR/filtergt.py 4 2 | more
# the .tc file has lines of the form:
# signal quality a 3 3 1.000000
# where field 3 is the # of term-feat pairs that match the category (a)
# and field 4 is the # of term-feat pairs matching any category.
# field 5 is the probability of the category(a) given the features associated with "signal quality"
# In this case, since the prob is 1, fields 3 and 4 are equal.
#for int_year in range(1997, 1998):
for int_year in range(start_range, end_range):
year = str(int_year)
print "[run_tc2tcs]Processing dir: %s" % year
tc2tcs(corpus_root, corpus, year, min_prob, min_pair_freq, cat_type, subset)
#print "[run_tc2tcs]Completed: %s.st in %s" % (year, outroot)
# use the seed terms to create a file of feature category pairs. That is, for
# each line containing a seed term, replace it with the category.
# role.run_tcs2fc()
def run_tcs2fc(corpus_root, corpus, start_range, end_range, cat_type, subset):
#inroot = "/home/j/anick/patent-classifier/ontology/creation/data/patents/ln-us-all-600k/data/tv"
#inroot = "/home/j/anick/patent-classifier/ontology/creation/data/patents/ln-us-cs-500k/data/tv"
#outroot = inroot
for int_year in range(start_range, end_range):
year = str(int_year)
print "[run_tcs2fc]Processing dir: %s" % year
tcs2fc(corpus_root, corpus, year, cat_type, subset)
#print "[run_tcs2fc]Completed: %s.fc in %s" % (year, outroot)
# Generate probability for each feature cat combination
# Input file is the result of a uc on the .fc file
# First run:
# sh run_fc2fcuc.sh
# role.run_fcuc2fcprob()
def run_fcuc2fcprob(corpus_root, corpus, start_range, end_range, cat_list, cat_type, subset):
#inroot = "/home/j/anick/patent-classifier/ontology/creation/data/patents/ln-us-all-600k/data/tv"
#inroot = "/home/j/anick/patent-classifier/ontology/creation/data/patents/ln-us-cs-500k/data/tv"
#outroot = inroot
for int_year in range(start_range, end_range):
year = str(int_year)
print "[run_fcuc2fcprob]Processing dir: %s" % year
fcuc2fcprob(corpus_root, corpus, year, cat_list, cat_type, subset)
#print "[run_fcuc2fcprob]Completed: %s.fc in %s" % (year, outroot)
def summary(term, d_term2act, d_term2pn):
if d_term2act.has_key(term):
(term, num_diagnostic_feats, num_doc_feature_instances, cat, doc_freq, score_a, score_c, score_t, feats) = d_term2act[term].split("\t")
print "ACT: %s\t%s\%s\t%s" % (term, cat, doc_freq, feats)
if d_term2pn.has_key(term):
(term, num_diagnostic_feats, num_doc_feature_instances, cat, doc_freq, score_p, score_n, feats) = d_term2pn[term].split("\t")
print "Polarity: %s\t%s\%s\t%s" % (term, cat, doc_freq, feats)
# return the cat files as dictionaries
# (d_act, d_pn) = role.get_dcats("ln-us-cs-500k", 2002)
def get_dcats(corpus, year):
d_term2act = {}
d_term2pn = {}
file_type = "cat.w0.0"
act_file = pnames.tv_filepath(corpus_root, corpus, year, file_type, "", cat_type="act")
pn_file = pnames.tv_filepath(corpus_root, corpus, year, file_type, "a", cat_type="pn")
s_act_file = codecs.open(act_file, encoding='utf-8')
for line in s_act_file:
line = line.strip("\n")
l_fields = line.split("\t")
term = l_fields[0]
d_term2act[term] = l_fields
s_act_file.close()
s_pn_file = codecs.open(pn_file, encoding='utf-8')
for line in s_pn_file:
line = line.strip("\n")
l_fields = line.split("\t")
term = l_fields[0]
d_term2pn[term] = l_fields
s_pn_file.close()
return(d_term2act, d_term2pn)
# in progress
def get_hword2label(corpus, year):
d_term2act = {}
d_term2pn = {}
file_type = "cat.w0.0"
act_file = pnames.tv_filepath(corpus_root, corpus, year, file_type, "", cat_type="act")
s_act_file = codecs.open(act_file, encoding='utf-8')
for line in s_act_file:
line = line.strip("\n")
l_fields = line.split("\t")
term = l_fields[0]
d_term2act[term] = l_fields
s_act_file.close()
# line to extract headwords
# fcpy (fuse code python) is "python /home/j/anick/patent-classifier/ontology/creation"
# fcpy="python /home/j/anick/patent-classifier/ontology/creation"
# cat 2002.terms | cut -f1 | sed 's/.* //' | sort | uniq -c | sort -nr | $fcpy/reformat_uc1.py
# 3/19/14 temporal entropy idea
# Similar to Kanhabua and Norvig use of TE in Machine Learning and Knowledge Discovery in Databases: European Conference ...
# edited by Wray Buntine, Marko Grobelnik, Dunja Mladenic, John Shawe-Taylor
# http://books.google.com/books?id=5THWkRwjZywC&pg=PA739&lpg=PA739&dq=%22temporal+entropy%22+terms&source=bl&ots=0TptVioYXD&sig=pB0ZYlF63pZfYYcC0eZc_4uSg3I&hl=en&sa=X&ei=ikMqU9TYB9SEqQGmrYGYBw&ved=0CEMQ6AEwBQ#v=onepage&q=%22temporal%20entropy%22%20terms&f=false
# Get the feats with doc freq > 1000 in 2005
# cat 2005.feats | grep prev_V= | $pgt 2 1000 |cut -f1,2 > 2005.feats.gt1000
# Get the terms with freq > 10 in 2005 (from .terms)
#cat 2005.terms | $pgt 2 10 | wc -l
# 50670
# cat 2005.terms | $pgt 2 10 | cut -f1,2 > 2005.terms.gt10
# Todo later, compare TE for c, a, t terms
# To compute TE, we'll need for each year: