-
Notifications
You must be signed in to change notification settings - Fork 21
/
classification.py
5174 lines (4060 loc) · 202 KB
/
classification.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: "classification.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 with classes for record pair classification.
This module provides various classifiers, both based on supervised and
unsupervised methods, that classify weight vectors into 'matches' and
'non-matches', and possibly 'possible matches' (some classifiers don't
classify weight vectors into this third class).
FellegiSunter The classical Fellegi and Sunter classifier with two
thresholds.
OptimalThreshold A classifiers that uses the true match and non-match
status to optimally set threshold values.
KMeans Unsupervised K-means clustering algorithm with.
FarthestFirst Unsupervised farthest first clustering algorithm.
SuppVecMachine Supervised support vector machine (SVM) classifier.
TwoStep Unsupervised two-step classifier.
TAILOR Unsupervised hybrid classifier as described in the paper
TAILOR: A record linkage toolbox (Elfeky MG, Verykios
VS, Elmagarmid AK, ICDE, San Jose, 2002.
##
TODO: DecisionTree Supervised decision tree induction based classifier.
##
Creating and using a classifier normally consists of the following steps:
- initialise The classifier is initialised and trained if training data is
provided (i.e. if a weight vector dictionary and a match and
non-match set is given, the training method will be called).
- train Train the classifier using training data.
- test Testing the trained classifier using test data (with known
match and non-match status).
- classify Use the trained classifier to classify weight vectors with
unknown match status.
Each classifier also has a cross_validate() method that allows evaluation of
the classifier by conducting a cross validation.
Additional auxiliary functions in this module that are related to record
pair classification are:
get_true_matches_nonmatches Checks for all weight vectors in a weight
vector dictionary if they correspond to
true matches or true non-matches.
extract_collapse_weight_vectors A function that allows manipulation of
the weight vectors in a weight vector
dictionary, such as summing weight vector
elements or filtering them out. Returns a
modified weight vector dictionary.
TODO:
- Decision Tree based -> improve, make faster
- EM clustering
- have an argument collapse_vector [0,0,1,2,0,1] of same lengths as weight
vector, which will take weights and summ them according to index numbers
e.g. new_w-vec[0] = w_vec[0]+w_vec[1]+w_vec[4], new_w_vec[1] = ...
"""
# =============================================================================
# Import necessary modules (Python standard modules first, then Febrl modules)
import auxiliary
import mymath
import heapq
import logging
import math
import os
import random
#try:
# import Numeric
# imp_numeric = True
#except:
# imp_numeric = False
#
#if (imp_numeric == True):
# try:
# import PyML
# import PyML.datafunc
# import PyML.svm
# imp_pyml = True
# except:
# imp_pyml = False
#else:
# imp_pyml = False
try:
import svm
imp_svm = True
except:
imp_svm = False
#if (imp_pyml == False):
# logging.warn('Cannot import Numeric and PyML modules')
if (imp_svm == False):
logging.warn('Cannot import svm module')
# =============================================================================
class Classifier:
"""Base class for classifiers.
All classifiers have the following instance variables, which can be set
when a classifier is initialised:
description A string describing the classifier.
train_w_vec_dict A weight vector dictionary that will be used for
training.
train_match_set A set with record identifier pairs which are
assumed to be the match training examples.
train_non_match_set A set with record identifier pairs which are
assumed to be the non-match training examples.
If the last three arguments (train_w_vec_dict, train_match_set, and
train_non_match_set) are given when a classifier is initialised, it is
trained straight away (so the 'train' method does not have to be called).
Default is that these three values are set to None, so no training is done
when a classifier is initialised.
"""
# ---------------------------------------------------------------------------
def __init__(self, base_kwargs):
"""Constructor.
"""
# General attributes for all classifiers.
#
self.description = '' # A description of the classifier.
self.train_w_vec_dict = None # The dictionary containing weight vectors
# used for training.
self.train_match_set = None # A set with record identifier pairs that
# are matches used for training.
self.train_non_match_set = None # A set with record identifier pairs that
# are non-matches used for training.
# Process base keyword arguments (all data set specific keywords were
# processed in the derived class constructor)
#
for (keyword, value) in base_kwargs.items():
if (keyword.startswith('desc')):
auxiliary.check_is_string('description', value)
self.description = value
elif (keyword.startswith('train_w_vec')):
auxiliary.check_is_dictionary('train_w_vec_dict', value)
self.train_w_vec_dict = value
elif (keyword.startswith('train_mat')):
auxiliary.check_is_set('train_match_set', value)
self.train_match_set = value
elif (keyword.startswith('train_non')):
auxiliary.check_is_set('train_non_match_set', value)
self.train_non_match_set = value
else:
logging.exception('Illegal constructor argument keyword: '+keyword)
raise Exception
# ---------------------------------------------------------------------------
def train(self, w_vec_dict, match_set, non_match_set):
"""Method to train a classifier using the given weight vector dictionary
and match and non-match sets of record identifier pairs.
See implementations in derived classes for details.
"""
logging.exception('Override abstract method in derived class')
raise Exception
# ---------------------------------------------------------------------------
def test(self, w_vec_dict, match_set, non_match_set):
"""Method to test a classifier using the given weight vector dictionary and
match and non-match sets of record identifier pairs.
Will return a confusion matrix as a list of the form: [TP, FN, FP, TN].
See implementations in derived classes for details.
"""
logging.exception('Override abstract method in derived class')
raise Exception
# ---------------------------------------------------------------------------
def cross_validate(self, w_vec_dict, match_set, non_match_set):
"""Method to conduct a cross validation using the given weight vector
dictionary and match and non-match sets of record identifier pairs.
Will return a confusion matrix as a list of the form: [TP, FN, FP, TN].
See implementations in derived classes for details.
"""
logging.exception('Override abstract method in derived class')
raise Exception
# ---------------------------------------------------------------------------
def classify(self, w_vec_dict):
"""Method to classify the given weight vector dictionary using the trained
classifier.
Will return three sets with record identifier pairs:
1) match set
2) non-match set
3) possible match set (this will always be empty for certain
classifiers that only classify into matches and
non-matches)
See implementations in derived classes for details.
"""
logging.exception('Override abstract method in derived class')
raise Exception
# ---------------------------------------------------------------------------
def log(self, instance_var_list = None):
"""Write a log message with the basic classifier instance variables plus
the instance variable provided in the given input list (assumed to
contain pairs of names (strings) and values).
"""
logging.info('')
logging.info('Classifier: "%s"' % (self.description))
if (self.train_w_vec_dict != None):
logging.info(' Number of weight vectors provided: %d' % \
(len(self.train_w_vec_dict)))
if (self.train_match_set != None):
logging.info(' Number of match training examples provided: %d' % \
(len(self.train_match_set)))
if (self.train_non_match_set != None):
logging.info(' Number of non-match training examples provided: %d' % \
(len(self.train_non_match_set)))
if (instance_var_list != None):
logging.info(' Classifier specific variables:')
max_name_len = 0
for (name, value) in instance_var_list:
max_name_len = max(max_name_len, len(name))
for (name, value) in instance_var_list:
pad_spaces = (max_name_len-len(name))*' '
logging.info(' %s %s' % (name+':'+pad_spaces, str(value)))
# =============================================================================
class FellegiSunter(Classifier):
"""Implements the classical Fellegi and Sunter classifier.
This classifier sums all weights in a weight vector into one matching
weight and then uses two threshold to classify this weight vector as
either a match, non-match or a possible match.
The arguments that have to be set when this classifier is initialised are:
lower_threshold All weight vectors with a summed matching weight below
this threshold are classified as non-matches.
upper_threshold All weight vectors with a summed matching weight above
this threshold are classified as matches.
"""
# ---------------------------------------------------------------------------
def __init__(self, **kwargs):
"""Constructor. Process the 'lower_threshold' and 'upper_threshold'
arguments first, then call the base class constructor.
"""
self.lower_threshold = None
self.upper_threshold = None
base_kwargs = {} # Dictionary, will contain unprocessed arguments for base
# class constructor
for (keyword, value) in kwargs.items():
if (keyword.startswith('lower_t')):
auxiliary.check_is_number('lower_threshold', value)
self.lower_threshold = value
elif (keyword.startswith('upper_t')):
auxiliary.check_is_number('upper_threshold', value)
self.upper_threshold = value
else:
base_kwargs[keyword] = value
Classifier.__init__(self, base_kwargs) # Initialise base class
# Check threshold values are set and valid - - - - - - - - - - - - - - - -
#
auxiliary.check_is_number('lower_threshold', self.lower_threshold)
auxiliary.check_is_number('upper_threshold', self.upper_threshold)
if (self.lower_threshold > self.upper_threshold):
logging.exception('Lower threshold is larger than upper threshold: ' + \
'%.3f / %.3f' % (lower_threshold, upper_threshold))
raise Exception
self.log([('Lower threshold', self.lower_threshold),
('Upper threshold', self.upper_threshold)]) # Log a message
# If the weight vector dictionary and both match and non-match sets - - - -
# are given start the training process
#
if ((self.train_w_vec_dict != None) and (self.train_match_set != None) \
and (self.train_non_match_set != None)):
logging.info('Train Fellegi and Sunter classifier: "%s"' % \
(self.description))
logging.info(' Nothing needs to be done.')
# ---------------------------------------------------------------------------
def train(self, w_vec_dict, match_set, non_match_set):
"""Method to train a classifier using the given weight vector dictionary
and match and non-match sets of record identifier pairs.
Nothing needs to be done.
"""
logging.info('')
logging.info('Train Fellegi and Sunter classifier: "%s"' % \
(self.description))
logging.info(' Nothing needs to be done.')
# ---------------------------------------------------------------------------
def test(self, w_vec_dict, match_set, non_match_set):
"""Method to test a classifier using the given weight vector dictionary and
match and non-match sets of record identifier pairs.
Will return a confusion matrix as a list of the form: [TP, FN, FP, TN].
The numbers returned in the confusion matrix will only consider the
classified matches and non-matches, but not the possible matches.
TODO:
- Is this correct, does this makes sense?
"""
auxiliary.check_is_dictionary('w_vec_dict', w_vec_dict)
auxiliary.check_is_set('match_set', match_set)
auxiliary.check_is_set('non_match_set', non_match_set)
# Check that match and non-match sets are separate and do cover all weight
# vectors given
#
if (len(match_set.intersection(non_match_set)) > 0):
logging.exception('Intersection of match and non-match set not empty')
raise Exception
if ((len(match_set)+len(non_match_set)) != len(w_vec_dict)):
logging.exception('Weight vector dictionary of different length than' + \
' summed lengths of match and non-match sets: ' + \
'%d / %d+%d=%d' % (len(w_vec_dict), len(match_set),
len(non_match_set), len(match_set)+len(non_match_set)))
raise Exception
logging.info('')
logging.info('Testing Fellegi and Sunter classifier using %d weight ' % \
(len(w_vec_dict))+'vectors')
logging.info(' Match and non-match sets with %d and %d entries' % \
(len(match_set), len(non_match_set)))
num_true_m = 0
num_false_m = 0
num_true_nm = 0
num_false_nm = 0
num_poss_m = 0
for (rec_id_tuple, w_vec) in w_vec_dict.iteritems():
w_sum = sum(w_vec)
if (w_sum > self.upper_threshold):
if (rec_id_tuple in match_set):
num_true_m += 1
else:
num_false_m += 1
elif (w_sum < self.lower_threshold):
if (rec_id_tuple in non_match_set):
num_true_nm += 1
else:
num_false_nm += 1
else:
num_poss_m += 1
assert (num_true_m+num_false_nm+num_false_m+num_true_nm+num_poss_m) == \
len(w_vec_dict)
logging.info(' Results: TP = %d, FN = %d, FP = %d, TN = %d; ' % \
(num_true_m,num_false_nm,num_false_m,num_true_nm) + \
'possible matches = %d' % (num_poss_m))
return [num_true_m, num_false_nm, num_false_m, num_true_nm]
# ---------------------------------------------------------------------------
def cross_validate(self, w_vec_dict, match_set, non_match_set, n=10):
"""Method to conduct a cross validation using the given weight vector
dictionary and match and non-match sets of record identifier pairs.
Will return a confusion matrix as a list of the form: [TP, FN, FP, TN].
The Fellegi and Sunter classifier cannot perform cross validation, as
the thresholds are set by the user. Therefore, in this method the given
weight vectors are tested once only by calling the 'test' method.
See documentation of 'test' for more information.
"""
logging.info('')
logging.info('Cross validation for Fellegi and Sunter is the same as' + \
'testing.')
return self.test(w_vec_dict, match_set, non_match_set)
# ---------------------------------------------------------------------------
def classify(self, w_vec_dict):
"""Method to classify the given weight vector dictionary using the trained
classifier.
Will return three sets with record identifier pairs: 1) match set,
2) non-match set, and 3) possible match set
"""
auxiliary.check_is_dictionary('w_vec_dict', w_vec_dict)
logging.info('')
logging.info('Classify %d weight vectors using Fellegi and Sunter ' % \
(len(w_vec_dict))+'classifier')
match_set = set()
non_match_set = set()
poss_match_set = set()
for (rec_id_tuple, w_vec) in w_vec_dict.iteritems():
w_sum = sum(w_vec)
if (w_sum > self.upper_threshold):
match_set.add(rec_id_tuple)
elif (w_sum < self.lower_threshold):
non_match_set.add(rec_id_tuple)
else:
poss_match_set.add(rec_id_tuple)
assert (len(match_set) + len(non_match_set) + len(poss_match_set)) == \
len(w_vec_dict)
logging.info('Classified %d weight vectors: %d as matches, %d as ' % \
(len(w_vec_dict), len(match_set), len(non_match_set)) + \
'non-matches, and %d as possible matches' % \
(len(poss_match_set)))
return match_set, non_match_set, poss_match_set
# =============================================================================
class OptimalThreshold(Classifier):
"""Implements a classifier that has access to the true matches and true
non-matches, and can thus set an optimal threshold (one for each weight
vector element / dimension) so that the sum of either the number of (a)
false matches and false non-matches, (b) false matches only, or (c) false
non-matches only, is minimised.
The weight vector values are binned first (according to the value of the
'bin_width' argument) and then the optimal threshold is used on the binned
values in each vector element (dimension).
The arguments that have to be set when this classifier is initialised are:
bin_width The numerical width of the bins to be used.
min_method A string which designates what to minimise. This can either
be 'pos-neg' (default) in which case the sum of both false
matches and false non-matches will be minimised, or 'pos' or
'neg', in which case only the corresponding false numbers
will be minimised. Default is 'pos-neg'.
"""
# ---------------------------------------------------------------------------
def __init__(self, **kwargs):
"""Constructor. Process the 'bin_width' and 'min_method' arguments first,
then call the base class constructor.
"""
self.bin_width = None
self.min_method = 'pos-neg'
self.opt_threshold_list = None # Will be calculated in training phase
base_kwargs = {} # Dictionary, will contain unprocessed arguments for base
# class constructor
for (keyword, value) in kwargs.items():
if (keyword.startswith('bin_w')):
auxiliary.check_is_number('bin_width', value)
auxiliary.check_is_positive('bin_width', value)
self.bin_width = value
elif (keyword.startswith('min_m')):
auxiliary.check_is_string('min_method', value)
if (value not in ['pos-neg', 'pos', 'neg']):
logging.exception('Value of "min_method" is not one of "pos-neg"' + \
', "pos", or "neg": %s' % (value))
raise Exception
self.min_method = value
else:
base_kwargs[keyword] = value
Classifier.__init__(self, base_kwargs) # Initialise base class
# Check the bin width value is set - - - - - - - - - - - - - - - - - - - -
#
auxiliary.check_is_number('bin_width', self.bin_width)
auxiliary.check_is_positive('bin_width', self.bin_width)
self.log([('Bin width', self.bin_width),
('Minimise method', self.min_method)]) # Log a message
# If the weight vector dictionary and both match and non-match sets - - - -
# are given start the training process
#
if ((self.train_w_vec_dict != None) and (self.train_match_set != None) \
and (self.train_non_match_set != None)):
self.train(self.train_w_vec_dict, self.train_match_set,
(self.train_non_match_set))
# ---------------------------------------------------------------------------
def train(self, w_vec_dict, match_set, non_match_set):
"""Method to train a classifier using the given weight vector dictionary
and match and non-match sets of record identifier pairs.
Note that all weight vectors must either be in the match or the
non-match training sets.
This method will calculate the optimal threshold for each vector element
(dimension).
"""
auxiliary.check_is_dictionary('w_vec_dict', w_vec_dict)
auxiliary.check_is_set('match_set', match_set)
auxiliary.check_is_set('non_match_set', non_match_set)
# Check that match and non-match sets are separate and do cover all weight
# vectors given
#
if (len(match_set.intersection(non_match_set)) > 0):
logging.exception('Intersection of match and non-match set not empty')
raise Exception
if ((len(match_set)+len(non_match_set)) != len(w_vec_dict)):
logging.exception('Weight vector dictionary of different length than' + \
' summed lengths of match and non-match sets: ' + \
'%d / %d+%d=%d' % (len(w_vec_dict), len(match_set),
len(non_match_set), len(match_set)+len(non_match_set)))
raise Exception
self.train_w_vec_dict = w_vec_dict # Save
self.train_match_set = match_set
self.train_non_match_set = non_match_set
# Get a random vector dictionary element to get dimensionality of vectors
#
(rec_id_tuple, w_vec) = w_vec_dict.popitem()
v_dim = len(w_vec)
w_vec_dict[rec_id_tuple] = w_vec # Put back in
logging.info('Train optimal threshold classifier using %d weight ' % \
(len(w_vec_dict))+'vectors')
logging.info(' Match and non-match sets with %d and %d entries' % \
(len(match_set), len(non_match_set)))
logging.info(' Dimensionality: %d' % (v_dim))
# One dictionary with binned weights and their counts per dimension - - - -
#
match_weight_dict_list = []
non_match_weight_dict_list = []
for i in range(v_dim):
match_weight_dict_list.append({})
non_match_weight_dict_list.append({})
# Go through all weight vectors and put them into match or non-match bins -
#
for (rec_id_tuple, w_vec) in w_vec_dict.iteritems():
for i in range(v_dim):
match_dict = match_weight_dict_list[i]
non_match_dict = non_match_weight_dict_list[i]
# Bin by rounding values down
#
binned_w = w_vec[i] - (w_vec[i] % self.bin_width)
if (rec_id_tuple in match_set):
w_count = match_dict.get(binned_w, 0) + 1
match_dict[binned_w] = w_count
elif (rec_id_tuple in non_match_set):
w_count = non_match_dict.get(binned_w, 0) + 1
non_match_dict[binned_w] = w_count
else:
logging.exception('Record identifier tuple %s not in match sets!' % \
(str(rec_id_tuple)))
raise Exception
# Get minimum and maximum binned weights - - - - - - - - - - - - - - - - -
#
opt_threshold_list = [] # One optimal threshold per dimension
for i in range(v_dim):
match_dict = match_weight_dict_list[i]
non_match_dict = non_match_weight_dict_list[i]
min_match_weight = 99999.99999
max_match_weight = -99999.99999
all_weights_set = set()
for w in match_dict:
min_match_weight = min(w, min_match_weight)
max_match_weight = max(w, max_match_weight)
all_weights_set.add(w)
min_non_match_weight = 99999.99999
max_non_match_weight = -99999.99999
for w in non_match_dict:
min_non_match_weight = min(w, min_non_match_weight)
max_non_match_weight = max(w, max_non_match_weight)
all_weights_set.add(w)
all_weights_list = list(all_weights_set)
all_weights_list.sort()
assert min(min_match_weight,min_non_match_weight) == all_weights_list[0]
assert max(max_match_weight,max_non_match_weight) == all_weights_list[-1]
logging.info(' Minimum and maximum binnded weights in dimension' + \
' %d: %.3f / %.3f' % (i, all_weights_list[0],
all_weights_list[-1]))
logging.info(' True match weights range: %.3f to %.3f' % \
(min_match_weight, max_match_weight))
logging.info(' True non-match weights range: %.3f to %.3f' % \
(min_non_match_weight, max_non_match_weight))
# Go through weight count dictionaries to find optimal thresholds - - - -
#
tp = len(match_set) # Set initial classification counts
tn = 0
fp = len(non_match_set)
fn = 0
if (self.min_method == 'pos-neg'): # Init classification information
min_num_wrong = fp+fn
elif (self.min_method == 'pos'):
min_num_wrong = fp
else:
min_num_wrong = fn
opt_threshold = all_weights_list[0]
for w in all_weights_list:
m_count = match_dict.get(w, 0)
nm_count = non_match_dict.get(w, 0)
tp -= m_count
fn += m_count
tn += nm_count
fp -= nm_count
if (self.min_method == 'pos-neg'):
if ((fp+fn) < min_num_wrong):
min_num_wrong = (fp+fn)
opt_threshold = w
elif (self.min_method == 'pos'):
if (fp < min_num_wrong):
min_num_wrong = fp
opt_threshold = w
else: # Minimise false negatives
if ((min_num_wrong == 0 ) and (fn > 0)): # First time there are FM
min_num_wrong = fn
opt_threshold = w-self.bin_width
opt_threshold_list.append(opt_threshold)
if (self.min_method == 'neg'):
min_num_wrong = 0 # Adjust, this is always possible with very low thr.
logging.info(' Optimal threshold in dimension %d is %.3f' % \
(i, opt_threshold))
logging.info(' Number of "%s" misclassifications: %d' % \
(self.min_method, min_num_wrong))
self.opt_threshold_list = opt_threshold_list
# ---------------------------------------------------------------------------
def test(self, w_vec_dict, match_set, non_match_set):
"""Method to test a classifier using the given weight vector dictionary and
match and non-match sets of record identifier pairs.
Weight vectors will be assigned to matches or non-matches according to
the summed distances for their values from the thresholds in each vector
element (dimension).
Will return a confusion matrix as a list of the form: [TP, FN, FP, TN].
"""
auxiliary.check_is_dictionary('w_vec_dict', w_vec_dict)
auxiliary.check_is_set('match_set', match_set)
auxiliary.check_is_set('non_match_set', non_match_set)
# Check that match and non-match sets are separate and do cover all weight
# vectors given
#
if (len(match_set.intersection(non_match_set)) > 0):
logging.exception('Intersection of match and non-match set not empty')
raise Exception
if ((len(match_set)+len(non_match_set)) != len(w_vec_dict)):
logging.exception('Weight vector dictionary of different length than' + \
' summed lengths of match and non-match sets: ' + \
'%d / %d+%d=%d' % (len(w_vec_dict), len(match_set),
len(non_match_set), len(match_set)+len(non_match_set)))
raise Exception
# Get a random vector dictionary element to get dimensionality of vectors
#
(rec_id_tuple, w_vec) = w_vec_dict.popitem()
v_dim = len(w_vec)
w_vec_dict[rec_id_tuple] = w_vec # Put back in
logging.info('')
logging.info('Testing optimal threshold classifier using %d weight ' % \
(len(w_vec_dict))+'vectors')
logging.info(' Match and non-match sets with %d and %d entries' % \
(len(match_set), len(non_match_set)))
logging.info(' Dimensionality: %d' % (v_dim))
num_true_m = 0
num_false_m = 0
num_true_nm = 0
num_false_nm = 0
for (rec_id_tuple, w_vec) in w_vec_dict.iteritems():
w_sum = sum(w_vec)
diff_sum = 0.0 # Sum of differences over vector elements (dimensions)
for i in range(v_dim):
# Get difference between this weight value and threshold
#
diff_sum += (w_vec[i] - self.opt_threshold_list[i])
if (diff_sum >= 0.0):
if (rec_id_tuple in match_set):
num_true_m += 1
else:
num_false_m += 1
else:
if (rec_id_tuple in non_match_set):
num_true_nm += 1
else:
num_false_nm += 1
assert (num_true_m+num_false_nm+num_false_m+num_true_nm) == len(w_vec_dict)
logging.info(' Results: TP = %d, FN = %d, FP = %d, TN = %d' % \
(num_true_m,num_false_nm,num_false_m,num_true_nm))
return [num_true_m, num_false_nm, num_false_m, num_true_nm]
# --------------------------------------------------------------------------
def cross_validate(self, w_vec_dict, match_set, non_match_set, n=10):
"""Method to conduct a cross validation using the given weight vector
dictionary and match and non-match sets of record identifier pairs.
Will return a confusion matrix as a list of the form: [TP, FN, FP, TN].
The cross validation approach randomly splits the weight vector
dictionary into 'n' parts (and 'n' corresponding sub-set for matches and
non-matches), and then generates 'n' optimal threshold classifiers,
tests them and finally returns the average performance of these 'n'
classifiers.
At the end of the cross validation procedure the optimal thresholds will
be set to the average values of the 'n' optimal thresholds (in each
dimension).
"""
auxiliary.check_is_integer('n', n)
auxiliary.check_is_positive('n', n)
auxiliary.check_is_dictionary('w_vec_dict', w_vec_dict)
auxiliary.check_is_set('match_set', match_set)
auxiliary.check_is_set('non_match_set', non_match_set)
# Check that match and non-match sets are separate and do cover all weight
# vectors given
#
if (len(match_set.intersection(non_match_set)) > 0):
logging.exception('Intersection of match and non-match set not empty')
raise Exception
if ((len(match_set)+len(non_match_set)) != len(w_vec_dict)):
logging.exception('Weight vector dictionary of different length than' + \
' summed lengths of match and non-match sets: ' + \
'%d / %d+%d=%d' % (len(w_vec_dict), len(match_set),
len(non_match_set), len(match_set)+len(non_match_set)))
raise Exception
# Get a random vector dictionary element to get dimensionality of vectors
#
(rec_id_tuple, w_vec) = w_vec_dict.popitem()
v_dim = len(w_vec)
w_vec_dict[rec_id_tuple] = w_vec # Put back in
logging.info('')
logging.info('Conduct %d-fold cross validation on optimal threshold ' % \
(n) + 'classifier using %d weight vectors' % \
(len(w_vec_dict)))
logging.info(' Match and non-match sets with %d and %d entries' % \
(len(match_set), len(non_match_set)))
logging.info(' Dimensionality: %d' % (v_dim))
opt_thres = [] # Keep the threshold from all folds
# Create the sub-sets of record identifier pairs for folds - - - - - - - -
#
rec_id_tuple_list = w_vec_dict.keys()
random.shuffle(rec_id_tuple_list)
fold_num_rec_id_tuple = max(1,int(round(float(len(rec_id_tuple_list))/n)))
# Split the weight vector dictionary and match and non-match sets into
# (lists containing one entry per fold) and only store test elements
#
w_vec_dict_test_list = []
m_set_test_list = []
nm_set_test_list = []
for fold in range(n):
w_vec_dict_test_list.append({})
m_set_test_list.append(set())
nm_set_test_list.append(set())
for fold in range(n):
# Calculate start and end indices for test elements for this fold
#
if (fold == (n-1)): # The last fold, get remainder of list
start = fold*fold_num_rec_id_tuple
this_fold_test_ids = rec_id_tuple_list[start:]
else: # All other folds
start = fold*fold_num_rec_id_tuple
end = start+fold_num_rec_id_tuple
this_fold_test_ids = rec_id_tuple_list[start:end]
for rec_id_tuple in this_fold_test_ids:
w_vec_dict_test_list[fold][rec_id_tuple] = w_vec_dict[rec_id_tuple]
if (rec_id_tuple in match_set):
m_set_test_list[fold].add(rec_id_tuple)
else:
nm_set_test_list[fold].add(rec_id_tuple)
assert len(w_vec_dict_test_list[fold]) == len(this_fold_test_ids)
assert len(m_set_test_list[fold]) + len(nm_set_test_list[fold]) == \
len(this_fold_test_ids)
# Loop over folds - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Generate training and test dictionaries and sets
#
for fold in range(n): # First extract test record identifier pairs
this_fold_test_m_set = m_set_test_list[fold]
this_fold_test_nm_set = nm_set_test_list[fold]
this_fold_test_w_vec_dict = w_vec_dict_test_list[fold]
this_fold_train_m_set = match_set.difference(m_set_test_list[fold])
this_fold_train_nm_set = non_match_set.difference(nm_set_test_list[fold])
this_fold_train_w_vec_dict = {}
for f2 in range(n):
if (f2 != fold):
this_fold_train_w_vec_dict.update(w_vec_dict_test_list[f2])
assert len(this_fold_test_m_set) + len(this_fold_train_m_set) == \
len(match_set)
assert len(this_fold_test_nm_set) + len(this_fold_train_nm_set) == \
len(non_match_set)
assert len(this_fold_test_w_vec_dict) + \
len(this_fold_train_w_vec_dict) == len(w_vec_dict)
#assert this_fold_test_m_set.intersection(this_fold_train_m_set) == set()
#assert this_fold_test_m_set.intersection(this_fold_test_nm_set) == set()
#assert this_fold_test_m_set.intersection(this_fold_train_nm_set) == set()
#assert this_fold_test_nm_set.intersection(this_fold_train_m_set) ==set()
#assert this_fold_test_nm_set.intersection(this_fold_train_nm_set) ==set()
#assert this_fold_train_m_set.intersection(this_fold_train_nm_set) ==set()
# Train optimal thrshold classifier and save calculated thresholds
#
self.train(this_fold_train_w_vec_dict, this_fold_train_m_set,
this_fold_train_nm_set)
opt_thres.append(self.opt_threshold_list)
del this_fold_train_w_vec_dict
# Calculate final averaged optimal thresholds - - - - - - - - - - - - - - -
#
self.opt_threshold_list = [0.0]*v_dim
for fold in range(n):
for i in range(v_dim):
self.opt_threshold_list[i] += (opt_thres[fold][i]/float(n))
logging.info('Optimal thresholds: %s' % \
(auxiliary.str_vector(self.opt_threshold_list)))
# Test on complete weight vector dictionary
#
[num_true_m,num_false_nm,num_false_m,num_true_nm]= self.test(w_vec_dict,
match_set,
non_match_set)
return [num_true_m, num_false_nm, num_false_m, num_true_nm]
# ---------------------------------------------------------------------------
def classify(self, w_vec_dict):
"""Method to classify the given weight vector dictionary using the trained
classifier.
Will return three sets with record identifier pairs: 1) match set,
2) non-match set, and 3) possible match set.
The possible match set will be empty, as this classifier classifies all
weight vectors as either matches or non-matches.
"""
auxiliary.check_is_dictionary('w_vec_dict', w_vec_dict)