pelinker.analysis¶
compute_adjusted_rand_index(y_true, y_pred)
¶
Compute clustering quality via adjusted Rand index (ARI).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
ndarray
|
True labels (e.g., property names) |
required |
y_pred
|
ndarray
|
Predicted cluster labels |
required |
Returns:
| Type | Description |
|---|---|
float
|
ARI score. |
Source code in pelinker/analysis.py
compute_clustering_fit_metrics(clusterer, manifold_df, *, min_cluster_size, cluster_labels)
¶
DBCV, ARI vs entity, and cluster counts for a fitted HDBSCAN model.
Source code in pelinker/analysis.py
compute_kb_generality_scores(embeddings, labels, k_neighbors=10, metric='cosine', word_frequencies=None, density_weight=0.5)
¶
Compute generality scores for entities based on KB statistics.
Combines embedding-space density with label simplicity to identify generic vs specific terms. Generic terms tend to have: - Many similar neighbors (high density) - High average similarity to neighbors - Shorter, simpler labels (fewer words, common words) - Central position in semantic space
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
embeddings
|
ndarray
|
Array of shape (n_points, n_features) containing embeddings |
required |
labels
|
list[str]
|
List of labels corresponding to embeddings |
required |
k_neighbors
|
int
|
Number of nearest neighbors to consider |
10
|
metric
|
str
|
Distance metric ('cosine' or 'euclidean') |
'cosine'
|
word_frequencies
|
Mapping[str, float] | None
|
Optional word frequency mapping for simplicity scoring |
None
|
density_weight
|
float
|
Weight for embedding density vs label simplicity (0.0 = pure simplicity, 1.0 = pure density) |
0.5
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Array of generality scores (higher = more generic), shape (n_points,) |
Source code in pelinker/analysis.py
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 | |
drop_entities_with_few_mentions(frame, min_mentions_per_entity, *, negative_label=None)
¶
Drop entities with fewer than min_mentions_per_entity rows (same rule as
estimate_clustering_from_frame with aggregation_level='mention').
When negative_label is set, that label is never dropped for low mention count
(so thin negative tails remain for screener training).
Source code in pelinker/analysis.py
embeddings_dict_to_dataframe(embeddings_dict)
¶
Convert embeddings dictionary to DataFrame format expected by transform artifacts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
embeddings_dict
|
dict[str, tuple[str, Tensor | ndarray]]
|
Dictionary mapping id -> (label, embedding) |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns: id, label, embed |
Source code in pelinker/analysis.py
estimate_clustering_from_frame(dfr, transform_config, optimization_config=None, *, selected_labels=None, all_metrics_dfs=None, aggregation_level='mention')
¶
Run clustering grid search and optional accumulation of per-sample grid tables.
When all_metrics_dfs is provided, each call appends this sample's metrics_df to
that list. The optimal min_cluster_size for the final HDBSCAN fit on this sample
is always the per-sample DBCV argmax on its own grid; run
:func:pooled_min_cluster_size_from_metrics_dfs after all samples to obtain one consensus
choice across bootstraps (for summaries, plots, and optional grid CSV markers).
aggregation_level="entity" expects one row per distinct entity (e.g. fused
KB vectors) and skips min-mention-per-entity trimming used for mention-level corpora.
Source code in pelinker/analysis.py
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 | |
estimate_model_clustering(transform_config, optimization_config=None, *, file_path=None, file_paths=None, dfr=None, selected_labels=None, all_metrics_dfs=None, embedding_read_status=None, show_embedding_read_progress=False)
¶
Estimate optimal cluster size from parquet file(s) or a preloaded DataFrame.
Provide exactly one of file_path, file_paths, or dfr. For multiple parquets,
rows are inner-joined on (pmid, entity, mention) and embed vectors are concatenated
in path order (must match EmbeddingModelMetadata.sources). Sampling frac /
n_embedding_batches are applied while loading each file (batches), then frac is applied
once on the merged
mention-level frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transform_config
|
TransformConfig
|
TransformConfig instance specifying transformation parameters |
required |
optimization_config
|
ClusteringOptimizationConfig | None
|
Clustering optimization settings. If None, defaults to ClusteringOptimizationConfig(). |
None
|
file_path
|
Path | None
|
Single parquet path (backward-compatible entry point). |
None
|
file_paths
|
Sequence[Path] | None
|
Multiple parquets to fuse at mention level before clustering. |
None
|
dfr
|
DataFrame | None
|
Optional pre-built frame (e.g. fused) with |
None
|
selected_labels
|
set[str] | None
|
Optional set of labels from selected labels KB to filter by |
None
|
all_metrics_dfs
|
list[DataFrame] | None
|
Optional mutable list that receives each sample's grid |
None
|
embedding_read_status
|
Callable[[str], None] | None
|
Callback for embedding parquet batch progress lines
(e.g. append to an existing Rich |
None
|
show_embedding_read_progress
|
bool
|
When True and |
False
|
Returns:
| Type | Description |
|---|---|
|
ClusteringReport or None if processing failed |
Source code in pelinker/analysis.py
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 | |
evaluate_negative_screener_cv_summary(dfr, cfg)
¶
Stratified CV for LDA vs linear SVM on negative vs KB (same task as grid analysis).
Source code in pelinker/analysis.py
fit_negative_screener_with_metrics(dfr, config)
¶
Fit the persisted screener on dfr and report in-sample PR/F1 for detecting
negative_label when both classes are present.
Source code in pelinker/analysis.py
get_word_frequencies_from_library(language='en', wordlist='best')
¶
Get word frequency lookup object from wordfreq library.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
language
|
str
|
Language code (default: "en" for English) |
'en'
|
wordlist
|
str
|
Wordlist size - "best", "large", or "small" (default: "best") |
'best'
|
Returns:
| Type | Description |
|---|---|
object | None
|
WordFrequencyLookup object with .get() method, or None if library not available |
Source code in pelinker/analysis.py
mention_frame_from_embedding_paths(paths, *, optimization_config=None, read_status=None, show_read_progress=False)
¶
Load mention-level rows from parquet file(s) like estimate_model_clustering
(batched read, optional multi-source inner join on keys), without frac subsampling.
Source code in pelinker/analysis.py
metrics_df_with_grid_sample_columns(report, *, model, layer, sample_idx, chosen_min_cluster_size=None)
¶
Per-sample grid rows for results_grid_per_sample.csv.
chosen_min_cluster_size defaults to the value used to fit this sample's clusters
(per-sample grid argmax). Pass the pooled choice from
:func:pooled_min_cluster_size_from_metrics_dfs so every row shares one consensus marker.
Source code in pelinker/analysis.py
pooled_min_cluster_size_from_metrics_dfs(metrics_dfs, optimization_config=None)
¶
After all bootstrap samples have run a min_cluster_size grid, aggregate their metrics
once and return the smoothed (chosen_min_cluster_size, raw objective mean at that grid point).
The objective is set by ClusteringOptimizationConfig.grid_objective (default: pooled
min–max normalized DBCV and ARI).
Source code in pelinker/analysis.py
split_by_negative_label(dfr, negative_label)
¶
Split a mention frame into a boolean mask of synthetic-negative rows and the manifold frame (KB / non-negative rows only).