-
Notifications
You must be signed in to change notification settings - Fork 543
/
api.py
1582 lines (1282 loc) · 54.1 KB
/
api.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
dedupe provides the main user interface for the library the
Dedupe class
"""
from __future__ import annotations
import itertools
import logging
import multiprocessing
import os
import pickle
import sqlite3
import tempfile
import warnings
from typing import TYPE_CHECKING, cast, overload
import numpy
import sklearn.linear_model
import sklearn.model_selection
import dedupe.blocking as blocking
import dedupe.clustering as clustering
import dedupe.core as core
import dedupe.datamodel as datamodel
import dedupe.labeler as labeler
import dedupe.predicates
import dedupe.serializer as serializer
from dedupe._typing import Literal
if TYPE_CHECKING:
from typing import (
BinaryIO,
Collection,
Generator,
Iterable,
MutableMapping,
TextIO,
Union,
)
import numpy.typing
from dedupe._typing import (
ArrayLinks,
Blocks,
BlocksInt,
BlocksStr,
Classifier,
Clusters,
ClustersInt,
ClustersStr,
Data,
DataInt,
DataStr,
JoinConstraint,
LabelsLike,
Links,
LookupResultsInt,
LookupResultsStr,
PathLike,
RecordDict,
)
from dedupe._typing import RecordDictPair as TrainingExample
from dedupe._typing import RecordDictPairs as TrainingExamples
from dedupe._typing import (
RecordID,
RecordPairs,
Scores,
TrainingData,
TupleLinks,
VariableDefinition,
)
logger = logging.getLogger(__name__)
class Matching(object):
"""
Base Class for Record Matching Classes
"""
def __init__(
self, num_cores: int | None, in_memory: bool = False, **kwargs
) -> None:
if num_cores is None:
self.num_cores = multiprocessing.cpu_count()
else:
self.num_cores = num_cores
self.in_memory = in_memory
self._fingerprinter: blocking.Fingerprinter | None = None
self.data_model: datamodel.DataModel
self.classifier: Classifier
self.predicates: Collection[dedupe.predicates.Predicate]
@property
def fingerprinter(self) -> blocking.Fingerprinter:
if self._fingerprinter is None:
raise ValueError(
"the record fingerprinter is not intialized, "
"please run the train method"
)
return self._fingerprinter
class IntegralMatching(Matching):
"""
This class is for linking class where we need to score all possible
pairs before deciding on any matches
"""
def score(self, pairs: RecordPairs) -> Scores:
"""
Scores pairs of records. Returns pairs of tuples of records id and
associated probabilities that the pair of records are match
Args:
pairs: Iterator of pairs of records
"""
try:
matches = core.scoreDuplicates(
pairs, self.data_model.distances, self.classifier, self.num_cores
)
except RuntimeError:
raise RuntimeError(
"""
You need to either turn off multiprocessing or protect
the calls to the Dedupe methods with a
`if __name__ == '__main__'` in your main module, see
https://docs.python.org/3/library/multiprocessing.html#the-spawn-and-forkserver-start-methods"""
)
return matches
class DedupeMatching(IntegralMatching):
"""
Class for Deduplication, extends Matching.
Use DedupeMatching when you have a dataset that can contain
multiple references to the same entity.
"""
@overload
def partition(
self, data: DataInt, threshold: float = 0.5
) -> ClustersInt: # pragma: no cover
...
@overload
def partition(
self, data: DataStr, threshold: float = 0.5
) -> ClustersStr: # pragma: no cover
...
def partition(self, data, threshold=0.5): # pragma: no cover
"""
Identifies records that all refer to the same entity, returns
tuples containing a sequence of record ids and corresponding
sequence of confidence score as a float between 0 and 1. The
record_ids within each set should refer to the same entity and the
confidence score is a measure of our confidence a particular entity
belongs in the cluster.
For details on the confidence score, see :func:`dedupe.Dedupe.cluster`.
This method should only used for small to moderately sized
datasets for larger data, you need may need to generate your
own pairs of records and feed them to :func:`~score`.
Args:
data: Dictionary of records, where the keys are record_ids
and the values are dictionaries with the keys being
field names
threshold: Number between 0 and 1. We
will only consider put together records into
clusters if the `cophenetic similarity
<https://en.wikipedia.org/wiki/Cophenetic>`_ of
the cluster is greater than the threshold.
Lowering the number will increase recall,
raising it will increase precision
Examples:
>>> duplicates = matcher.partition(data, threshold=0.5)
>>> duplicates
[
((1, 2, 3), (0.790, 0.860, 0.790)),
((4, 5), (0.720, 0.720)),
((10, 11), (0.899, 0.899)),
]
"""
pairs = self.pairs(data)
pair_scores = self.score(pairs)
clusters = self.cluster(pair_scores, threshold)
clusters = self._add_singletons(data.keys(), clusters)
clusters_eval = list(clusters)
_cleanup_scores(pair_scores)
return clusters_eval
@overload
@staticmethod
def _add_singletons(all_ids: Iterable[int], clusters: ClustersInt) -> ClustersInt:
...
@overload
@staticmethod
def _add_singletons(all_ids: Iterable[str], clusters: ClustersStr) -> ClustersStr:
...
@staticmethod
def _add_singletons(all_ids, clusters):
singletons = set(all_ids)
for record_ids, score in clusters:
singletons.difference_update(record_ids)
yield (record_ids, score)
for singleton in singletons:
yield (singleton,), (1.0,)
def pairs(self, data: Data) -> RecordPairs:
"""
Yield pairs of records that share common fingerprints.
Each pair will occur at most once. If you override this
method, you need to take care to ensure that this remains
true, as downstream methods, particularly :func:`cluster`, assumes
that every pair of records is compared no more than once.
Args:
data: Dictionary of records, where the keys are record_ids
and the values are dictionaries with the keys being
field names
Examples:
>>> pairs = matcher.pairs(data)
>>> list(pairs)
[
(
(1, {"name": "Pat", "address": "123 Main"}),
(2, {"name": "Pat", "address": "123 Main"}),
),
(
(1, {"name": "Pat", "address": "123 Main"}),
(3, {"name": "Sam", "address": "123 Main"}),
),
]
"""
self.fingerprinter.index_all(data)
id_type = core.sqlite_id_type(data)
# Blocking and pair generation are typically the first memory
# bottlenecks, so we'll use sqlite3 to avoid doing them in memory
with tempfile.TemporaryDirectory() as temp_dir:
if self.in_memory:
con = sqlite3.connect(":memory:")
else:
con = sqlite3.connect(temp_dir + "/blocks.db")
# Set journal mode to WAL.
con.execute("pragma journal_mode=off")
con.execute(
f"CREATE TABLE blocking_map (block_key text, record_id {id_type})"
)
con.executemany(
"INSERT INTO blocking_map values (?, ?)",
self.fingerprinter(data.items()),
)
self.fingerprinter.reset_indices()
con.execute(
"""CREATE UNIQUE INDEX record_id_block_key_idx
ON blocking_map (record_id, block_key)"""
)
con.execute(
"""CREATE INDEX block_key_idx
ON blocking_map (block_key)"""
)
con.execute("""ANALYZE""")
pairs = con.execute(
"""SELECT DISTINCT a.record_id, b.record_id
FROM blocking_map a
INNER JOIN blocking_map b
USING (block_key)
WHERE a.record_id < b.record_id"""
)
for a_record_id, b_record_id in pairs:
yield (
(a_record_id, data[a_record_id]),
(b_record_id, data[b_record_id]),
)
pairs.close()
con.close()
def cluster(self, scores: Scores, threshold: float = 0.5) -> Clusters:
r"""From the similarity scores of pairs of records, decide which groups
of records are all referring to the same entity.
Yields tuples containing a sequence of record ids and corresponding
sequence of confidence score as a float between 0 and 1. The
record_ids within each set should refer to the same entity and the
confidence score is a measure of our confidence a particular entity
belongs in the cluster.
Each confidence scores is a measure of how similar the record is
to the other records in the cluster. Let :math:`\phi(i,j)` be the pair-wise
similarity between records :math:`i` and :math:`j`. Let :math:`N` be the number of records in the cluster.
.. math::
\text{confidence score}_i = 1 - \sqrt {\frac{\sum_{j}^N (1 - \phi(i,j))^2}{N -1}}
This measure is similar to the average squared distance
between the focal record and the other records in the
cluster. These scores can be `combined to give a total score
for the cluster
<https://en.wikipedia.org/wiki/Variance#Discrete_random_variable>`_.
.. math::
\text{cluster score} = 1 - \sqrt { \frac{\sum_i^N(1 - \mathrm{score}_i)^2 \cdot (N - 1) } { 2 N^2}}
Args:
scores: a numpy `structured array <https://docs.scipy.org/doc/numpy/user/basics.rec.html>`_ with a dtype of `[('pairs', id_type, 2),
('score', 'f4')]` where dtype is either a str
or int, and score is a number between 0 and
1. The 'pairs' column contains pairs of ids of
the records compared and the 'score' column
should contains the similarity score for that
pair of records.
For each pair, the smaller id should be first.
threshold: Number between 0 and 1. We will only consider
put together records into clusters if the
`cophenetic similarity
<https://en.wikipedia.org/wiki/Cophenetic>`_ of
the cluster is greater than the threshold.
Lowering the number will increase recall,
raising it will increase precision
Examples:
>>> pairs = matcher.pairs(data)
>>> scores = matcher.scores(pairs)
>>> clusters = matcher.cluster(scores)
>>> list(clusters)
[
((1, 2, 3), (0.790, 0.860, 0.790)),
((4, 5), (0.720, 0.720)),
((10, 11), (0.899, 0.899)),
]
"""
logger.debug("matching done, begin clustering")
yield from clustering.cluster(scores, threshold)
class RecordLinkMatching(IntegralMatching):
"""
Class for Record Linkage, extends Matching.
Use RecordLinkMatching when you have two datasets that you want to merge
"""
def pairs(self, data_1: Data, data_2: Data) -> RecordPairs:
"""
Yield pairs of records that share common fingerprints.
Each pair will occur at most once. If you override this
method, you need to take care to ensure that this remains
true, as downstream methods, particularly :func:`one_to_one`,
and :func:`many_to_one` assumes that every pair of records is
compared no more than once.
Args:
data_1: Dictionary of records from first dataset, where the
keys are record_ids and the values are dictionaries
with the keys being field names
data_2: Dictionary of records from second dataset, same
form as data_1
Examples:
>>> pairs = matcher.pairs(data_1, data_2)
>>> list(pairs)
[
(
(1, {"name": "Pat", "address": "123 Main"}),
(2, {"name": "Pat", "address": "123 Main"}),
),
(
(1, {"name": "Pat", "address": "123 Main"}),
(3, {"name": "Sam", "address": "123 Main"}),
),
]
"""
self.fingerprinter.index_all(data_2)
id_type_a = core.sqlite_id_type(data_1)
id_type_b = core.sqlite_id_type(data_2)
# Blocking and pair generation are typically the first memory
# bottlenecks, so we'll use sqlite3 to avoid doing them in memory
with tempfile.TemporaryDirectory() as temp_dir:
if self.in_memory:
con = sqlite3.connect(":memory:")
else:
con = sqlite3.connect(temp_dir + "/blocks.db")
con.execute("pragma journal_mode=off")
con.executescript(
f"""CREATE TABLE blocking_map_a
(block_key text, record_id {id_type_a});
CREATE TABLE blocking_map_b
(block_key text, record_id {id_type_b});"""
)
con.executemany(
"INSERT INTO blocking_map_a values (?, ?)",
self.fingerprinter(data_1.items()),
)
con.executemany(
"INSERT INTO blocking_map_b values (?, ?)",
self.fingerprinter(data_2.items(), target=True),
)
self.fingerprinter.reset_indices()
con.executescript(
"""CREATE UNIQUE INDEX block_key_a_idx
ON blocking_map_a (record_id, block_key);
CREATE UNIQUE INDEX block_key_b_idx
ON blocking_map_b (block_key, record_id);"""
)
con.execute("""ANALYZE""")
pairs = con.execute(
"""SELECT DISTINCT a.record_id, b.record_id
FROM blocking_map_a a
INNER JOIN blocking_map_b b
USING (block_key)"""
)
for a_record_id, b_record_id in pairs:
yield (
(a_record_id, data_1[a_record_id]),
(b_record_id, data_2[b_record_id]),
)
pairs.close()
con.close()
def join(
self,
data_1: Data,
data_2: Data,
threshold: float = 0.5,
constraint: JoinConstraint = "one-to-one",
) -> Links:
"""
Identifies pairs of records that refer to the same entity.
Returns pairs of record ids with a confidence score as a float
between 0 and 1. The record_ids within the pair should refer to the
same entity and the confidence score is the estimated probability that
the records refer to the same entity.
This method should only used for small to moderately sized
datasets for larger data, you need may need to generate your
own pairs of records and feed them to the :func:`~score`.
Args:
data_1: Dictionary of records from first dataset, where the
keys are record_ids and the values are dictionaries
with the keys being field names
data_2: Dictionary of records from second dataset, same form
as data_1
threshold: Number between 0 and 1. We
will consider records as potential
duplicates if the predicted probability of
being a duplicate is above the threshold.
Lowering the number will increase recall, raising it
will increase precision
constraint: What type of constraint to put on a join.
'one-to-one'
Every record in data_1 can match at most
one record from data_2 and every record
from data_2 can match at most one record
from data_1. This is good for when both
data_1 and data_2 are from different
sources and you are interested in
matching across the sources. If,
individually, data_1 or data_2 have many
duplicates you will not get good
matches.
'many-to-one'
Every record in data_1 can match at most
one record from data_2, but more than
one record from data_1 can match to the
same record in data_2. This is good for
when data_2 is a lookup table and data_1
is messy, such as geocoding or matching
against golden records.
'many-to-many'
Every record in data_1 can match
multiple records in data_2 and vice
versa. This is like a SQL inner join.
Examples:
>>> links = matcher.join(data_1, data_2, threshold=0.5)
>>> list(links)
[
((1, 2), 0.790),
((4, 5), 0.720),
((10, 11), 0.899)
]
"""
assert constraint in {"one-to-one", "many-to-one", "many-to-many"}, (
"%s is an invalid constraint option. Valid options include "
"one-to-one, many-to-one, or many-to-many" % constraint
)
pairs = self.pairs(data_1, data_2)
pair_scores = self.score(pairs)
links: Links
if constraint == "one-to-one":
links = self.one_to_one(pair_scores, threshold)
elif constraint == "many-to-one":
links = self.many_to_one(pair_scores, threshold)
else:
links = pair_scores[pair_scores["score"] > threshold]
links_evaluated: Links = list(links) # type: ignore[assignment]
_cleanup_scores(pair_scores)
return links_evaluated
def one_to_one(self, scores: Scores, threshold: float = 0.0) -> TupleLinks:
"""From the similarity scores of pairs of records, decide which
pairs refer to the same entity.
Every record in data_1 can match at most one record from
data_2 and every record from data_2 can match at most one
record from data_1. See
https://en.wikipedia.org/wiki/Injective_function.
This method is good for when both data_1 and data_2 are from
different sources and you are interested in matching across
the sources. If, individually, data_1 or data_2 have many duplicates
you will not get good matches.
Yields pairs of record ids with a confidence score as a float
between 0 and 1. The record_ids within the pair should refer to the
same entity and the confidence score is the estimated probability that
the records refer to the same entity.
Args:
scores: a numpy `structured array <https://docs.scipy.org/doc/numpy/user/basics.rec.html>`_ with a dtype of `[('pairs', id_type, 2),
('score', 'f4')]` where dtype is either a str
or int, and score is a number between 0 and
1. The 'pairs' column contains pairs of ids of
the records compared and the 'score' column
should contains the similarity score for that
pair of records.
threshold: Number between 0 and 1. We
will consider records as potential
duplicates if the predicted probability of
being a duplicate is above the threshold.
Lowering the number will increase recall, raising it
will increase precision
Examples:
>>> pairs = matcher.pairs(data)
>>> scores = matcher.scores(pairs, threshold=0.5)
>>> links = matcher.one_to_one(scores)
>>> list(links)
[
((1, 2), 0.790),
((4, 5), 0.720),
((10, 11), 0.899)
]
"""
if threshold:
scores = scores[scores["score"] > threshold]
logger.debug("matching done, begin clustering")
yield from clustering.greedyMatching(scores)
def many_to_one(self, scores: Scores, threshold: float = 0.0) -> ArrayLinks:
"""
From the similarity scores of pairs of records, decide which
pairs refer to the same entity.
Every record in data_1 can match at most one record from
data_2, but more than one record from data_1 can match to the same
record in data_2. See
https://en.wikipedia.org/wiki/Surjective_function
This method is good for when data_2 is a lookup table and data_1
is messy, such as geocoding or matching against golden records.
Yields pairs of record ids with a confidence score as a float
between 0 and 1. The record_ids within the pair should refer to the
same entity and the confidence score is the estimated probability that
the records refer to the same entity.
Args:
scores: a numpy `structured array <https://docs.scipy.org/doc/numpy/user/basics.rec.html>`_ with a dtype of `[('pairs', id_type, 2),
('score', 'f4')]` where dtype is either a str
or int, and score is a number between 0 and
1. The 'pairs' column contains pairs of ids of
the records compared and the 'score' column
should contains the similarity score for that
pair of records.
threshold: Number between 0 and 1. We
will consider records as potential
duplicates if the predicted probability of
being a duplicate is above the threshold.
Lowering the number will increase recall, raising it
will increase precision
Examples:
>>> pairs = matcher.pairs(data)
>>> scores = matcher.scores(pairs, threshold=0.5)
>>> links = matcher.many_to_one(scores)
>>> print(list(links))
[
((1, 2), 0.790),
((4, 5), 0.720),
((7, 2), 0.623),
((10, 11), 0.899)
]
"""
logger.debug("matching done, begin clustering")
yield from clustering.pair_gazette_matching(scores, threshold, 1)
class GazetteerMatching(Matching):
def __init__(
self, num_cores: int | None, in_memory: bool = False, **kwargs
) -> None:
super().__init__(num_cores, in_memory, **kwargs)
self.db: PathLike
if self.in_memory:
self.db = ":memory:"
else:
self.temp_dir = tempfile.TemporaryDirectory()
self.db = self.temp_dir.name + "/blocks.db"
self.indexed_data: Union[
MutableMapping[int, RecordDict], MutableMapping[str, RecordDict]
]
self.indexed_data = {} # type: ignore[assignment]
def _close(self) -> None:
if not self.in_memory:
self.temp_dir.cleanup()
def __del__(self) -> None:
self._close()
@overload
def index(self, data: DataInt) -> None:
...
@overload
def index(self, data: DataStr) -> None:
...
def index(self, data): # pragma: no cover
"""
Add records to the index of records to match against. If a record in
`canonical_data` has the same key as a previously indexed record, the
old record will be replaced.
Args:
data: a dictionary of records where the keys
are record_ids and the values are
dictionaries with the keys being
field_names
"""
self.fingerprinter.index_all(data)
id_type = core.sqlite_id_type(data)
con = sqlite3.connect(self.db)
# Set journal mode to WAL.
con.execute("pragma journal_mode=wal")
con.execute(
f"""CREATE TABLE IF NOT EXISTS indexed_records
(block_key text,
record_id {id_type},
UNIQUE(block_key, record_id))"""
)
con.executemany(
"REPLACE INTO indexed_records VALUES (?, ?)",
self.fingerprinter(data.items(), target=True),
)
con.execute(
"""CREATE UNIQUE INDEX IF NOT EXISTS
indexed_records_block_key_idx
ON indexed_records
(block_key, record_id)"""
)
con.execute("""ANALYZE""")
con.commit()
con.close()
self.indexed_data.update(data)
@overload
def unindex(self, data: DataInt) -> None: # pragma: no cover
...
@overload
def unindex(self, data: DataStr) -> None: # pragma: no cover
...
def unindex(self, data): # pragma: no cover
"""
Remove records from the index of records to match against.
Args:
data: a dictionary of records where the keys
are record_ids and the values are
dictionaries with the keys being
field_names
"""
for field in self.fingerprinter.index_fields:
self.fingerprinter.unindex(
{record[field] for record in data.values()}, field
)
con = sqlite3.connect(self.db)
con.executemany(
"""DELETE FROM indexed_records
WHERE record_id = ?""",
((k,) for k in data.keys()),
)
con.commit()
con.close()
for k in data:
del self.indexed_data[k]
@overload
def blocks(self, data: DataInt) -> BlocksInt:
...
@overload
def blocks(self, data: DataStr) -> BlocksStr:
...
def blocks(self, data):
"""
Yield groups of pairs of records that share fingerprints.
Each group contains one record from data_1 paired with the records
from the indexed records that data_1 shares a fingerprint with.
Each pair within and among blocks will occur at most once. If
you override this method, you need to take care to ensure that
this remains true, as downstream methods, particularly
:func:`many_to_n`, assumes that every pair of records is compared no
more than once.
Args:
data: Dictionary of records, where the keys are record_ids
and the values are dictionaries with the keys being
field names
Examples:
>>> blocks = matcher.pairs(data)
>>> print(list(blocks)
[
[
(
(1, {"name": "Pat", "address": "123 Main"}),
(8, {"name": "Pat", "address": "123 Main"}),
),
(
(1, {"name": "Pat", "address": "123 Main"}),
(9, {"name": "Sam", "address": "123 Main"}),
),
],
[
(
(2, {"name": "Sam", "address": "2600 State"}),
(5, {"name": "Pam", "address": "2600 Stat"}),
),
(
(2, {"name": "Sam", "address": "123 State"}),
(7, {"name": "Sammy", "address": "123 Main"}),
),
],
]
"""
id_type = core.sqlite_id_type(data)
con = sqlite3.connect(self.db, check_same_thread=False)
con.execute("BEGIN")
con.execute(
f"CREATE TEMPORARY TABLE blocking_map (block_key text, record_id {id_type})"
)
con.executemany(
"INSERT INTO blocking_map VALUES (?, ?)", self.fingerprinter(data.items())
)
pairs = con.execute(
"""SELECT DISTINCT a.record_id, b.record_id
FROM blocking_map a
INNER JOIN indexed_records b
USING (block_key)
ORDER BY a.record_id"""
)
pair_blocks: Union[
Iterable[tuple[int, Iterable[tuple[int, int]]]],
Iterable[tuple[str, Iterable[tuple[str, str]]]],
]
pair_blocks = itertools.groupby(pairs, lambda x: x[0])
for _, pair_block in pair_blocks:
yield [
(
(a_record_id, data[a_record_id]),
(b_record_id, self.indexed_data[b_record_id]),
)
for a_record_id, b_record_id in pair_block
]
pairs.close()
con.execute("ROLLBACK")
con.close()
def score(self, blocks: Blocks) -> Generator[Scores, None, None]:
"""
Scores groups of pairs of records. Yields structured numpy arrays
representing pairs of records in the group and the associated
probability that the pair is a match.
Args:
blocks: Iterator of blocks of records
"""
matches = core.scoreGazette(
blocks, self.data_model.distances, self.classifier, self.num_cores
)
return matches
def many_to_n(
self,
score_blocks: Iterable[Scores],
threshold: float = 0.0,
n_matches: int = 1,
) -> ArrayLinks:
"""
For each group of scored pairs, yield the highest scoring N pairs
Args:
score_blocks: Iterator of numpy `structured arrays <https://docs.scipy.org/doc/numpy/user/basics.rec.html>`_,
each with a dtype of `[('pairs', id_type, 2),
('score', 'f4')]` where dtype is either a str
or int, and score is a number between 0 and
1. The 'pairs' column contains pairs of ids of
the records compared and the 'score' column
should contains the similarity score for that
pair of records.
threshold: Number between 0 and 1. We
will consider records as potential
duplicates if the predicted probability of
being a duplicate is above the threshold.
Lowering the number will increase recall, raising it
will increase precision
n_matches: How many top scoring pairs to select per group
"""
yield from clustering.gazetteMatching(score_blocks, threshold, n_matches)
@overload
def search(
self,
data: DataInt,
threshold: float = 0.0,
n_matches: int = 1,
generator: bool = False,
) -> LookupResultsInt: # pragma: no cover
...
@overload
def search(
self,
data: DataStr,
threshold: float = 0.0,
n_matches: int = 1,
generator: bool = False,
) -> LookupResultsStr: # pragma: no cover
...
def search(
self,
data,
threshold=0.0,
n_matches=1,
generator=False,
): # pragma: no cover
"""
Identifies pairs of records that could refer to the same entity,
returns tuples containing tuples of possible matches, with a
confidence score for each match. The record_ids within each
tuple should refer to potential matches from a messy data
record to canonical records. The confidence score is the
estimated probability that the records refer to the same
entity.
Args:
data: a dictionary of records from a messy
dataset, where the keys are record_ids and
the values are dictionaries with the keys
being field names.
threshold: a number between 0 and 1. We will consider
records as potential duplicates if the predicted
probability of being a duplicate is
above the threshold.
Lowering the number will increase
recall, raising it will increase
precision
n_matches: the maximum number of possible matches from
canonical_data to return for each record in
data. If set to `None` all possible
matches above the threshold will be
returned.
generator: when `True`, match will generate a sequence of
possible matches, instead of a list.
Examples:
>>> matches = gazetteer.search(data, threshold=0.5, n_matches=2)
>>> print(matches)
[
(((1, 6), 0.72), ((1, 8), 0.6)),
(((2, 7), 0.72),),
(((3, 6), 0.72), ((3, 8), 0.65)),
(((4, 6), 0.96), ((4, 5), 0.63)),
]
"""
blocks = self.blocks(data)
pair_scores = self.score(blocks)
search_results = self.many_to_n(pair_scores, threshold, n_matches)