-
Notifications
You must be signed in to change notification settings - Fork 21
/
evalClassification.py
4346 lines (3863 loc) · 217 KB
/
evalClassification.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
# =============================================================================
# AUSTRALIAN NATIONAL UNIVERSITY OPEN SOURCE LICENSE (ANUOS LICENSE)
# VERSION 1.3
#
# The contents of this file are subject to the ANUOS License Version 1.3
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at:
#
# https://sourceforge.net/projects/febrl/
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
# the License for the specific language governing rights and limitations
# under the License.
#
# The Original Software is: "evalClassification.py"
#
# The Initial Developer of the Original Software is:
# Dr Peter Christen (Research School of Computer Science, The Australian
# National University)
#
# Copyright (C) 2002 - 2011 the Australian National University and
# others. All Rights Reserved.
#
# Contributors:
#
# Alternatively, the contents of this file may be used under the terms
# of the GNU General Public License Version 2 or later (the "GPL"), in
# which case the provisions of the GPL are applicable instead of those
# above. The GPL is available at the following URL: http://www.gnu.org/
# If you wish to allow use of your version of this file only under the
# terms of the GPL, and not to allow others to use your version of this
# file under the terms of the ANUOS License, indicate your decision by
# deleting the provisions above and replace them with the notice and
# other provisions required by the GPL. If you do not delete the
# provisions above, a recipient may use your version of this file under
# the terms of any one of the ANUOS License or the GPL.
# =============================================================================
#
# Freely extensible biomedical record linkage (Febrl) - Version 0.4.2
#
# See: http://datamining.anu.edu.au/linkage.html
#
# =============================================================================
"""Module to evaluate the various classification techniques implemented in the
Febrl module 'classification.py'.
Uses Febrl-0.4.
Peter Christen, 2008/01/30
Defines a series of data sets, indices and comparisons, then runs them and
evaluates their linkage quality using various classifiers.
TODO:
- maybe also add sampling for training to the various classifiers
"""
# =============================================================================
# Imports go here
import logging
import os
import time
#import Gnuplot
import classification
import comparison
import dataset
import encode
import indexing
import measurements
import mymath
import output
# =============================================================================
# Various settings
do_plotting = False
do_complexity = True
n = 10 # Number of cross validation folds
do_opt_thres = True # Flags, set to True to do certain classifiers
do_svm = True
do_kmeans = True
do_ffirst = True
do_tailor = True
do_two_step_thres = True
do_two_step_near = True
do_timing = Truee
# File name for writing results to (incl. date and time)
#
result_file_name = './results/evalClassification-' + \
time.strftime('%Y%m%d-%H%M')+'.res'
progress_precentage = 10
num_random_select_iterations = 10
# Various possible deduplication indexing (blocking) techniques
#
index_dedup_block_method = ('block',)
#index_dedup_block_method = ('sort', 3)
#index_dedup_block_method = ('qgram', 2, False, 0.8)
weight_vect_dir = './weight-vectors/' # Where weight vector files are stored
# =============================================================================
def get_measures(result_list):
"""Function which calculates quality measures from raw classification
counts.
Returns accuracy, precision, recall, and f-measure values.
"""
tp, fn, fp, tn = result_list
tp = float(tp)
tn = float(tn)
fp = float(fp)
fn = float(fn)
if ((tp != 0) or (fp != 0) or (tn != 0) or (fn != 0)):
acc = (tp + tn) / (tp + fp + tn + fn)
else:
acc = 0.0
if ((tp != 0) or (fp != 0)):
prec = tp / (tp + fp)
else:
prec = 0.0
if ((tp != 0) or (fn != 0)):
reca = tp / (tp + fn)
else:
reca = 0.0
if ((prec != 0.0) or (reca != 0.0)):
fmeas = 2*(prec*reca) / (prec+reca)
else:
fmeas = 0.0
return acc, prec, reca, fmeas
# =============================================================================
# Define a project logger
my_logger = logging.getLogger() # New logger at root level
my_logger.setLevel(logging.WARNING)
#my_logger.setLevel(logging.INFO)
# =============================================================================
# Open the results file
#
res_file = open(result_file_name, 'w')
# =============================================================================
# Generate a list with information for each data set:
# 1) A tuple with the two data set objects (will be the same for deduplication)
# 2) The data set index object
# 3) A list with tuples on a field comparison selection, each having:
# a) A comment string
# b) A list with the fields used in one experiment for the function
# classification.extract_collapse()
# 4) The function to be used to check for true matches and non-matches
#
experiment_list = []
# =============================================================================
# Define original input data sets, indices and field comparisons for them
# -----------------------------------------------------------------------------
# The publicly available Census data set with synthetic personal names and
# addresses (taken from SecondString data repository).
#
# - The 'entity_id' attribute (2nd attribute) contains entity numbers.
# - No record identifer is available.
#
census_ds_A = dataset.DataSetCSV(description='Census data set A',
access_mode='read',
delimiter='\t',
rec_ident='rec_id',
header_line=False,
field_list=[('relation',0),
('entity_id',1),
('surname',2),
('given_name',3),
('middle_inital',4),
('zipcode',5),
('suburb',6)],
file_name = './data/secondstring/censusTextSegmentedA.tab')
census_ds_B = dataset.DataSetCSV(description='Census data set B',
access_mode='read',
delimiter='\t',
rec_ident='rec_id',
header_line=False,
field_list=[('relation',0),
('entity_id',1),
('surname',2),
('given_name',3),
('middle_inital',4),
('zipcode',5),
('suburb',6)],
file_name = './data/secondstring/censusTextSegmentedB.tab')
census_index_list = [[['surname', 'surname', False, False, None,
[encode.dmetaphone,3]]],
[['given_name','given_name', False, False, None,
[encode.dmetaphone,3]]],
[['surname', 'surname', False, False, 1, []],
['given_name','given_name', False, False, 1, []]],
[['zipcode', 'zipcode', False, False, None, []]],
[['suburb', 'suburb', False, False, None,
[encode.dmetaphone,3]]]]
# Exact comparison of 'relation' and 'entity_id': If 'relation' is different
# and 'entity_id' is the same it is a match, otherwise not
#
census_entity_id_exact = comparison.FieldComparatorExactString(desc = \
'entity_id_exact')
census_surname_winkler = comparison.FieldComparatorWinkler(thres=0,
desc = 'surname_winkler')
census_given_name_winkler = comparison.FieldComparatorWinkler(thres=0,
desc = 'given_name_winkler')
census_suburb_winkler = comparison.FieldComparatorWinkler(thres=0,
desc = 'suburb_winkler')
census_surname_qgram = comparison.FieldComparatorQGram(thres=0, q=2,
common_divisor='average',
desc = 'surname_qgram')
census_given_name_qgram = comparison.FieldComparatorQGram(thres=0, q=2,
common_divisor='average',
desc = 'given_name_qgram')
census_suburb_qgram = comparison.FieldComparatorQGram(thres=0, q=2,
common_divisor='average',
desc = 'suburb_qgram')
census_surname_bagdist = comparison.FieldComparatorBagDist(thres=0,
desc = 'surname_bagdist')
census_given_name_bagdist = comparison.FieldComparatorBagDist(thres=0,
desc = 'given_name_bagdist')
census_suburb_bagdist = comparison.FieldComparatorBagDist(thres=0,
desc = 'suburb_bagdist')
census_surname_lcs = comparison.FieldComparatorLCS(thres=0,
min_common_len=2,
common_divisor='average',
desc = 'surname_lcs')
census_given_name_lcs = comparison.FieldComparatorLCS(thres=0,
min_common_len=2,
common_divisor='average',
desc = 'given_name_lcs')
census_suburb_lcs = comparison.FieldComparatorLCS(thres=0,
min_common_len=2,
common_divisor='average',
desc = 'suburb_lcs')
census_middle_inital_exact = comparison.FieldComparatorExactString(desc = \
'middle_inital_exact')
census_zipcode_exact = comparison.FieldComparatorExactString(desc = \
'zipcode_exact')
census_zipcode_keydiff = comparison.FieldComparatorKeyDiff(max_key_diff=2,
desc = 'zipcode_keydiff')
census_fc_list = [(census_entity_id_exact, 'entity_id', 'entity_id'),
(census_surname_winkler, 'surname', 'surname'),
(census_given_name_winkler, 'given_name', 'given_name'),
(census_suburb_winkler, 'suburb', 'suburb'),
(census_surname_qgram, 'surname', 'surname'),
(census_given_name_qgram, 'given_name', 'given_name'),
(census_suburb_qgram, 'suburb', 'suburb'),
(census_surname_bagdist, 'surname', 'surname'),
(census_given_name_bagdist, 'given_name', 'given_name'),
(census_suburb_bagdist, 'suburb', 'suburb'),
(census_surname_lcs, 'surname', 'surname'),
(census_given_name_lcs, 'given_name', 'given_name'),
(census_suburb_lcs, 'suburb', 'suburb'),
(census_middle_inital_exact,'middle_inital','middle_inital'),
(census_zipcode_exact, 'zipcode', 'zipcode'),
(census_zipcode_keydiff, 'zipcode', 'zipcode')]
census_rec_comp = comparison.RecordComparator(census_ds_A, census_ds_B,
census_fc_list,
'Census record comparator')
# List with sub-sets of the field comparisons for experiments
#
census_sel_list = [('Winkler', [ (1,), (2,), (3,),(13,),(15,)]),
('Q-Gram', [ (4,), (5,), (6,),(13,),(15,)]),
('Bag-Distance',[ (7,), (8,), (9,),(13,),(15,)]),
('LCS', [(10,),(11,),(12,),(13,),(15,)])]
cens_bigmatch_index = indexing.BigMatchIndex(descrip = 'Census BigMatch index',
dataset1 = census_ds_A,
dataset2 = census_ds_B,
weight_vec_file = weight_vect_dir + \
'census-bigmatch-index-weight-vectors.csv',
rec_comparator = census_rec_comp,
progress=progress_precentage,
block_method = index_dedup_block_method,
index_def = census_index_list)
cens_full_index = indexing.FullIndex(description = 'Census Full index',
dataset1 = census_ds_A,
dataset2 = census_ds_B,
weight_vec_file = weight_vect_dir + \
'census-full-index-weight-vectors.csv',
rec_comparator = census_rec_comp,
progress=progress_precentage,
index_def = []) # Not needed for full ind.
# Function to be used to check for true matches and non-matches
#
def census_check_funct(rec_id1, rec_id2, weight_vec):
return (weight_vec[0] == 1.0)
# Function to be used to extract the record identifier from a raw record
#
def census_get_id_funct(rec):
return rec[1]
experiment_list.append(((census_ds_A,census_ds_B), cens_bigmatch_index,
census_sel_list, census_check_funct,
census_get_id_funct))
experiment_list.append(((census_ds_A,census_ds_B), cens_full_index,
census_sel_list, census_check_funct,
census_get_id_funct))
# -----------------------------------------------------------------------------
# The publicly available Restaurant data set (Fodors/ Zagats) restaurant names
# and addresses (taken from SecondString data repository).
#
# - The 'class' attribute contains entity numbers.
# - No record identifer is available.
#
rest_ds = dataset.DataSetCSV(description='Restaurant data set',
access_mode='read',
rec_ident='rec_id',
header_line=True,
file_name = './data/secondstring/restaurant.csv')
rest_index_list = [[['phone', 'phone', False, False, None,
[encode.get_substring,0,4]]],
[['type', 'type', False, False, None, [encode.soundex,4]]],
[['city', 'city', False, False, None,
[encode.dmetaphone,4]]]]
# Exact comparison of 'class:' If the same it is a match, otherwise not
#
rest_class_exact = comparison.FieldComparatorExactString(desc = 'class_exact')
rest_name_winkler = comparison.FieldComparatorWinkler(thres=0,
desc = 'name_winkler')
rest_addr_winkler = comparison.FieldComparatorWinkler(thres=0,
desc = 'addr_winkler')
rest_city_winkler = comparison.FieldComparatorWinkler(thres=0,
desc = 'city_winkler')
rest_name_qgram = comparison.FieldComparatorQGram(thres=0, q=2,
common_divisor='average',
desc = 'name_qgram')
rest_addr_qgram = comparison.FieldComparatorQGram(thres=0, q=2,
common_divisor='average',
desc = 'addr_qgram')
rest_city_qgram = comparison.FieldComparatorQGram(thres=0, q=2,
common_divisor='average',
desc = 'city_qgram')
rest_name_bagdist = comparison.FieldComparatorBagDist(thres=0,
desc = 'name_bagdist')
rest_addr_bagdist = comparison.FieldComparatorBagDist(thres=0,
desc = 'addr_bagdist')
rest_city_bagdist = comparison.FieldComparatorBagDist(thres=0,
desc = 'city_bagdist')
rest_name_lcs = comparison.FieldComparatorLCS(thres=0, min_common_len=2,
common_divisor='average',
desc = 'name_lcs')
rest_addr_lcs = comparison.FieldComparatorLCS(thres=0, min_common_len=2,
common_divisor='average',
desc = 'addr_lcs')
rest_city_lcs = comparison.FieldComparatorLCS(thres=0, min_common_len=2,
common_divisor='average',
desc = 'city_lcs')
rest_fc_list = [(rest_class_exact, 'class', 'class'),
(rest_name_winkler, 'name', 'name'),
(rest_addr_winkler, 'addr', 'addr'),
(rest_city_winkler, 'city', 'city'),
(rest_name_qgram, 'name', 'name'),
(rest_addr_qgram, 'addr', 'addr'),
(rest_city_qgram, 'city', 'city'),
(rest_name_bagdist, 'name', 'name'),
(rest_addr_bagdist, 'addr', 'addr'),
(rest_city_bagdist, 'city', 'city'),
(rest_name_lcs, 'name', 'name'),
(rest_addr_lcs, 'addr', 'addr'),
(rest_city_lcs, 'city', 'city')]
rest_rec_comp = comparison.RecordComparator(rest_ds, rest_ds, rest_fc_list,
'Restaurant record comparator')
# List with sub-sets of the field comparisons for experiments
#
rest_sel_list = [('Winkler', [ (1,), (2,), (3,)]),
('Q-Gram', [ (4,), (5,), (6,)]),
('Bag-Distance',[ (7,), (8,), (9,)]),
('LCS', [(10,),(11,),(12,)])]
rest_dedup_index = indexing.DedupIndex(description = 'Restaurant Dedup index',
dataset1 = rest_ds,
dataset2 = rest_ds,
weight_vec_file = weight_vect_dir + \
'restaurant-dedup-index-weight-vectors.csv',
rec_comparator = rest_rec_comp,
progress=progress_precentage,
block_method = index_dedup_block_method,
index_def = rest_index_list)
rest_full_index = indexing.FullIndex(description = 'Restaurant Full index',
dataset1 = rest_ds,
dataset2 = rest_ds,
weight_vec_file = weight_vect_dir + \
'restaurant-full-index-weight-vectors.csv',
rec_comparator = rest_rec_comp,
progress=progress_precentage,
index_def = []) # Not needed for full ind.
# Function to be used to check for true matches and non-matches
#
def rest_check_funct(rec_id1, rec_id2, weight_vec):
return (weight_vec[0] == 1.0)
# Function to be used to extract the record identifier from a raw record
#
def rest_get_id_funct(rec):
return rec[-1]
experiment_list.append(((rest_ds, rest_ds), rest_dedup_index, rest_sel_list,
rest_check_funct, rest_get_id_funct))
experiment_list.append(((rest_ds, rest_ds), rest_full_index, rest_sel_list,
rest_check_funct, rest_get_id_funct))
# -----------------------------------------------------------------------------
# The publicly available Cora containing bibliographic citations.
cora_ds = dataset.DataSetCSV(description='Cora data set',
access_mode='read',
rec_ident='rec_id',
delimiter='\t',
header_line=False,
field_list=[('unknown',0),
('paper_id',1),
('author_list',2),
('pub_details',3),
('title',4),
('affiliation',5),
('conf_journal',6),
('location',7),
('publisher',8),
('year',9),
('pages',10),
('editors',11),
('appear',12),
('month',13)],
file_name = './data/secondstring/cora.tab')
cora_index_list = [[['author_list','author_list', False, False, None,
[encode.dmetaphone,3]]],
[['title', 'title', False, False, None,
[encode.dmetaphone,3]]],
[['conf_journal','conf_journal', False, False, None,
[encode.dmetaphone,3]]],
[['year', 'year', False, False, None,
[encode.dmetaphone,3]]]]
# Exact comparison of 'paper_id': If the same it is a match, otherwise not
#
cora_paper_id_exact = comparison.FieldComparatorExactString(desc = \
'paper_id_exact')
cora_author_list_winkler = comparison.FieldComparatorWinkler(thres=0,
desc = 'author_list_winkler')
cora_title_winkler = comparison.FieldComparatorWinkler(thres=0,
desc = 'title_winkler')
cora_conf_journal_winkler = comparison.FieldComparatorWinkler(thres=0,
desc = 'conf_journal_winkler')
cora_author_list_qgram = comparison.FieldComparatorQGram(thres=0,
common_divisor='average',
desc = 'author_list_qgram')
cora_title_qgram = comparison.FieldComparatorQGram(thres=0,
common_divisor='average',
desc = 'title_qgram')
cora_conf_journal_qgram = comparison.FieldComparatorQGram(thres=0,
common_divisor='average',
desc = 'conf_journal_qgram')
cora_author_list_bagdist = comparison.FieldComparatorBagDist(thres=0,
desc = 'author_list_bagdist')
cora_title_bagdist = comparison.FieldComparatorBagDist(thres=0,
desc = 'title_bagdist')
cora_conf_journal_bagdist = comparison.FieldComparatorBagDist(thres=0,
desc = 'conf_journal_bagdist')
cora_author_list_lcs = comparison.FieldComparatorLCS(thres=0,
min_common_len=2,
common_divisor='average',
desc = 'author_list_qgram')
cora_title_lcs = comparison.FieldComparatorLCS(thres=0,
min_common_len=2,
common_divisor='average',
desc = 'title_qgram')
cora_conf_journal_lcs = comparison.FieldComparatorLCS(thres=0,
min_common_len=2,
common_divisor='average',
desc = 'conf_journal_qgram')
cora_year_exact = comparison.FieldComparatorExactString(desc = 'year_exact')
cora_year_keydiff = comparison.FieldComparatorKeyDiff(max_key_diff=1,
desc = 'year_keydiff')
cora_pages_exact = comparison.FieldComparatorExactString(desc = 'pages_exact')
cora_pages_keydiff = comparison.FieldComparatorKeyDiff(max_key_diff=2,
desc = 'pages_keydiff')
cora_fc_list = [(cora_paper_id_exact, 'paper_id', 'paper_id'),
(cora_author_list_winkler, 'author_list', 'author_list'),
(cora_title_winkler, 'title', 'title'),
(cora_conf_journal_winkler, 'conf_journal','conf_journal'),
(cora_author_list_qgram, 'author_list', 'author_list'),
(cora_title_qgram, 'title', 'title'),
(cora_conf_journal_qgram, 'conf_journal','conf_journal'),
(cora_author_list_bagdist, 'author_list', 'author_list'),
(cora_title_bagdist, 'title', 'title'),
(cora_conf_journal_bagdist, 'conf_journal','conf_journal'),
(cora_author_list_lcs, 'author_list', 'author_list'),
(cora_title_lcs, 'title', 'title'),
(cora_conf_journal_lcs, 'conf_journal','conf_journal'),
(cora_year_exact, 'year', 'year'),
(cora_year_keydiff, 'year', 'year'),
(cora_pages_exact, 'pages', 'pages'),
(cora_pages_keydiff, 'pages', 'pages')]
cora_rec_comp = comparison.RecordComparator(cora_ds, cora_ds, cora_fc_list,
'Cora record comparator')
# List with sub-sets of the field comparisons for experiments
#
cora_sel_list = [('Winkler', [ (1,), (2,), (3,),(14,),(16,)]),
('Q-Gram', [ (4,), (5,), (6,),(14,),(16,)]),
('Bag-Distance',[ (7,), (8,), (9,),(14,),(16,)]),
('LCS', [(10,),(11,),(12,),(14,),(16,)])]
cora_dedup_index = indexing.DedupIndex(description = 'Cora Dedup index',
dataset1 = cora_ds,
dataset2 = cora_ds,
weight_vec_file = weight_vect_dir + \
'cora-dedup-index-weight-vectors.csv',
rec_comparator = cora_rec_comp,
progress=progress_precentage,
block_method = index_dedup_block_method,
index_def = cora_index_list)
# Function to be used to check for true matches and non-matches
#
def cora_check_funct(rec_id1, rec_id2, weight_vec):
return (weight_vec[0] == 1.0)
# Function to be used to extract the record identifier from a raw record
#
def cora_get_id_funct(rec):
return rec[1]
experiment_list.append(((cora_ds, cora_ds), cora_dedup_index, cora_sel_list,
cora_check_funct, cora_get_id_funct))
# -----------------------------------------------------------------------------
# Synthetic data sets of different sizes generated with Febrl data generator
# Index and field comparisons are the same for all synthetic data sets
#
synth_index_list = [[['surname', 'surname', False, False, None,
[encode.soundex]],
['postcode', 'postcode', False, False, None,
[encode.get_substring,0,2]]],
[['given_name', 'given_name', False, False, None,
[encode.soundex]],
['postcode', 'postcode', False, False, None,
[encode.get_substring,1,3]]],
[['suburb', 'suburb', False, False, None,
[encode.soundex]],
['postcode', 'postcode', False, False, None,
[encode.get_substring,2,4]]],
[['suburb', 'suburb', False, False, None,
[encode.soundex]],
['street_number', 'street_number', False, False, None,
[]]],
[['postcode', 'postcode', False, False, None, []],
['age', 'age', False, False, None, []]],
[['address_1', 'address_1', False, False, 3, []],
['age', 'age', False, False, None, []]],
[['surname', 'surname', False, False, 3, []],
['state', 'state', False, False, None, []]],
[['given_name', 'given_name', False, False, 3, []],
['state', 'state', False, False, None, []]],
[['surname', 'surname', False, False, None,
[encode.get_substring,0,2]],
['given_name', 'given_name', False, False, None,
[encode.get_substring,0,2]]]]
synth_surname_winkler = comparison.FieldComparatorWinkler(thres=0,
desc = 'surname_winkler')
synth_given_name_winkler = comparison.FieldComparatorWinkler(thres=0,
desc = 'given_name_winkler')
synth_address_1_winkler = comparison.FieldComparatorWinkler(thres=0,
desc = 'address_1_winkler')
synth_suburb_winkler = comparison.FieldComparatorWinkler(thres=0,
desc = 'suburb_winkler')
synth_surname_qgram = comparison.FieldComparatorQGram(thres=0, q=2,
common_divisor='average',
desc = 'surname_qgram')
synth_given_name_qgram = comparison.FieldComparatorQGram(thres=0, q=2,
common_divisor='average',
desc = 'given_name_qgram')
synth_address_1_qgram = comparison.FieldComparatorQGram(thres=0, q=2,
common_divisor='average',
desc = 'address_1_qgram')
synth_suburb_qgram = comparison.FieldComparatorQGram(thres=0, q=2,
common_divisor='average',
desc = 'suburb_qgram')
synth_surname_bagdist = comparison.FieldComparatorBagDist(thres=0,
desc = 'surname_bagdist')
synth_given_name_bagdist = comparison.FieldComparatorBagDist(thres=0,
desc = 'given_name_bagdist')
synth_address_1_bagdist = comparison.FieldComparatorBagDist(thres=0,
desc = 'address_1_bagdist')
synth_suburb_bagdist = comparison.FieldComparatorBagDist(thres=0,
desc = 'suburb_bagdist')
synth_surname_lcs = comparison.FieldComparatorLCS(thres=0, min_common_len=2,
common_divisor='average',
desc = 'surname_lcs')
synth_given_name_lcs = comparison.FieldComparatorLCS(thres=0, min_common_len=2,
common_divisor='average',
desc = 'given_name_lcs')
synth_address_1_lcs = comparison.FieldComparatorLCS(thres=0, min_common_len=2,
common_divisor='average',
desc = 'address_1_lcs')
synth_suburb_lcs = comparison.FieldComparatorLCS(thres=0, min_common_len=2,
common_divisor='average',
desc = 'suburb_lcs')
synth_street_num_exact = comparison.FieldComparatorExactString(desc = \
'street_num_exact')
synth_street_num_keydiff = comparison.FieldComparatorKeyDiff(max_key_diff=1,
desc = 'street_num_keydiff')
synth_postcode_exact = comparison.FieldComparatorExactString(desc = \
'postcode_exact')
synth_postcode_keydiff = comparison.FieldComparatorKeyDiff(max_key_diff=1,
desc = 'postcode_keydiff')
synth_state_exact = comparison.FieldComparatorExactString(desc = \
'state_exact')
synth_state_keydiff = comparison.FieldComparatorKeyDiff(max_key_diff=1,
desc = 'state_keydiff')
synth_fc_list = [(synth_surname_winkler, 'surname', 'surname'),
(synth_given_name_winkler, 'given_name', 'given_name'),
(synth_address_1_winkler, 'address_1', 'address_1'),
(synth_suburb_winkler, 'suburb', 'suburb'),
(synth_surname_qgram, 'surname', 'surname'),
(synth_given_name_qgram, 'given_name', 'given_name'),
(synth_address_1_qgram, 'address_1', 'address_1'),
(synth_suburb_qgram, 'suburb', 'suburb'),
(synth_surname_bagdist, 'surname', 'surname'),
(synth_given_name_bagdist, 'given_name', 'given_name'),
(synth_address_1_bagdist, 'address_1', 'address_1'),
(synth_suburb_bagdist, 'suburb', 'suburb'),
(synth_surname_lcs, 'surname', 'surname'),
(synth_given_name_lcs, 'given_name', 'given_name'),
(synth_address_1_lcs, 'address_1', 'address_1'),
(synth_suburb_lcs, 'suburb', 'suburb'),
(synth_street_num_exact, 'street_number', 'street_number'),
(synth_street_num_keydiff, 'street_number', 'street_number'),
(synth_postcode_exact, 'postcode', 'postcode'),
(synth_postcode_keydiff, 'postcode', 'postcode'),
(synth_state_exact, 'state', 'state'),
(synth_state_keydiff, 'state', 'state')]
# List with sub-sets of the field comparisons for experiments
#
synth_sel_list = [('Winkler', [ (0,), (1,), (2,), (3,),(17,),(19,),(21,)]),
('Q-Gram', [ (4,), (5,), (6,), (7,),(17,),(19,),(21,)]),
('Bag-Distance',[ (8,), (9,),(10,),(11,),(17,),(19,),(21,)]),
('LCS', [(12,),(13,),(14,),(15,),(17,),(19,),(21,)])]
# Function to be used to check for true matches and non-matches
#
def synth_check_funct(rec_id1, rec_id2, weight_vec):
return (rec_id1[:-1] == rec_id2[:-1])
# Function to be used to extract the record identifier from a raw record
#
def synth_get_id_funct(rec):
return rec[0][:-1]
# Loop over different data set sizes - - - - - - - - - - - - - - - - - - - - -
#
for size in ['B_1000', 'C_1000', 'B_2500', 'C_2500',
'B_5000', 'C_5000', 'B_10000', 'C_10000',
'B_25000', 'C_25000', 'B_50000', 'C_50000']:
ds_file_name = 'dataset_%s.csv.gz' % (size)
synth_ds = dataset.DataSetCSV(description='Febrl synthetic data set %s' % \
(size),
access_mode='read',
rec_ident='rec_id',
header_line=True,
file_name = './data/dedup-dsgen/%s' % \
(ds_file_name))
synth_rec_comp = comparison.RecordComparator(synth_ds, synth_ds,
synth_fc_list,
'Febrl synthetic data record' \
+ ' comparator')
synth_dedup_index = indexing.DedupIndex(description = 'Febrl synthetic ' + \
' Dedup index',
dataset1 = synth_ds,
dataset2 = synth_ds,
weight_vec_file = weight_vect_dir + \
'synth-%s-dedup-index-weight-vectors.csv' % (size),
rec_comparator = synth_rec_comp,
progress=progress_precentage,
block_method = index_dedup_block_method,
index_def = synth_index_list)
experiment_list.append(((synth_ds, synth_ds), synth_dedup_index,
synth_sel_list, synth_check_funct,
synth_get_id_funct))
# =============================================================================
# Run all the experiments
#
res_dict = {} # With data set names as keys and a list with results each
########## Select experiments #######################
#
# Census: 0,1, Restaurant: 2,3, Cora: 4,
# DS-Gen B: 5,7,...15, DS-Gen C: 6,8,...,16
#
# Started 1 Feb:
#experiment_list =[experiment_list[0],experiment_list[2],experiment_list[4],
# experiment_list[6],experiment_list[8],experiment_list[10],
# experiment_list[12],experiment_list[14],experiment_list[16]]
# Started 15 Feb:
#experiment_list =[experiment_list[6],experiment_list[8],experiment_list[10],
# experiment_list[12],experiment_list[14],experiment_list[16]]
# Started 19 Feb:
#experiment_list =[experiment_list[12],experiment_list[14],experiment_list[16]]
# Started 21 Feb:
#experiment_list =[experiment_list[12]]
# Started 21 Feb (later)
#experiment_list =[experiment_list[4]]
# Started 22 Feb
#experiment_list =[experiment_list[4]]
# Started 25 Feb:
#experiment_list =[experiment_list[12]]
# Started 26 Feb:
#experiment_list =[experiment_list[12]]
# Started 27 Feb:
experiment_list =[experiment_list[4]]
#####################################################
for experiment in experiment_list:
res_list = [] # List with all results for this data set, a list for each
# experiment
data_set_a = experiment[0][0]
data_set_b = experiment[0][1]
data_set_index = experiment[1]
field_comp_sel = experiment[2]
match_check_funct = experiment[3]
get_id_funct = experiment[4]
res_list_key = (data_set_a.description, data_set_b.description)
res_file.write(os.linesep + '='*84 + os.linesep + os.linesep)
if (data_set_a == data_set_b):
res_file.write('Run deduplication experiments for data set:' + os.linesep)
res_file.write('===========================================' + os.linesep)
res_file.write(' %s' % (data_set_a.description) + os.linesep)
res_file.write(os.linesep)
res_file.write(' Number of records in data set: %d' % \
(data_set_a.num_records) + os.linesep)
else: # Linkage of two data sets
res_file.write('Run linkage experiments for data sets:' + os.linesep)
res_file.write('======================================' + os.linesep)
res_file.write(' A: %s' % (data_set_a.description) + os.linesep)
res_file.write(' B: %s' % (data_set_b.description) + os.linesep)
res_file.write(os.linesep)
res_file.write(' Number of records in data sets: %d / %d ' % \
(data_set_a.num_records, data_set_b.num_records) + \
os.linesep)
res_file.write(os.linesep)
res_file.write(' Index: %s' % (data_set_index.description) + os.linesep)
res_file.write(os.linesep)
res_file.flush()
# Check if weight vector file is available for this experiment - - - - - - -
#
weight_vec_file = data_set_index.weight_vec_file
if (weight_vec_file != None):
# Check if the weight vector file or it's GZipped version is available
#
file_avail = (os.access(weight_vec_file, os.R_OK) or \
os.access(weight_vec_file+'.gz', os.R_OK) or \
os.access(weight_vec_file+'.GZ', os.R_OK)) # Can read file
else:
file_avail = False
if (file_avail == True): # File is available, so load it - - - - - - - - - -
res_file.write(' Load weight vector dictionary from file:' + os.linesep)
res_file.write(' %s' % (weight_vec_file) + os.linesep)
res_file.flush()
[field_names_list, w_vec_dict] = \
output.LoadWeightVectorFile(weight_vec_file)
res_file.write(' Field names from weight vector file:' + os.linesep)
res_file.write(' %s' % (str(field_names_list)) + os.linesep)
res_file.flush()
else: # Have to calculate weight vectors - - - - - - - - - - - - - - - - - -
res_file.write(' Build and compact index, then run comparison step' + \
os.linesep)
data_set_index.build()
data_set_index.compact()
my_logger.setLevel(logging.INFO)
w_vec_run_data = data_set_index.run()
my_logger.setLevel(logging.WARNING)
if (w_vec_run_data == None): # Has been written to file - - - - - - - - -
[field_names_list, w_vec_dict] = \
output.LoadWeightVectorFile(weight_vec_file)
else:
[field_names_list, w_vec_dict] = w_vec_run_data
num_w_vec = len(w_vec_dict)
res_file.write(os.linesep)
res_file.write(' Returned dictionary with %d weight vectors' \
% (num_w_vec) + os.linesep)
res_file.flush()
# Get the true matches and true non-matches in the weight vector dictionary
#
true_m_set, true_nm_set = \
classification.get_true_matches_nonmatches(w_vec_dict,
match_check_funct)
num_true_m = len(true_m_set)
num_true_nm = len(true_nm_set)
assert (num_true_m + num_true_nm) == num_w_vec
res_file.write(' Number of true matches and non-matches: %d / %d' % \
(num_true_m, num_true_nm) + os.linesep)
res_file.write(os.linesep)
res_file.flush()
# Check that true quality is 100% for all measures - - - - - - - - - - - - -
#
acc, prec, reca, fmeas = measurements.quality_measures(w_vec_dict,
true_m_set,
true_nm_set,
match_check_funct)
assert acc == 1.0, 'Accuracy of true matches and non-matches not 100%'
assert prec == 1.0, 'Precision of true matches and non-matches not 100%'
assert prec == 1.0, 'Recall of true matches and non-matches not 100%'
assert fmeas == 1.0, 'F-measure of true matches and non-matches not 100%'
# Get quality and complexity measures for weight vectors - - - - - - - - -
#
if (do_complexity == True):
rr = measurements.reduction_ratio(w_vec_dict, data_set_a, data_set_b)
pc = measurements.pairs_completeness(w_vec_dict, data_set_a, data_set_b,
get_id_funct, match_check_funct)
pq = measurements.pairs_quality(w_vec_dict, match_check_funct)
res_file.write(' Reduction ratio: %7.2f%%' % (100.0*rr) + os.linesep)
res_file.write(' Pairs completeness: %7.2f%%' % (100.0*pc) + os.linesep)
res_file.write(' Pairs quality: %7.2f%%' % (100.0*pq) + os.linesep)
res_file.write(os.linesep)
res_file.write('-'*84 + os.linesep + os.linesep)
# ===========================================================================
# End of initialisation, now perform various classifications
#############
field_comp_sel = [field_comp_sel[0]] #### ONLY DO WINKLER #################
#############
# Loop over the field comparison selections ---------------------------------
#
for (sel_name, sel_list) in field_comp_sel:
exp_res_list = [sel_name] # All results for this experiment
num_weights = len(sel_list)
res_file.write(' Field comparison selection: %s' % (sel_name) + \
os.linesep)
res_file.write(' ----------------------------'+'-'*len(sel_name) + \
os.linesep + os.linesep)
res_file.write(' Number of fields comparisons: %d' % (num_weights) + \
os.linesep)
field_names = []
for tup in sel_list:
field_names.append(field_names_list[tup[0]])
res_file.write(' Selected fields:' + os.linesep)
res_file.write(' %s' % (str(field_names)) + os.linesep + os.linesep)
sel_w_vec_dict = classification.extract_collapse_weight_vectors(sel_list,
w_vec_dict)
if (do_plotting == True): # Plot true match and non-match sets
plot_weight_vectors(sel_w_vec_dict, true_m_set, true_m_set,
true_nm_set, true_nm_set, 'True match status')
# Write header of result tables to file - - - - - - - - - - - - - - - - - -
#
res_file.write(' '+'='*80 + os.linesep)
res_file.write(' Classifier experiment | Acc | ' + \
'Prec | Reca | F-Meas| Time (s)' + os.linesep)
res_file.write(' '+'='*80 + os.linesep)
# Now conduct the various classification experiments ----------------------
# -------------------------------------------------------------------------
# Classify using a one-dimensional classifier that knows true match status
#
res_file.write(' ' + \
'Optimal threshold classifier (1-dimensional)'.center(79) \
+ os.linesep)
res_file.write(' ' + '-'*80 + os.linesep)
one_dim_sel_list = [tuple(range(len(sel_list)))]
one_dim_w_vec_dict = \
classification.extract_collapse_weight_vectors(one_dim_sel_list,
sel_w_vec_dict)
assert len(one_dim_w_vec_dict) == num_w_vec
# Three variations: minimise pos-neg, pos only, neg only - - - - - - - - -
#
opt_thres_param_list = [('Minimise false pos-neg ', 'pos-neg'),
('Minimise false pos only', 'pos'),
('Minimise false neg only', 'neg')]
if (do_opt_thres == False):
opt_thres_param_list = [] # Don't perform these experiments
opt_thres_res_list = []
for (class_name, min_method_name) in opt_thres_param_list:
opt_thres_classifier = classification.OptimalThreshold(bin_width = 0.01,
min_method = min_method_name)
start_time = time.time()