-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathmodel.py
More file actions
1572 lines (1426 loc) · 72.6 KB
/
model.py
File metadata and controls
1572 lines (1426 loc) · 72.6 KB
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
from __future__ import annotations
from s2and.eval import b3_precision_recall_fscore
from s2and.featurizer import FeaturizationInfo, many_pairs_featurize
from s2and.data import ANDData
from s2and.consts import LARGE_INTEGER, DEFAULT_CHUNK_SIZE
from s2and.subblocking import make_subblocks
from s2and.text import same_prefix_tokens
from typing import Dict, Optional, Any, Union, List, Tuple, cast
from collections import defaultdict
import warnings
import time
from functools import partial
from tqdm import tqdm
import logging
import copy
import math
import inspect
import numpy as np
from scipy.cluster.hierarchy import fcluster
from hyperopt import hp, fmin, tpe, Trials, space_eval
from hyperopt.pyll import scope
from fastcluster import linkage
import lightgbm as lgb
from sklearn.metrics import roc_auc_score
from sklearn.base import clone
from sklearn.base import TransformerMixin, BaseEstimator
from sklearn.exceptions import EfficiencyWarning
logger = logging.getLogger("s2and")
class Clusterer:
"""
A wrapper for learning a clusterer
Args:
featurizer_info: FeaturizationInfo
Featurization information
classifier: sklearn compatible model
Classifier which uses pairwise features to make a distance matrix
val_blocks_size: int
How many blocks to use during hyperparam optimization.
Defaults to None, which uses all of them.
cluster_model: sklearn compatible model
Clusterer model
Defaults to None, which uses FastCluster with average linking.
search_space: Dict
Search space for the hyperpamater optimization.
Defaults to None, which uses a space appropriate to FastCluster.
n_iter: int
Number of hyperparameter evaluations
n_jobs: int
Parallelize each clusterer this many ways
use_cache: bool
Whether to use the cache when making distance matrices
use_default_constraints_as_supervision: bool
Whether to use the default constraints when constructing the distance matrices.
These are high precision and can save a lot of compute/time.
random_state: int
Random state
nameless_classifier: sklearn compatible model
A second classifier which uses pairwise features excluding all name information, and
whose predictions are averaged with the main classifier. Won't be used if None
nameless_featurizer_info: FeaturizationInfo
The FeaturizationInfo for the second classifier. Won't be used if None
dont_merge_cluster_seeds: bool
this flag controls whether to use cluster seeds to enforce "dont merge"
as well as "must merge" constraints
batch_size: int
batch size for featurization, lower means less memory, but slower
"""
def __init__(
self,
featurizer_info: FeaturizationInfo,
classifier: Any,
val_blocks_size: Optional[int] = None,
cluster_model: Optional[Any] = None,
search_space: Optional[Dict[str, Any]] = None,
n_iter: int = 25,
n_jobs: int = 16,
use_cache: bool = False,
use_default_constraints_as_supervision: bool = True,
random_state: int = 42,
nameless_classifier: Optional[Any] = None,
nameless_featurizer_info: Optional[FeaturizationInfo] = None,
dont_merge_cluster_seeds: bool = True,
batch_size: int = 1000000,
):
self.featurizer_info = featurizer_info
self.nameless_featurizer_info = nameless_featurizer_info
self.classifier = copy.deepcopy(classifier)
self.nameless_classifier = copy.deepcopy(nameless_classifier)
self.val_blocks_size = val_blocks_size
self.n_iter = n_iter
self.n_jobs = n_jobs
self.random_state = random_state
self.use_cache = use_cache
self.use_default_constraints_as_supervision = use_default_constraints_as_supervision
self.dont_merge_cluster_seeds = dont_merge_cluster_seeds
if cluster_model is None:
self.cluster_model = FastCluster(linkage="average")
else:
self.cluster_model = copy.deepcopy(cluster_model)
if search_space is None:
self.search_space = {"eps": hp.uniform("eps", 0, 1)}
else:
self.search_space = search_space
self.hyperopt_trials_store: Optional[Union[Trials, List[Trials]]] = None
self.best_params: Optional[Dict[Any, Any]] = None
self.batch_size = batch_size
@staticmethod
def filter_blocks(block_dict: Dict[str, List[str]], num_to_keep: Optional[int] = None) -> Dict[str, List[str]]:
"""
Filter out blocks of size 1, as they are not useful or train/val
Parameters
----------
block_dict: Dict
the block dictionary
num_to_keep: int
the number of blocks to keep, keeps all if None
Returns
-------
either the loaded json, or the passed in object
"""
# blocks with only 1 element are useless for train/val
# and we can only keep as many as is specified
out_dict = {}
count = 0
for block_key, signatures in block_dict.items():
if len(signatures) > 1:
out_dict[block_key] = signatures
count += 1
# early stopping if we have enough
if num_to_keep is not None and count == num_to_keep:
return out_dict
return out_dict
def distance_matrix_helper(
self,
block_dict: Dict,
dataset: ANDData,
partial_supervision: Dict[Tuple[str, str], Union[int, float]],
incremental_dont_use_cluster_seeds: bool = False,
):
"""
Helper generator function to yield one pair for batch featurization on the fly
Parameters
----------
block_dict: Dict
the block dictionary
dataset: ANDData
the dataset
partial_supervision: Dict
the dictionary of partial supervision provided with this dataset/these blocks
incremental_dont_use_cluster_seeds: bool
Are we clustering in incremental mode? If so, don't use the cluster seeds that came with the dataset
Returns
-------
yields pairs of ((sig id 1, sig id 2, label), index pair into the distance matrix, block key)
"""
for block_key, signatures in block_dict.items():
for i, j in zip(*np.triu_indices(len(signatures), k=1)):
# subtracting LARGE_INTEGER so many_pairs_featurize knows not to make features
label = np.nan
if (signatures[i], signatures[j]) in partial_supervision:
label = partial_supervision[(signatures[i], signatures[j])] - LARGE_INTEGER
elif (signatures[j], signatures[i]) in partial_supervision:
label = partial_supervision[(signatures[j], signatures[i])] - LARGE_INTEGER
elif self.use_default_constraints_as_supervision:
value = dataset.get_constraint(
signatures[i],
signatures[j],
dont_merge_cluster_seeds=self.dont_merge_cluster_seeds,
incremental_dont_use_cluster_seeds=incremental_dont_use_cluster_seeds,
)
if value is not None:
label = value - LARGE_INTEGER
yield ((signatures[i], signatures[j], label), (i, j), block_key)
def make_distance_matrices(
self,
block_dict: Dict[str, List[str]],
dataset: ANDData,
partial_supervision: Dict[Tuple[str, str], Union[int, float]] = {},
disable_tqdm: bool = False,
incremental_dont_use_cluster_seeds: bool = False,
) -> Dict[str, np.ndarray]:
"""
Creates the distance matrices for the input blocks.
Note: This function is much more complicated than it needs to be in an
effort to reduce its memory footprint
Parameters
----------
block_dict: Dict
the block dictionary to make distances for
dataset: ANDData
the dataset
partial_supervision: Dict
the dictionary of partial supervision provided with this dataset/these blocks
disable_tqdm: bool
whether to turn off the tqdm progress bars in this function
incremental_dont_use_cluster_seeds: bool
Are we clustering in incremental mode? If so, don't use the cluster seeds that came with the dataset
Returns
-------
Dict: the distance matrix dictionary, keyed by block key
"""
logger.info(f"Making {len(block_dict)} distance matrices")
logger.info("Initializing pairwise_probas")
# initialize pairwise_probas with correctly size arrays
pairwise_probas = {}
num_pairs = 0
for block_key, signatures in block_dict.items():
block_size = len(signatures)
num_pairs += int(block_size * (block_size - 1) / 2)
if isinstance(self.cluster_model, FastCluster):
# flattened pdist style
pairwise_proba = np.zeros(int(block_size * (block_size - 1) / 2), dtype=np.float16)
else:
pairwise_proba = np.zeros((block_size, block_size), dtype=np.float16)
pairwise_probas[block_key] = pairwise_proba
logger.info(f"Pairwise probas initialized with {num_pairs} elements, starting making all pairs")
# featurize and predict in batches
helper_output = self.distance_matrix_helper(
block_dict,
dataset,
partial_supervision,
incremental_dont_use_cluster_seeds=incremental_dont_use_cluster_seeds,
)
prev_block_key = ""
batch_num = 0
num_batches = math.ceil(num_pairs / self.batch_size)
while True:
logger.info(f"Featurizing batch {batch_num}/{num_batches}")
count = 0
pairs = []
indices = []
blocks = []
# iterate over a batch_size number of pairs
for item in helper_output:
pairs.append(item[0])
indices.append(item[1])
blocks.append(item[2])
count += 1
if count == self.batch_size:
break
if len(pairs) == 0:
break
batch_features, _, batch_nameless_features = many_pairs_featurize(
pairs,
dataset,
self.featurizer_info,
self.n_jobs,
use_cache=self.use_cache,
chunk_size=DEFAULT_CHUNK_SIZE,
nameless_featurizer_info=self.nameless_featurizer_info,
)
# get predictions where there isn't partial supervision
# and fill the rest with partial supervision
# undoing the offset by LARGE_INTEGER from above
logger.info("Making predict flags to separate partial supervision from prediction")
batch_labels = np.array([i[2] for i in pairs])
predict_flag = np.isnan(batch_labels)
not_predict_flag = ~predict_flag
batch_predictions = np.zeros(len(batch_features))
# index 0 is p(not the same)
logger.info("Doing pairwise classification")
if np.any(predict_flag):
if self.nameless_classifier is not None:
batch_predictions[predict_flag] = (
self.classifier.predict_proba(batch_features[predict_flag, :])[:, 0]
+ self.nameless_classifier.predict_proba(
batch_nameless_features[predict_flag, :] # type: ignore
)[:, 0]
) / 2
else:
batch_predictions[predict_flag] = self.classifier.predict_proba(batch_features[predict_flag, :])[
:, 0
]
if np.any(not_predict_flag):
batch_predictions[not_predict_flag] = batch_labels[not_predict_flag] + LARGE_INTEGER
logger.info("Constructing distance matrices")
for within_batch_index, (prediction, signature_pair) in tqdm(
enumerate(zip(batch_predictions, pairs)),
total=len(batch_predictions),
desc="Writing matrices",
disable=disable_tqdm,
):
block_key = blocks[within_batch_index]
if block_key != prev_block_key:
block_key_start_index = blocks.index(block_key) + (batch_num * self.batch_size)
pairwise_proba = pairwise_probas[block_key]
if isinstance(self.cluster_model, FastCluster):
index = (batch_num * self.batch_size + within_batch_index) - block_key_start_index
pairwise_proba[index] = prediction
else:
i, j = indices[within_batch_index]
pairwise_proba[i, j] = prediction
prev_block_key = block_key
if count < self.batch_size:
break
batch_num += 1
if not isinstance(self.cluster_model, FastCluster):
for pairwise_proba in pairwise_probas.values():
pairwise_proba += pairwise_proba.T
np.fill_diagonal(pairwise_proba, 0)
logger.info(f"{len(block_dict)} distance matrices made")
return pairwise_probas
def fit(
self,
datasets: Union[ANDData, List[ANDData]],
val_dists_precomputed: Optional[Dict[str, Dict[str, np.ndarray]]] = None,
metric_for_hyperopt: str = "b3",
) -> Clusterer:
"""
Fits the clusterer
Parameters
----------
datasets: List[ANDData]
the list of datasets to use for validations
val_dists_precomputed: Dict
precomputed distance matrices
metric_for_hyperopt: string
the metric to use for hyperparamter optimization
Returns
-------
Clusterer: a fit clusterer, also sets the best params
"""
assert metric_for_hyperopt in {"b3", "ratio"}
logger.info("Fitting clusterer")
if isinstance(datasets, ANDData):
datasets = [datasets]
val_block_dict_list = []
val_cluster_to_signatures_list = []
val_dists_list = []
weights: List[float] = []
for dataset in datasets:
# blocks
train_block_dict, val_block_dict, _ = dataset.split_cluster_signatures()
# incremental setting uses all the signatures in train and val
# block-wise split uses only validation set for building the clustering model
if dataset.unit_of_data_split == "time" or dataset.unit_of_data_split == "signatures":
for block_key, signatures in train_block_dict.items():
if block_key in val_block_dict:
val_block_dict[block_key].extend(signatures)
# we don't need val blocks with only a single element
val_block_dict = self.filter_blocks(val_block_dict, self.val_blocks_size)
val_block_dict_list.append(val_block_dict)
# block ground truth labels: cluster_to_signatures
val_cluster_to_signatures = dataset.construct_cluster_to_signatures(val_block_dict)
val_cluster_to_signatures_list.append(val_cluster_to_signatures)
# distance matrix
if val_dists_precomputed is None:
val_dists = self.make_distance_matrices(val_block_dict, dataset)
else:
val_dists = val_dists_precomputed[dataset.name]
val_dists_list.append(val_dists)
# weights for weighted F1 average: total # of signatures in dataset
weights.append(np.sum([len(i) for i in val_block_dict.values()]))
def obj(params):
self.set_params(params)
f1s = []
ratios = []
for val_block_dict, val_cluster_to_signatures, val_dists in zip(
val_block_dict_list, val_cluster_to_signatures_list, val_dists_list
):
pred_clusters, _ = self.predict(
val_block_dict,
dataset=None,
dists=val_dists,
)
(
_,
_,
f1,
_,
pred_bigger_ratios,
true_bigger_ratios,
) = b3_precision_recall_fscore(val_cluster_to_signatures, pred_clusters)
ratios.append(np.mean(pred_bigger_ratios + true_bigger_ratios))
f1s.append(f1)
if metric_for_hyperopt == "ratio":
return np.average(ratios, weights=weights)
elif metric_for_hyperopt == "b3":
# minimize means we need to negate
return -np.average(f1s, weights=weights)
self.hyperopt_trials_store = Trials()
_ = fmin(
fn=obj,
space=self.search_space,
algo=partial(tpe.suggest, n_startup_jobs=5),
max_evals=self.n_iter,
trials=self.hyperopt_trials_store,
rstate=np.random.RandomState(self.random_state),
)
# hyperopt has some problems with hp.choice so we need to do this:
assert self.hyperopt_trials_store is not None
trials_store = cast(Trials, self.hyperopt_trials_store)
best_params = space_eval(self.search_space, trials_store.argmin)
self.best_params = {k: intify(v) for k, v in best_params.items()}
self.set_params(self.best_params)
logger.info("Clusterer fit")
return self
def set_params(self, params: Optional[Dict[str, Any]], clone_flag: bool = False):
"""
Sets params on the cluster model
Parameters
----------
params: Dict
the params to set
clone_flag: bool
whether to return a clone of the cluster model
"""
if params is None:
params = {}
else:
params = {k: intify(v) for k, v in params.items()}
if clone_flag:
cluster_model = clone(self.cluster_model)
cluster_model.set_params(**params)
return cluster_model
else:
self.cluster_model.set_params(**params)
def predict(
self,
block_dict: Dict[str, List[str]],
dataset: ANDData,
dists: Optional[Dict[str, np.ndarray]] = None,
cluster_model_params: Optional[Dict[str, Any]] = None,
partial_supervision: Dict[Tuple[str, str], Union[int, float]] = {},
use_s2_clusters: bool = False,
incremental_dont_use_cluster_seeds: bool = False,
batching_threshold: Optional[int] = None,
desired_memory_use: Optional[int] = None,
) -> Tuple[Dict[str, List[str]], Optional[Dict[str, np.ndarray]]]:
"""
Predicts clusters
Parameters
----------
block_dict: Dict
the block dict to predict clusters from
dataset: ANDData
the dataset
dists: Dict
(optional) precomputed distance matrices
cluster_model_params: Dict
params to set on the cluster model
partial_supervision: Dict
the dictionary of partial supervision provided with this dataset/these blocks
use_s2_clusters: bool
whether to "predict" using the clusters from Semantic Scholar's old system
incremental_dont_use_cluster_seeds: bool
Are we clustering in incremental mode? If so, don't use the cluster seeds that came with the dataset
Don't use if you don't know what this is
batching_threshold: int
If the number of signatures in a block is above this number, we will use subblocking on the block.
This means that the single-letter first names will be sent through via predict_incremental.
Defaults to None, which means no batching occurs
desired_memory_use: int
If batching_threshold is not None, then this is the desired memory use for predict_incremental.
The units of this are the same as the units of batching_threshold -> number of signatures.
If None, then using batching_threshold * batching_threshold as the desired memory use.
Note: batching_threshold is a hack to get around OOM issues. We will assume that it implies
that we don't want to ever take up more memory than (batching_threshold ** 2)
Returns
-------
Dict: the predicted clusters
Dict: the predicted distance matrices
"""
# the approach will be to (1) take every block, apply subblocking function to it
# (2) then run the clusterer on the subblocked blocks, taking care to remove that that are single-letter first names
# (3) then run predict incremental on the single-letter first names
if batching_threshold is not None:
assert batching_threshold > 0, "Batching threshold must be positive"
assert dists is None, "If batching_threshold is not None, then can't use precomputed dists"
if desired_memory_use is None:
desired_memory_use = batching_threshold * batching_threshold
# run subblocking on each block in the block_dict
block_dict_subblocked = {}
for block_key, block_signatures in block_dict.items():
if len(block_signatures) > batching_threshold:
# run subblocking on this block
subblocks = make_subblocks(block_signatures, dataset, maximum_size=batching_threshold)
# add these subblocks to the block_dict
for subblock_key, subblock_signatures in subblocks.items():
block_dict_subblocked[block_key + "|subblock=" + subblock_key] = subblock_signatures
assert len(subblock_signatures) <= batching_threshold, "Subblock is too big for some reason!"
else:
# add this block to the block_dict_subblocked
block_dict_subblocked[block_key] = block_signatures
# now run predict_helper on the blocks in block_dict_subblocked
# pull out all of the ones that are single-letter first names
block_dict_subblocked_single_letter_first_names = {
block_key: block_signatures
for block_key, block_signatures in block_dict_subblocked.items()
if len(dataset.signatures[block_signatures[0]].author_info_first_normalized_without_apostrophe) <= 1
}
block_dict_subblocked_multiple_letter_first_names = {
block_key: block_signatures
for block_key, block_signatures in block_dict_subblocked.items()
if block_key not in block_dict_subblocked_single_letter_first_names
}
# edge case: where there are no block_dict_subblocked_multiple_letter_first_names
# so then it makes no sense to (1) run predict on multiple letters and (2) incremental on single.
# the only thing we can do is run predict on the multi.
if len(block_dict_subblocked_multiple_letter_first_names) == 0:
# not really true, but it makes the code much easier below
alert_flag = True
block_dict_subblocked_multiple_letter_first_names = block_dict_subblocked_single_letter_first_names
block_dict_subblocked_single_letter_first_names = {}
else:
alert_flag = False
pred_clusters = {}
# ideally we would batch the subblocks for predictions
# but it's hard to know how to batch since this can be called
# from inside of predict_incremental, which has different OOM behavior.
# so just doing it one at a time here
if len(block_dict_subblocked_multiple_letter_first_names) > 0:
if alert_flag:
logger.info("Note! There are no subblocks with multiple letter first names")
logger.info("Running predict on subblocks with single letter first names")
else:
logger.info("Running predict on subblocks with multiple letter first names")
predict_times = {}
for block_key, block_signatures in block_dict_subblocked_multiple_letter_first_names.items():
logger.info(f"Working on subblock {block_key}")
start = time.time()
pred_clusters_intermediate, _ = self.predict_helper(
{block_key: block_signatures},
dataset,
None, # precomputed dists is too hard to do here
cluster_model_params,
partial_supervision,
use_s2_clusters,
incremental_dont_use_cluster_seeds,
)
end = time.time()
total_predict_time = end - start
predict_times[block_key] = total_predict_time
pred_clusters.update(pred_clusters_intermediate)
logger.info(f"Finished, here's how long each took: {predict_times}")
# now we run predict_incremental on the single-letter first name blocks, one block at a time
# and we will be using the pred_clusters as cluster_seeds_require because
# that's how predict_incremental works: cluster_seeds_require is what is already clustered
# and the input to predict_incremental will be assigned into those seed clusters
# note: storing the original cluster_seeds_require so we can restore it later
if len(block_dict_subblocked_single_letter_first_names) > 0:
logger.info("Running predict incremental on subblocks with single letter first names")
cluster_seeds_require_original = copy.deepcopy(dataset.cluster_seeds_require)
dataset.cluster_seeds_require = {}
for cluster_id, signatures in pred_clusters.items():
for signature in signatures:
dataset.cluster_seeds_require[signature] = cluster_id # type: ignore
predict_times = {}
for block_key, block_signatures in block_dict_subblocked_single_letter_first_names.items():
# we have to be super careful here and adjust the batching threshold take into account
# the implied requirement of passing batching_threshold into batch predict:
# it essentially assumes that max memory is batching_threshold ** 2,
# but it could be MUCH bigger here since predict incremental memory use is up to
# (batching_threshold * (total_block_size - batching_threshold))
# so we need a special batching_threshold just for this operation
# this is the number of signatures already assigned
N = len(dataset.cluster_seeds_require)
actual_memory_usage = len(block_signatures) * N
print(
f"N_seeds = {N}",
f"N_signatures = {len(block_signatures)}",
f"desired_memory_use: {desired_memory_use}",
f"actual_memory_usage: {actual_memory_usage}",
)
if actual_memory_usage > desired_memory_use:
# we need to have a loop_batching_threshold such that
# loop_batching_threshold * N = desired_memory_use
loop_batching_threshold = int(desired_memory_use / N)
else:
# already within memory limits using no batching
loop_batching_threshold = None # type: ignore
logger.info(
f"Working on subblock {block_key} with computed batching threshold {loop_batching_threshold}"
)
start_predict_time = time.time()
pred_clusters_intermediate = self.predict_incremental(
block_signatures,
dataset,
prevent_new_incompatibilities=True,
batching_threshold=loop_batching_threshold,
partial_supervision=partial_supervision,
)
end_predict_time = time.time()
total_predict_time = end_predict_time - start_predict_time
predict_times[block_key] = total_predict_time
# again, make cluster seeds require
dataset.cluster_seeds_require = {}
for cluster_id, signatures in pred_clusters_intermediate.items():
for signature in signatures:
dataset.cluster_seeds_require[signature] = cluster_id # type: ignore
# undoing the damage
logger.info(
f"Finished subblocked predict incremental. Here's how long each subblock took:", predict_times
)
dataset.cluster_seeds_require = cluster_seeds_require_original
# the output of predict_incremental_helper has the ENTIRE clustering, not just the new stuff
pred_clusters = pred_clusters_intermediate
dists = None
else:
# normal mode - everything goes through full block clustering
logger.info("Running predict on full blocks - no subblocking")
start = time.time()
pred_clusters, dists = self.predict_helper(
block_dict,
dataset,
dists,
cluster_model_params,
partial_supervision,
use_s2_clusters,
incremental_dont_use_cluster_seeds,
)
end = time.time()
total_predict_time = end - start
logger.info(f"Finished predict on full blocks. Time taken: {total_predict_time}")
return dict(pred_clusters), dists
def predict_helper(
self,
block_dict: Dict[str, List[str]],
dataset: ANDData,
dists: Optional[Dict[str, np.ndarray]] = None,
cluster_model_params: Optional[Dict[str, Any]] = None,
partial_supervision: Dict[Tuple[str, str], Union[int, float]] = {},
use_s2_clusters: bool = False,
incremental_dont_use_cluster_seeds: bool = False,
) -> Tuple[Dict[str, List[str]], Optional[Dict[str, np.ndarray]]]:
"""
Predicts clusters
Parameters
----------
block_dict: Dict
the block dict to predict clusters from
dataset: ANDData
the dataset
dists: Dict
(optional) precomputed distance matrices
cluster_model_params: Dict
params to set on the cluster model
partial_supervision: Dict
the dictionary of partial supervision provided with this dataset/these blocks
use_s2_clusters: bool
whether to "predict" using the clusters from Semantic Scholar's old system
incremental_dont_use_cluster_seeds: bool
Are we clustering in incremental mode? If so, don't use the cluster seeds that came with the dataset
Returns
-------
Dict: the predicted clusters
Dict: the predicted distance matrices
"""
pred_clusters = defaultdict(list)
if use_s2_clusters:
for _, signature_list in block_dict.items():
for _signature in signature_list:
s2_cluster_key = dataset.signatures[_signature].author_id
pred_clusters[s2_cluster_key].append(_signature)
return dict(pred_clusters), dists
if dists is None:
dists = self.make_distance_matrices(
block_dict,
dataset,
partial_supervision,
incremental_dont_use_cluster_seeds=incremental_dont_use_cluster_seeds,
)
# we may need this set later for post-hoc merging
if self.use_default_constraints_as_supervision:
all_disallow_signature_ids = set()
for sig_id_a, sig_id_b in dataset.cluster_seeds_disallow:
all_disallow_signature_ids.add(sig_id_a)
all_disallow_signature_ids.add(sig_id_b)
for block_key in block_dict.keys():
if block_key in dists and len(block_dict[block_key]) > 1:
cluster_model = self.set_params(cluster_model_params, clone_flag=True)
with warnings.catch_warnings():
# annoying sparse matrix not sorted warning
warnings.simplefilter("ignore", category=EfficiencyWarning)
cluster_model.fit(dists[block_key])
labels = cluster_model.labels_
# in HDBSCAN the labels of -1 are actually "outliers"
# each of these gets its own label starting at
# max label + 1 and going up
max_label = labels.max()
negative_one_label_locations = np.where(labels == -1)[0]
for i, loc in enumerate(negative_one_label_locations):
labels[loc] = max_label + 1 + i
if self.use_default_constraints_as_supervision:
# at this point it is possible that clusters that should be merged
# are STILL not joined together
# due to the 0 enforced distance not being enough to outweigh
# a lot of large distances. the 0 enforced distance is between pairs
# of signatures that are passed in via cluster_seeds_require.
# this is a way to tell S2AND that we want these two to be in the same
# cluster. but the way that clusters are joined is that we compute
# *average* distance between all pairs, so the 0s may not be enough
# to drag the average below the threshold eps.
# so we manually go through the clusters
# find which ones overlap according to cluster_seeds_require
# note: if the signature id appears in cluster_seeds_disallow
# then we won't try to merge it as there may be conflicts
# that there is no clear way to resolve
inverse_id_map = defaultdict(set)
for signature_id, label in zip(block_dict[block_key], labels):
if (
signature_id in dataset.cluster_seeds_require
and signature_id not in all_disallow_signature_ids
):
inverse_id_map[dataset.cluster_seeds_require[signature_id]].add(label)
# now join any clusters that have overlapping ids
# this is a tad tricky because as we merge clusters, we need to
# keep track of where they are going
to_join_sets = [sorted(join_set) for join_set in inverse_id_map.values() if len(join_set) > 1]
mapped_labels = {label: label for label in labels}
labels = np.array(labels)
for join_set in to_join_sets:
for other_label in join_set[1:]:
labels[labels == mapped_labels[other_label]] = mapped_labels[join_set[0]]
mapped_labels[other_label] = mapped_labels[join_set[0]]
labels = list(labels)
else:
labels = [0]
for signature, label in zip(block_dict[block_key], labels):
pred_clusters[block_key + "_" + str(label)].append(signature)
return dict(pred_clusters), dists
def predict_incremental(
self,
block_signatures: List[str],
dataset: ANDData,
prevent_new_incompatibilities: bool = True,
batching_threshold: Optional[int] = None,
partial_supervision: Dict[Tuple[str, str], Union[int, float]] = {},
):
"""
Predict clustering in incremental mode. This assumes that the majority of the labels are passed
in using the cluster_seeds_require parameter of the dataset class, and skips work by simply assigning each
unassigned signature to the closest cluster if distance is less than eps, and then separately clusters all
the unassigned signatures that are not within eps of any existing cluster.
Corrected, claimed profiles should be noted via the altered_cluster_signatures parameter (in ANDData).
Then predict_incremental performs a pre-clustering step on each altered cluster to determine how
S2AND would divide it into clusters. Mentions are incrementally added to these new subclusters,
then reassembled to restore the complete claimed profile when S2AND returns results.
Currently this would be useful in the following situation. We have a massive block, for which we want
to cluster a small number of new signatures into (block size * number of new signatures should be less
than the normal batch size).
Note: this function was designed to work on a single block at a time.
Parameters
----------
block_signatures: List[str]
the signature ids in the block to predict from
dataset: ANDData
the dataset
prevent_new_incompatibilities: bool
if True, prevents the addition to a cluster of new first names that are not prefix match
or in the name pairs list, for at least one existing name in the cluster. This can happen
if a claimed cluster has D Jones and David Jones, s2and would have split that cluster into two,
and then s2and might add Donald Jones to the D Jones cluster, and once remerged, the resulting
final cluster would have D Jones, David Jones, and Donald Jones.
batching_threshold: int
If there are more unassigned signatures than this number,
they will be predicted in batches of this size. This is to prevent OOM errors.
Defaults to None, which means no batching occurs
partial_supervision: Dict
the dictionary of partial supervision provided with this dataset/these blocks
Returns
-------
Dict: the predicted clusters
"""
if batching_threshold is not None and len(block_signatures) > batching_threshold:
assert batching_threshold > 0, "Batching threshold must be positive"
# STEP 1: Make subblocks
logger.info(f"Too many signatures to do all at once for predict_incremental. Subblocking...")
subblocks = make_subblocks(block_signatures, dataset, maximum_size=batching_threshold)
cluster_seeds_require_original = copy.deepcopy(dataset.cluster_seeds_require)
# STEP 2: do predict_incremental on each subblock
# and keep updating the cluster_seeds_require as we go
predict_times = {}
for subblock_key, subblock_signatures in subblocks.items():
logger.info(
f"Beginning incremental clustering for {len(subblock_signatures)} signatures for subblock {subblock_key}..."
)
# since the size of each subblock is <= batching_threshold
# and generally the number of signatures to do incrementally << number of signatures
# in cluster_seed_require
# the helper should be able to do a full block clustering on the unassigned signatures
# without violating the implied maximum # of pairs constrained by batching_threshold.
# to be clear: the biggest block in memory should be
# max(batching_threshold * (total_block_size - batching_threshold), batching_threshold ** 2)
start_predict_time = time.time()
pred_clusters_intermediate = self.predict_incremental_helper(
subblock_signatures,
dataset,
prevent_new_incompatibilities=prevent_new_incompatibilities,
partial_supervision=partial_supervision,
)
end_predict_time = time.time()
total_predict_time = end_predict_time - start_predict_time
predict_times[subblock_key] = total_predict_time
# now we have to update dataset.cluster_seeds_require with what's in pred_clusters_intermediate
# remembering to undo the changes later
# note that cluster_seeds_require is in this format:
# cluster_seeds_require[signature_id] = cluster_id
# and pred_clusters_intermediate is the inverse...
# so have to invert it
dataset.cluster_seeds_require = {}
for cluster_id, signatures in pred_clusters_intermediate.items():
for signature in signatures:
dataset.cluster_seeds_require[signature] = cluster_id
# STEP 3: undo the damage to cluster_seeds_require the damage
logger.info(f"Finished subblocked predict_incremental. Here's how long each subblock took:", predict_times)
dataset.cluster_seeds_require = cluster_seeds_require_original
return pred_clusters_intermediate
else:
# just call predict_incremental_helper as is
return self.predict_incremental_helper(
block_signatures,
dataset,
prevent_new_incompatibilities=prevent_new_incompatibilities,
partial_supervision=partial_supervision,
)
def predict_incremental_helper(
self,
block_signatures: List[str],
dataset: ANDData,
prevent_new_incompatibilities: bool = True,
partial_supervision: Dict[Tuple[str, str], Union[int, float]] = {},
):
"""
Predict clustering in incremental mode. This assumes that the majority of the labels are passed
in using the cluster_seeds_require parameter of the dataset class, and skips work by simply assigning each
unassigned signature to the closest cluster if distance is less than eps, and then separately clusters all
the unassigned signatures that are not within eps of any existing cluster.
Corrected, claimed profiles should be noted via the altered_cluster_signatures parameter (in ANDData).
Then predict_incremental performs a pre-clustering step on each altered cluster to determine how
S2AND would divide it into clusters. Mentions are incrementally added to these new subclusters,
then reassembled to restore the complete claimed profile when S2AND returns results.
Currently this would be useful in the following situation. We have a massive block, for which we want
to cluster a small number of new signatures into (block size * number of new signatures should be less
than the normal batch size).
Notes:
-This function was designed to work on a single block at a time.
-This function should not be called directly. Use predict_incremental instead.
-This function doesnt do any batching. It only calls predict_helper internally.
Parameters
----------
block_signatures: List[str]
the signature ids in the block to predict from
dataset: ANDData
the dataset
prevent_new_incompatibilities: bool
if True, prevents the addition to a cluster of new first names that are not prefix match
or in the name pairs list, for at least one existing name in the cluster. This can happen
if a claimed cluster has D Jones and David Jones, s2and would have split that cluster into two,
and then s2and might add Donald Jones to the D Jones cluster, and once remerged, the resulting
final cluster would have D Jones, David Jones, and Donald Jones.
partial_supervision: Dict
the dictionary of partial supervision provided with this dataset/these blocks
Returns
-------
Dict: the predicted clusters
"""
logger.info(f"Beginning incremental clustering for {len(block_signatures)} signatures...")
recluster_map = {}
cluster_seeds_require = copy.deepcopy(dataset.cluster_seeds_require)
# splitting up the claimed profiles that we received from prod
# because the claimed profiles may be "unnatural" -> users joined papers that S2AND rules
# would never have allowed. when we are going to try to add new signatures to these claimed
# clusters, they should be "natural" looking to avoid impossible additions
# that would be prevented by the rules
if dataset.altered_cluster_signatures is not None and len(dataset.altered_cluster_signatures) > 0:
logger.info("Dealing with altered cluster signatures")
altered_cluster_nums = set(
# it's possible that the altered signature is not in cluster_seeds_require
# because we are passing a custom cluster_seeds_require here from
# predict, but we checked that the altered signature is in the full
# cluster_seeds_require during init
dataset.cluster_seeds_require[altered_signature_id]
for altered_signature_id in dataset.altered_cluster_signatures
if altered_signature_id in dataset.cluster_seeds_require
)
if len(altered_cluster_nums) > 0:
cluster_seeds_require_inverse: Dict[int, list] = {}
for signature_id, cluster_num in dataset.cluster_seeds_require.items():
if cluster_num not in cluster_seeds_require_inverse:
cluster_seeds_require_inverse[cluster_num] = []
cluster_seeds_require_inverse[cluster_num].append(signature_id)
for altered_cluster_num in altered_cluster_nums:
signature_ids_for_cluster_num = cluster_seeds_require_inverse[altered_cluster_num]
# Note: incremental_dont_use_cluster_seeds is set to True, because at this stage
# of incremental clustering we are splitting up the claimed profiles that we received
# from production so that they align with s2and's predictions. When doing this, we
# don't want to use the passed in cluster seeds, because they reflect the claimed profile, not
# s2and's predictions
reclustered_output, _ = self.predict_helper(
{"block": signature_ids_for_cluster_num},
dataset,
incremental_dont_use_cluster_seeds=True,
partial_supervision=partial_supervision,
)
if len(reclustered_output) > 1:
for i, new_cluster_of_signatures in enumerate(reclustered_output.values()):
new_cluster_num = str(altered_cluster_num) + f"_{i}"
recluster_map[new_cluster_num] = altered_cluster_num
for reclustered_signature_id in new_cluster_of_signatures:
cluster_seeds_require[reclustered_signature_id] = new_cluster_num # type: ignore
logger.info("Getting name constraints")
all_pairs = []
unassigned_signatures = []
for possibly_unassigned_signature in block_signatures:
if possibly_unassigned_signature in cluster_seeds_require:
continue
unassigned_signature = possibly_unassigned_signature
unassigned_signatures.append(unassigned_signature)
for signature in cluster_seeds_require.keys():
label = np.nan