Skip to content

Late Interaction Topic Models

Most topic models in Turftopic represent a corpus on the level of documents. Late interaction or multi-vector topic models are different, as they can make use of embeddings of smaller units of text. We term these units Spans.

Spans can take many forms, and we let the user define, what unit they wish to do their analyses on e.g.:

Document with topic-annotated spans using a late interaction topic model.
  1. The default unit is a token, tokens are determined by the language model that you use to produce embeddings for the topic model (aka the Encoder).
  2. You can use sliding windows of tokens, these are somewhat larger units, capturing more meaning at once, reducing the number of vectors to be processed.
  3. Sentences are also a natural boundary for Spans.
  4. Anything else...

To learn more about Spans, check out the Span extraction page.

Usage Example

You can use a late model in Turftopic very similar to any other model.

There is, however, one big difference: since there are an uneven number of words in documents, it is also very likely that there is an unequal number of spans. This means that we cannot use a regular array without padding or truncation. Turftopic solves this problem with Ragged Arrays. Ragged arrays are expressed as regular Python objects, and all you have to know for now is that, instead of just a single embedding or document-topic matrix, we now pass around both a ragged matrix and the character Offsets of the spans in the document.

In this example we will use vSLDA:

from turftopic import vSLDA

# vSLDA, by default, is a sentence-level topic model
model = vSLDA(
    10,
    encode_kwargs=dict(show_progress_bar=True),
    n_iter=50,
    span_extractor="sentence"
)
# The first object is a ragged array of the span-topic proportions
# the second one is a list of (span_start, span_end) tuples for each span in the document
doc_topic, offsets = model.fit_transform(corpus)
model.print_topics()
Topic ID Highest Ranking
0 alt, cobb, tek, vice, edu, bobbe, april, series, alexia, lis
1 physics, evolution, main, opinions, objective, agreed, scientists, model, petri, cheers
2 bank, germany, uiuc, access, pay, illinois, programs, straight, cheers, wide
3 motivated, jews, stalin, imo, wars, cheers, petri, wide, failed, killed
4 morality, moral, animals, cruel, goal, immoral, actions, society, natural, crime
5 text, texts, versions, mark, logically, john, language, copies, valid, essentially
6 islam, qur, rushdie, islamic, muslim, khomeini, muslims, fatwa, quran, secular
7 jesus, paul, liar, church, christ, young, believed, biblical, existed, believing
8 military, sell, war, arabia, saudi, figure, water, regards, east, nation
9 atheism, atheists, atheist, exist, god, belief, gods, faq, existence, faith

Model Interpretation

Most of the same interpretation utilities are available when it comes to late interaction models as with regular ones. To learn more about those, check out the Interpreting and Visualizing Models page.

Top Spans

So far the only utilities specifically related to late interaction models are top span extraction. Top spans can be printed, or exported in different formats:

model.print_representative_spans(
    4, corpus, document_topic_matrix=doc_topic, offsets=offsets
)
model.representative_spans_df(
    4, corpus, document_topic_matrix=doc_topic, offsets=offsets
)
model.export_representative_spans(
    4, corpus, document_topic_matrix=doc_topic, offsets=offsets, format="markdown"
)
model.export_representative_spans(
    4, corpus, document_topic_matrix=doc_topic, offsets=offsets, format="latex"
)
model.export_representative_spans(
    4, corpus, document_topic_matrix=doc_topic, offsets=offsets, format="csv"
)
Span Score
Animals of the same species could kill each other arbitarily, but they don't. 1.00
In a natural sense, it is not at all immoral to harm another species (as long as it doesn't adversely affect your own, I guess). 1.00
.. So, only intelligent beings can be moral, even if the bahavior of other beings mimics theirs? 1.00
Well I agree with you in the sense that they have no "moral" right to inflict these rules, but there is one thing I might add: at the very least, almost everybody wants to avoid pain, and
if that means sacrificing some stuff for a herd morality, then so be it. 1.00
...

API Reference

Abstract Base Class

turftopic.late.LateModel

Bases: ContextualModel, TransformerMixin

Source code in turftopic/late.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
class LateModel(ContextualModel, TransformerMixin):
    normalize_spans = True
    span_extractor = None
    include_edge_tokens = True
    window_size = None
    step_size = None
    pooling = None

    """Base class for late interaction (multi-vector) topic models.

    Attributes
    ----------
    span_extractor: SpanExtractor or "sentence", default None
        Object that extracts arbitrary spans from a piece of text.
        These spans will then be used to pool token embeddings.
        This could for instance be a SentenceSeparator.
    include_edge_tokens: bool, default True
        Indicates whether the tokens on the edges of spans (ones that go over the span boundary)
        should be included in the span embedding.
        Ignored when not using a span extractor.
    window_size: int, default None
        Size of the sliding window to average tokens over.
        If None, documents will be represented at a token level.
        Ignored when span_extractor is not None.
    step_size: int, default None
        Step size of the window.
        If (step_size == None) or (step_size == window_size), then windows are separate.
        If step_size < window_size, windows will overlap.
        If step_size > window_size, there will be gaps between the windows.
        In this case, we throw a warning, as this is probably unintended behaviour.
        Ignored when span_extractor is not None.
    pooling: Callable, default None
        Indicates whether and how to pool document-topic matrices.
        If None, multi-vector topic proportions are returned in a ragged array.
        If Callable, multiple vectors are averaged with the callable in each document.
        You could for example take the mean by specifying `pooling=np.nanmean`.
    """

    def load_encoder(self):
        if isinstance(self.encoder, str):
            if self.trf_kwargs is None:
                trf_kwargs = dict()
            else:
                trf_kwargs = self.trf_kwargs
            self.encoder_ = MultiVectorEncoder(self.encoder, **trf_kwargs)
            self._encoder_preloaded = False
        elif isinstance(self.encoder, SentenceTransformer):
            self.encoder_ = self.encoder
            # This is a nasty trick, and I should probably find something better in the future,
            # but this casts a sentence transformer directly into a LateSentenceTransformer
            self.encoder_.__class__ = LateSentenceTransformer
        else:
            self.encoder_ = self.encoder
            self._encoder_preloaded = True

    @staticmethod
    def flatten_repr(repr):
        """Flattens ragged array to normal array.

        Parameters
        ----------
        repr: list[ndarray]
            Ragged representation array.

        Returns
        -------
        flat_repr: ndarray
            Flattened representation array.
        lengths: list[int]
            Length of each document in the corpus.
        """
        return flatten_repr(repr)

    @staticmethod
    def unflatten_repr(flat_repr, lengths):
        """Unflattens flat array to ragged array.

        Parameters
        ----------
        flat_repr: ndarray
            Flattened representation array.
        lengths: list[int]
            Length of each document in the corpus.

        Returns
        -------
        repr: list[ndarray]
            Ragged representation array.

        """
        return unflatten_repr(flat_repr, lengths)

    @staticmethod
    def pool_flat(flat_repr, lengths, agg=np.nanmean):
        """Pools vectors within documents using the agg function.

        Parameters
        ----------
        flat_repr: ndarray or sparse array of shape (n_total_tokens, n_dims)
            Flattened document representations.
        lengths: Lengths
            Number of tokens in each document.

        Returns
        -------
        ndarray or sparse array of shape (n_documents, n_dims)
            Pooled representation for each document.
        """
        return pool_flat(flat_repr, lengths, agg)

    @staticmethod
    def pool_spans(
        token_embeddings: list[np.ndarray],
        token_offsets: list[Offsets],
        span_offsets: list[Offsets],
        include_edge_tokens: bool = True,
        normalize_spans: bool = True,
    ) -> RaggedArray:
        """Pools vectors within the specified spans using in a bunch of documents.

        Parameters
        ----------
        token_embeddings: list[np.ndarray]
            Ragged array of token embeddings.
        token_offsets: list[Offsets]
            End and start character for each token in each document.
        span_offsets: list[Offsets]
            End and start character for each span in each document.
        include_edge_tokens: bool, default True
            Indicates whether tokens at the edges of spans
            should be included in the embeddings.
        normalize_spans: bool, default True
            Indicates whether span embeddings should be L2 normalized.

        Returns
        -------
        span_embeddings: list[np.ndarray]
            Ragged array of each span embedding in each document.
        span_offsets: list[Offsets]
            Offsets for the extracted spans.
            This can differ from the input as empty spans are removed in order to avoid NaNs.
        """
        return pool_spans(
            token_embeddings,
            token_offsets,
            span_offsets,
            include_edge_tokens,
            normalize_spans,
        )

    def pool(self, doc_topic_matrix: list[np.ndarray], offsets):
        """Pools the document topic matrix with the pooling method of the model.
        If pooling is None, nothing will be done

        Parameters
        ----------
        doc_topic_matrix: list[np.ndarray]
            Ragged doc-topic matrix.
        offsets: list[Offsets]
            Span offsets.

        Returns
        -------
        np.ndarray or RaggedArray
            If pooling is None, return array and offsets as is,
            otherwise the pooled document-topic-matrix.
        """
        if self.pooling is None:
            return doc_topic_matrix, offsets
        else:
            _m, lengths = self.flatten_repr(doc_topic_matrix)
            return pool_flat(_m, lengths, self.pooling)

    def ragged_vectorize(
        self,
        raw_documents: list[str],
        offsets: Offsets,
        train_vectorizer=False,
    ):
        """Vectorizes spans in a document.

        Parameters
        ----------
        doc_topic_matrix: list[np.ndarray]
            Ragged doc-topic matrix.
        offsets: list[Offsets]
            Span offsets.

        Returns
        -------
        list[np.ndarray]
            Ragged document-term-matrix.
        """
        if train_vectorizer:
            self.vectorizer.fit(raw_documents)
        dtm = []
        for doc, offs in zip(raw_documents, offsets):
            _dtm = self.vectorizer.transform(
                [doc[start_ind:end_ind] for start_ind, end_ind in offs]
            )
            dtm.append(_dtm)
        return dtm

    def encode_tokens(self, raw_documents: list[str]):
        """Encodes tokens in all documents.

        Parameters
        ----------
        raw_documents: list[str]
            List of documents.

        Returns
        -------
        token_embeddings: list[np.ndarray]
            Embeddings for all tokens.
        token_offsetes: list[Offsets]
            Start and end character indices for each token.
        """
        encode_kwargs = dict(convert_to_numpy=True)
        if self.encode_kwargs is not None:
            encode_kwargs = self.encode_kwargs
        if isinstance(self.encoder_, MultiVectorEncoder):
            embeddings = self.encoder_.encode(raw_documents, **encode_kwargs)
            offsets = self.encoder_.tokenizer(
                raw_documents, return_offsets_mapping=True, verbose=False
            )["offset_mapping"]
            offsets = [
                offs[: len(embs)] for offs, embs in zip(offsets, embeddings)
            ]
            return embeddings, offsets
        else:
            embeddings, offsets = self.encoder_.encode_tokens(
                raw_documents, **encode_kwargs
            )
            return embeddings, offsets

    def encode_documents(self, raw_documents: list[str]):
        """Encodes documents into a flat embedding.

        Parameters
        ----------
        raw_documents: list[str]
            List of documents.

        Returns
        -------
        np.ndarray
            Document embeddings.
        """
        encode_kwargs = dict(convert_to_numpy=True)
        if self.encode_kwargs is not None:
            encode_kwargs = self.encode_kwargs
        if isinstance(self.encoder_, MultiVectorEncoder):
            embeddings, offsets = self.encode_tokens(raw_documents)
            flat_emb, lengths = flatten_repr(embeddings)
            return pool_flat(flat_emb, lengths)
        else:
            return self.encoder_.encode(raw_documents, **encode_kwargs)

    def extract_spans(self, documents, token_offsets=None):
        """Extracts spans using the model's span_extractor.
        If span_extractor is None, tokens are returned as the default spans.
        """
        if self.span_extractor is None:
            warnings.warn(
                "extract_spans was called on a late model even though span_extractor = None, returning token offsets."
            )
            return token_offsets
        if isinstance(self.span_extractor, str):
            if self.span_extractor == "sentence":
                extractor = DummySentenceExtractor()
                return extractor.batch_extract_spans(documents, token_offsets)
            else:
                raise ValueError(
                    f"span_extractor should be a SpanExtractor or 'sentence', not {self.span_extractor}"
                )
        else:
            return self.span_extractor.batch_extract_spans(
                documents, token_offsets
            )

    def encode_late(self, raw_documents: list[str]) -> RaggedArray:
        """Encodes spans in all documents.

        Parameters
        ----------
        raw_documents: list[str]
            List of documents.

        Returns
        -------
        span_embeddings: list[np.ndarray]
            Embeddings for all spans.
        span_offsets: list[Offsets]
            Start and end character indices for each span.
        """
        token_embeddings, token_offsets = self.encode_tokens(raw_documents)
        if self.span_extractor is not None:
            span_offsets = self.extract_spans(raw_documents, token_offsets)
            return self.pool_spans(
                token_embeddings,
                token_offsets,
                span_offsets,
                self.include_edge_tokens,
                self.normalize_spans,
            )
        if self.window_size is None:
            return token_embeddings, token_offsets
        # If the window_size is specified, but not step_size, we set the step size to the window size
        # Thereby getting non-overlapping windows
        step_size = (
            self.window_size if self.step_size is None else self.step_size
        )
        return sliding_window(
            token_embeddings,
            token_offsets,
            window_size=self.window_size,
            step_size=step_size,
        )

    def _representative_docs(
        self,
        topic_id,
        raw_documents=None,
        document_topic_matrix=None,
        top_k=5,
        show_negative: Optional[bool] = None,
    ) -> list[list[str]]:
        if document_topic_matrix is not None:
            if is_ragged(document_topic_matrix):
                flat, lengths = self.flatten_repr(document_topic_matrix)
                document_topic_matrix = self.pool_flat(flat, lengths)
            return super(LateModel, self)._representative_docs(
                topic_id,
                raw_documents,
                document_topic_matrix,
                top_k,
                show_negative,
            )
        elif getattr(self, "document_topic_matrix", None) is not None:
            return self._representative_docs(
                topic_id,
                raw_documents,
                self.document_topic_matrix,
                top_k,
                show_negative,
            )
        else:
            return super(LateModel, self)._representative_docs(
                topic_id,
                raw_documents,
                document_topic_matrix,
                top_k,
                show_negative,
            )

    def get_top_documents(
        self,
        raw_documents=None,
        document_topic_matrix=None,
        top_k: int = 10,
        positive: bool = True,
    ) -> list[list[str]]:
        if document_topic_matrix is not None:
            if is_ragged(document_topic_matrix):
                flat, lengths = self.flatten_repr(document_topic_matrix)
                document_topic_matrix = self.pool_flat(flat, lengths)
                return super(LateModel, self).get_top_documents(
                    positive,
                    raw_documents,
                    document_topic_matrix,
                    top_k,
                )
        elif getattr(self, "document_topic_matrix", None) is not None:
            return self.get_top_documents(
                raw_documents, self.document_topic_matrix, top_k, positive
            )
        else:
            return super(LateModel, self).get_top_documents(
                raw_documents,
                document_topic_matrix,
                top_k,
                positive,
            )

    def get_top_spans(
        self,
        raw_documents=None,
        document_topic_matrix=None,
        embeddings: list[np.ndarray] | None = None,
        offsets: list[Offsets] | None = None,
        top_k: int = 10,
        remove_whitespace: bool = True,
    ) -> list[list[str]]:
        """Returns the top K spans for each topic.
        If no documents are passed, the function will try
        to return the top spans saved during training.

        Parameters
        ----------
        raw_documents: list[str], default None
            List of documents.
        document_topic_matrix: list[np.ndarray], default None
            Ragged document topic matrix.
        embeddings: list[np.ndarray], default None
            Ragged embeddings.
        offsets: list[Offsets] = None
            Span offsets.
        top_k: int, default 10,
            Number of spans to return for each topic.
        remove_whitespace: bool, default rue,
            Indicates whether unnecessary remove_whitespace
            should be removed from the returned spans.

        Returns
        -------
        list[list[str]]
            List of top K spans for each topic.
        """
        raw_documents = getattr(self, "corpus", raw_documents)
        if raw_documents is None:
            if (getattr(self, "top_spans", None) is not None) and any(
                len(spans) >= 0 for spans in self.top_spans
            ):
                return [spans[:top_k] for spans in self.top_spans]
            else:
                raise ValueError(
                    "You either have to pass a corpus, or top_spans has to be an attribute of the model."
                )
        if (document_topic_matrix is None) or (offsets is None):
            if self.pooling is not None:
                raise ValueError(
                    "Cannot get top spans when the model is pooled. You can only use spans with a model that returns ragged arrays."
                )
            document_topic_matrix, offsets = self.transform(
                raw_documents, embeddings=embeddings
            )
        if not is_ragged(document_topic_matrix):
            raise ValueError(
                "Cannot get top spans from a pooled document_topic_matrix, it has to be ragged."
            )
        span_topic_matrix, _ = self.flatten_repr(document_topic_matrix)
        spans = []
        for doc, offs in zip(raw_documents, offsets):
            for span_start, span_end in offs:
                spans.append(doc[span_start:span_end])
        if remove_whitespace:
            spans = [" ".join(span.split()).strip() for span in spans]
        return self.get_top_documents(spans, span_topic_matrix, top_k)

    def _representative_spans(
        self,
        topic_id,
        raw_documents=None,
        document_topic_matrix=None,
        embeddings: list[np.ndarray] | None = None,
        offsets: list[Offsets] | None = None,
        top_k: int = 10,
        remove_whitespace: bool = True,
    ) -> list[list[str]]:
        raw_documents = getattr(self, "corpus", raw_documents)
        if raw_documents is None:
            if (getattr(self, "top_spans", None) is not None) and any(
                len(spans) >= 0 for spans in self.top_spans
            ):
                return [spans[:top_k] for spans in self.top_spans]
            else:
                raise ValueError(
                    "You either have to pass a corpus, or top_spans has to be an attribute of the model."
                )
        if (document_topic_matrix is None) or (offsets is None):
            if self.pooling is not None:
                raise ValueError(
                    "Cannot get top spans when the model is pooled. You can only use spans with a model that returns ragged arrays."
                )
            document_topic_matrix, offsets = self.transform(
                raw_documents, embeddings=embeddings
            )
        if not is_ragged(document_topic_matrix):
            raise ValueError(
                "Cannot get top spans from a pooled document_topic_matrix, it has to be ragged."
            )
        span_topic_matrix, _ = self.flatten_repr(document_topic_matrix)
        spans = []
        for doc, offs in zip(raw_documents, offsets):
            for span_start, span_end in offs:
                spans.append(doc[span_start:span_end])
        if remove_whitespace:
            spans = [" ".join(span.split()).strip() for span in spans]
        return super(LateModel, self)._representative_docs(
            topic_id,
            raw_documents=spans,
            document_topic_matrix=span_topic_matrix,
            top_k=top_k,
        )

    def representative_spans_df(
        self,
        topic_id,
        raw_documents=None,
        document_topic_matrix=None,
        embeddings: list[np.ndarray] | None = None,
        offsets: list[Offsets] | None = None,
        top_k: int = 10,
        remove_whitespace: bool = True,
    ):
        """Produces a DataFrame of representative spans for a given topic.

        Parameters
        ----------
        topic_id
            ID of the topic to show spans for.
        raw_documents: list[str], default None
            List of documents.
        document_topic_matrix: list[np.ndarray], default None
            Ragged document topic matrix.
        embeddings: list[np.ndarray], default None
            Ragged embeddings.
        offsets: list[Offsets] = None
            Span offsets.
        top_k: int, default 10,
            Number of spans to return for each topic.
        remove_whitespace: bool, default rue,
            Indicates whether unnecessary remove_whitespace
            should be removed from the returned spans.
        """
        raw_documents = getattr(self, "corpus", raw_documents)
        if raw_documents is None:
            if (getattr(self, "top_spans", None) is not None) and any(
                len(spans) >= 0 for spans in self.top_spans
            ):
                return [spans[:top_k] for spans in self.top_spans]
            else:
                raise ValueError(
                    "You either have to pass a corpus, or top_spans has to be an attribute of the model."
                )
        if (document_topic_matrix is None) or (offsets is None):
            if self.pooling is not None:
                raise ValueError(
                    "Cannot get top spans when the model is pooled. You can only use spans with a model that returns ragged arrays."
                )
            document_topic_matrix, offsets = self.transform(
                raw_documents, embeddings=embeddings
            )
        if not is_ragged(document_topic_matrix):
            raise ValueError(
                "Cannot get top spans from a pooled document_topic_matrix, it has to be ragged."
            )
        span_topic_matrix, _ = self.flatten_repr(document_topic_matrix)
        spans = []
        for doc, offs in zip(raw_documents, offsets):
            for span_start, span_end in offs:
                spans.append(doc[span_start:span_end])
        if remove_whitespace:
            spans = [" ".join(span.split()).strip() for span in spans]
        df = (
            super(LateModel, self)
            .representative_documents_df(
                topic_id,
                raw_documents=spans,
                document_topic_matrix=span_topic_matrix,
                top_k=top_k,
            )
            .rename(columns={"Document": "Span"})
        )
        return df

    def print_representative_spans(
        self,
        topic_id,
        raw_documents=None,
        document_topic_matrix=None,
        embeddings: list[np.ndarray] | None = None,
        offsets: list[Offsets] | None = None,
        top_k: int = 10,
        remove_whitespace: bool = True,
    ):
        """Prints representative spans for a given topic.

        Parameters
        ----------
        topic_id
            ID of the topic to show spans for.
        raw_documents: list[str], default None
            List of documents.
        document_topic_matrix: list[np.ndarray], default None
            Ragged document topic matrix.
        embeddings: list[np.ndarray], default None
            Ragged embeddings.
        offsets: list[Offsets] = None
            Span offsets.
        top_k: int, default 10,
            Number of spans to return for each topic.
        remove_whitespace: bool, default rue,
            Indicates whether unnecessary remove_whitespace
            should be removed from the returned spans.
        """
        columns, *rows = self._representative_spans(
            topic_id,
            raw_documents,
            document_topic_matrix,
            embeddings,
            offsets,
            top_k,
            remove_whitespace,
        )
        table = Table(show_lines=True)
        table.add_column(
            "Document", justify="left", style="magenta", max_width=100
        )
        table.add_column("Score", style="blue", justify="right")
        for row in rows:
            table.add_row(*row)
        console = Console()
        console.print(table)

    def export_representative_spans(
        self,
        topic_id,
        raw_documents=None,
        document_topic_matrix=None,
        embeddings: list[np.ndarray] | None = None,
        offsets: list[Offsets] | None = None,
        top_k: int = 10,
        remove_whitespace: bool = True,
        format: str = "csv",
    ):
        """Exports representative spans for a given topic in a given format

        Parameters
        ----------
        topic_id
            ID of the topic to show spans for.
        raw_documents: list[str], default None
            List of documents.
        document_topic_matrix: list[np.ndarray], default None
            Ragged document topic matrix.
        embeddings: list[np.ndarray], default None
            Ragged embeddings.
        offsets: list[Offsets] = None
            Span offsets.
        top_k: int, default 10,
            Number of spans to return for each topic.
        remove_whitespace: bool, default rue,
            Indicates whether unnecessary remove_whitespace
            should be removed from the returned spans.
        format: 'csv', 'latex' or 'markdown'
            Specifies which format should be used.
            'csv', 'latex' and 'markdown' are supported.
        """
        table = self._representative_spans(
            topic_id,
            raw_documents,
            document_topic_matrix,
            embeddings,
            offsets,
            top_k,
            remove_whitespace,
        )
        return export_table(table, format=format)

    @abstractmethod
    def fit_transform(
        self,
        raw_documents,
        y=None,
        embeddings: Optional[list[np.ndarray]] = None,
        offsets: Optional[Offsets] = None,
    ) -> RaggedArray | np.ndarray:
        """Fits model and infers topic importances for each document.

        Parameters
        ----------
        raw_documents: iterable of str
            Documents to fit the model on.
        y: None
            Ignored, exists for sklearn compatibility.
        embeddings: ndarray of shape (n_documents, n_dimensions), optional
            Ragged array of document encodings.
        offsets: Offsets, optional
            Character offset for each unit in the document.

        Returns
        -------
        (list[np.ndarray], list[Offsets]) or ndarray
            Document-topic matrix.
            If pooling = None, this should be a ragged array with offsets,
            otherwise a regular matrix.
        """
        pass

    def fit(
        self,
        raw_documents,
        y=None,
        embeddings: Optional[list[np.ndarray]] = None,
        offsets: Optional[Offsets] = None,
    ):
        """Fits model on the given corpus.

        Parameters
        ----------
        raw_documents: iterable of str
            Documents to fit the model on.
        y: None
            Ignored, exists for sklearn compatibility.
        embeddings: list[ndarray], optional
            Ragged array of document encodings.
        offsets: Offsets, optional
            Character offset for each unit in the document.
        """
        self.fit_transform(
            raw_documents, y, embeddings=embeddings, offsets=offsets
        )
        return self

pooling = None class-attribute instance-attribute

Base class for late interaction (multi-vector) topic models.

Attributes:

Name Type Description
span_extractor SpanExtractor or "sentence", default None

Object that extracts arbitrary spans from a piece of text. These spans will then be used to pool token embeddings. This could for instance be a SentenceSeparator.

include_edge_tokens bool, default True

Indicates whether the tokens on the edges of spans (ones that go over the span boundary) should be included in the span embedding. Ignored when not using a span extractor.

window_size int, default None

Size of the sliding window to average tokens over. If None, documents will be represented at a token level. Ignored when span_extractor is not None.

step_size int, default None

Step size of the window. If (step_size == None) or (step_size == window_size), then windows are separate. If step_size < window_size, windows will overlap. If step_size > window_size, there will be gaps between the windows. In this case, we throw a warning, as this is probably unintended behaviour. Ignored when span_extractor is not None.

pooling Callable, default None

Indicates whether and how to pool document-topic matrices. If None, multi-vector topic proportions are returned in a ragged array. If Callable, multiple vectors are averaged with the callable in each document. You could for example take the mean by specifying pooling=np.nanmean.

encode_documents(raw_documents)

Encodes documents into a flat embedding.

Parameters:

Name Type Description Default
raw_documents list[str]

List of documents.

required

Returns:

Type Description
ndarray

Document embeddings.

Source code in turftopic/late.py
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
def encode_documents(self, raw_documents: list[str]):
    """Encodes documents into a flat embedding.

    Parameters
    ----------
    raw_documents: list[str]
        List of documents.

    Returns
    -------
    np.ndarray
        Document embeddings.
    """
    encode_kwargs = dict(convert_to_numpy=True)
    if self.encode_kwargs is not None:
        encode_kwargs = self.encode_kwargs
    if isinstance(self.encoder_, MultiVectorEncoder):
        embeddings, offsets = self.encode_tokens(raw_documents)
        flat_emb, lengths = flatten_repr(embeddings)
        return pool_flat(flat_emb, lengths)
    else:
        return self.encoder_.encode(raw_documents, **encode_kwargs)

encode_late(raw_documents)

Encodes spans in all documents.

Parameters:

Name Type Description Default
raw_documents list[str]

List of documents.

required

Returns:

Name Type Description
span_embeddings list[ndarray]

Embeddings for all spans.

span_offsets list[Offsets]

Start and end character indices for each span.

Source code in turftopic/late.py
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
def encode_late(self, raw_documents: list[str]) -> RaggedArray:
    """Encodes spans in all documents.

    Parameters
    ----------
    raw_documents: list[str]
        List of documents.

    Returns
    -------
    span_embeddings: list[np.ndarray]
        Embeddings for all spans.
    span_offsets: list[Offsets]
        Start and end character indices for each span.
    """
    token_embeddings, token_offsets = self.encode_tokens(raw_documents)
    if self.span_extractor is not None:
        span_offsets = self.extract_spans(raw_documents, token_offsets)
        return self.pool_spans(
            token_embeddings,
            token_offsets,
            span_offsets,
            self.include_edge_tokens,
            self.normalize_spans,
        )
    if self.window_size is None:
        return token_embeddings, token_offsets
    # If the window_size is specified, but not step_size, we set the step size to the window size
    # Thereby getting non-overlapping windows
    step_size = (
        self.window_size if self.step_size is None else self.step_size
    )
    return sliding_window(
        token_embeddings,
        token_offsets,
        window_size=self.window_size,
        step_size=step_size,
    )

encode_tokens(raw_documents)

Encodes tokens in all documents.

Parameters:

Name Type Description Default
raw_documents list[str]

List of documents.

required

Returns:

Name Type Description
token_embeddings list[ndarray]

Embeddings for all tokens.

token_offsetes list[Offsets]

Start and end character indices for each token.

Source code in turftopic/late.py
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
def encode_tokens(self, raw_documents: list[str]):
    """Encodes tokens in all documents.

    Parameters
    ----------
    raw_documents: list[str]
        List of documents.

    Returns
    -------
    token_embeddings: list[np.ndarray]
        Embeddings for all tokens.
    token_offsetes: list[Offsets]
        Start and end character indices for each token.
    """
    encode_kwargs = dict(convert_to_numpy=True)
    if self.encode_kwargs is not None:
        encode_kwargs = self.encode_kwargs
    if isinstance(self.encoder_, MultiVectorEncoder):
        embeddings = self.encoder_.encode(raw_documents, **encode_kwargs)
        offsets = self.encoder_.tokenizer(
            raw_documents, return_offsets_mapping=True, verbose=False
        )["offset_mapping"]
        offsets = [
            offs[: len(embs)] for offs, embs in zip(offsets, embeddings)
        ]
        return embeddings, offsets
    else:
        embeddings, offsets = self.encoder_.encode_tokens(
            raw_documents, **encode_kwargs
        )
        return embeddings, offsets

export_representative_spans(topic_id, raw_documents=None, document_topic_matrix=None, embeddings=None, offsets=None, top_k=10, remove_whitespace=True, format='csv')

Exports representative spans for a given topic in a given format

Parameters:

Name Type Description Default
topic_id

ID of the topic to show spans for.

required
raw_documents

List of documents.

None
document_topic_matrix

Ragged document topic matrix.

None
embeddings list[ndarray] | None

Ragged embeddings.

None
offsets list[Offsets] | None

Span offsets.

None
top_k int

Number of spans to return for each topic.

10
remove_whitespace bool

Indicates whether unnecessary remove_whitespace should be removed from the returned spans.

True
format str

Specifies which format should be used. 'csv', 'latex' and 'markdown' are supported.

'csv'
Source code in turftopic/late.py
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
def export_representative_spans(
    self,
    topic_id,
    raw_documents=None,
    document_topic_matrix=None,
    embeddings: list[np.ndarray] | None = None,
    offsets: list[Offsets] | None = None,
    top_k: int = 10,
    remove_whitespace: bool = True,
    format: str = "csv",
):
    """Exports representative spans for a given topic in a given format

    Parameters
    ----------
    topic_id
        ID of the topic to show spans for.
    raw_documents: list[str], default None
        List of documents.
    document_topic_matrix: list[np.ndarray], default None
        Ragged document topic matrix.
    embeddings: list[np.ndarray], default None
        Ragged embeddings.
    offsets: list[Offsets] = None
        Span offsets.
    top_k: int, default 10,
        Number of spans to return for each topic.
    remove_whitespace: bool, default rue,
        Indicates whether unnecessary remove_whitespace
        should be removed from the returned spans.
    format: 'csv', 'latex' or 'markdown'
        Specifies which format should be used.
        'csv', 'latex' and 'markdown' are supported.
    """
    table = self._representative_spans(
        topic_id,
        raw_documents,
        document_topic_matrix,
        embeddings,
        offsets,
        top_k,
        remove_whitespace,
    )
    return export_table(table, format=format)

extract_spans(documents, token_offsets=None)

Extracts spans using the model's span_extractor. If span_extractor is None, tokens are returned as the default spans.

Source code in turftopic/late.py
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
def extract_spans(self, documents, token_offsets=None):
    """Extracts spans using the model's span_extractor.
    If span_extractor is None, tokens are returned as the default spans.
    """
    if self.span_extractor is None:
        warnings.warn(
            "extract_spans was called on a late model even though span_extractor = None, returning token offsets."
        )
        return token_offsets
    if isinstance(self.span_extractor, str):
        if self.span_extractor == "sentence":
            extractor = DummySentenceExtractor()
            return extractor.batch_extract_spans(documents, token_offsets)
        else:
            raise ValueError(
                f"span_extractor should be a SpanExtractor or 'sentence', not {self.span_extractor}"
            )
    else:
        return self.span_extractor.batch_extract_spans(
            documents, token_offsets
        )

fit(raw_documents, y=None, embeddings=None, offsets=None)

Fits model on the given corpus.

Parameters:

Name Type Description Default
raw_documents

Documents to fit the model on.

required
y

Ignored, exists for sklearn compatibility.

None
embeddings Optional[list[ndarray]]

Ragged array of document encodings.

None
offsets Optional[Offsets]

Character offset for each unit in the document.

None
Source code in turftopic/late.py
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
def fit(
    self,
    raw_documents,
    y=None,
    embeddings: Optional[list[np.ndarray]] = None,
    offsets: Optional[Offsets] = None,
):
    """Fits model on the given corpus.

    Parameters
    ----------
    raw_documents: iterable of str
        Documents to fit the model on.
    y: None
        Ignored, exists for sklearn compatibility.
    embeddings: list[ndarray], optional
        Ragged array of document encodings.
    offsets: Offsets, optional
        Character offset for each unit in the document.
    """
    self.fit_transform(
        raw_documents, y, embeddings=embeddings, offsets=offsets
    )
    return self

fit_transform(raw_documents, y=None, embeddings=None, offsets=None) abstractmethod

Fits model and infers topic importances for each document.

Parameters:

Name Type Description Default
raw_documents

Documents to fit the model on.

required
y

Ignored, exists for sklearn compatibility.

None
embeddings Optional[list[ndarray]]

Ragged array of document encodings.

None
offsets Optional[Offsets]

Character offset for each unit in the document.

None

Returns:

Type Description
(list[ndarray], list[Offsets]) or ndarray

Document-topic matrix. If pooling = None, this should be a ragged array with offsets, otherwise a regular matrix.

Source code in turftopic/late.py
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
@abstractmethod
def fit_transform(
    self,
    raw_documents,
    y=None,
    embeddings: Optional[list[np.ndarray]] = None,
    offsets: Optional[Offsets] = None,
) -> RaggedArray | np.ndarray:
    """Fits model and infers topic importances for each document.

    Parameters
    ----------
    raw_documents: iterable of str
        Documents to fit the model on.
    y: None
        Ignored, exists for sklearn compatibility.
    embeddings: ndarray of shape (n_documents, n_dimensions), optional
        Ragged array of document encodings.
    offsets: Offsets, optional
        Character offset for each unit in the document.

    Returns
    -------
    (list[np.ndarray], list[Offsets]) or ndarray
        Document-topic matrix.
        If pooling = None, this should be a ragged array with offsets,
        otherwise a regular matrix.
    """
    pass

flatten_repr(repr) staticmethod

Flattens ragged array to normal array.

Parameters:

Name Type Description Default
repr

Ragged representation array.

required

Returns:

Name Type Description
flat_repr ndarray

Flattened representation array.

lengths list[int]

Length of each document in the corpus.

Source code in turftopic/late.py
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
@staticmethod
def flatten_repr(repr):
    """Flattens ragged array to normal array.

    Parameters
    ----------
    repr: list[ndarray]
        Ragged representation array.

    Returns
    -------
    flat_repr: ndarray
        Flattened representation array.
    lengths: list[int]
        Length of each document in the corpus.
    """
    return flatten_repr(repr)

get_top_spans(raw_documents=None, document_topic_matrix=None, embeddings=None, offsets=None, top_k=10, remove_whitespace=True)

Returns the top K spans for each topic. If no documents are passed, the function will try to return the top spans saved during training.

Parameters:

Name Type Description Default
raw_documents

List of documents.

None
document_topic_matrix

Ragged document topic matrix.

None
embeddings list[ndarray] | None

Ragged embeddings.

None
offsets list[Offsets] | None

Span offsets.

None
top_k int

Number of spans to return for each topic.

10
remove_whitespace bool

Indicates whether unnecessary remove_whitespace should be removed from the returned spans.

True

Returns:

Type Description
list[list[str]]

List of top K spans for each topic.

Source code in turftopic/late.py
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
def get_top_spans(
    self,
    raw_documents=None,
    document_topic_matrix=None,
    embeddings: list[np.ndarray] | None = None,
    offsets: list[Offsets] | None = None,
    top_k: int = 10,
    remove_whitespace: bool = True,
) -> list[list[str]]:
    """Returns the top K spans for each topic.
    If no documents are passed, the function will try
    to return the top spans saved during training.

    Parameters
    ----------
    raw_documents: list[str], default None
        List of documents.
    document_topic_matrix: list[np.ndarray], default None
        Ragged document topic matrix.
    embeddings: list[np.ndarray], default None
        Ragged embeddings.
    offsets: list[Offsets] = None
        Span offsets.
    top_k: int, default 10,
        Number of spans to return for each topic.
    remove_whitespace: bool, default rue,
        Indicates whether unnecessary remove_whitespace
        should be removed from the returned spans.

    Returns
    -------
    list[list[str]]
        List of top K spans for each topic.
    """
    raw_documents = getattr(self, "corpus", raw_documents)
    if raw_documents is None:
        if (getattr(self, "top_spans", None) is not None) and any(
            len(spans) >= 0 for spans in self.top_spans
        ):
            return [spans[:top_k] for spans in self.top_spans]
        else:
            raise ValueError(
                "You either have to pass a corpus, or top_spans has to be an attribute of the model."
            )
    if (document_topic_matrix is None) or (offsets is None):
        if self.pooling is not None:
            raise ValueError(
                "Cannot get top spans when the model is pooled. You can only use spans with a model that returns ragged arrays."
            )
        document_topic_matrix, offsets = self.transform(
            raw_documents, embeddings=embeddings
        )
    if not is_ragged(document_topic_matrix):
        raise ValueError(
            "Cannot get top spans from a pooled document_topic_matrix, it has to be ragged."
        )
    span_topic_matrix, _ = self.flatten_repr(document_topic_matrix)
    spans = []
    for doc, offs in zip(raw_documents, offsets):
        for span_start, span_end in offs:
            spans.append(doc[span_start:span_end])
    if remove_whitespace:
        spans = [" ".join(span.split()).strip() for span in spans]
    return self.get_top_documents(spans, span_topic_matrix, top_k)

pool(doc_topic_matrix, offsets)

Pools the document topic matrix with the pooling method of the model. If pooling is None, nothing will be done

Parameters:

Name Type Description Default
doc_topic_matrix list[ndarray]

Ragged doc-topic matrix.

required
offsets

Span offsets.

required

Returns:

Type Description
ndarray or RaggedArray

If pooling is None, return array and offsets as is, otherwise the pooled document-topic-matrix.

Source code in turftopic/late.py
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
def pool(self, doc_topic_matrix: list[np.ndarray], offsets):
    """Pools the document topic matrix with the pooling method of the model.
    If pooling is None, nothing will be done

    Parameters
    ----------
    doc_topic_matrix: list[np.ndarray]
        Ragged doc-topic matrix.
    offsets: list[Offsets]
        Span offsets.

    Returns
    -------
    np.ndarray or RaggedArray
        If pooling is None, return array and offsets as is,
        otherwise the pooled document-topic-matrix.
    """
    if self.pooling is None:
        return doc_topic_matrix, offsets
    else:
        _m, lengths = self.flatten_repr(doc_topic_matrix)
        return pool_flat(_m, lengths, self.pooling)

pool_flat(flat_repr, lengths, agg=np.nanmean) staticmethod

Pools vectors within documents using the agg function.

Parameters:

Name Type Description Default
flat_repr

Flattened document representations.

required
lengths

Number of tokens in each document.

required

Returns:

Type Description
ndarray or sparse array of shape (n_documents, n_dims)

Pooled representation for each document.

Source code in turftopic/late.py
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
@staticmethod
def pool_flat(flat_repr, lengths, agg=np.nanmean):
    """Pools vectors within documents using the agg function.

    Parameters
    ----------
    flat_repr: ndarray or sparse array of shape (n_total_tokens, n_dims)
        Flattened document representations.
    lengths: Lengths
        Number of tokens in each document.

    Returns
    -------
    ndarray or sparse array of shape (n_documents, n_dims)
        Pooled representation for each document.
    """
    return pool_flat(flat_repr, lengths, agg)

pool_spans(token_embeddings, token_offsets, span_offsets, include_edge_tokens=True, normalize_spans=True) staticmethod

Pools vectors within the specified spans using in a bunch of documents.

Parameters:

Name Type Description Default
token_embeddings list[ndarray]

Ragged array of token embeddings.

required
token_offsets list[Offsets]

End and start character for each token in each document.

required
span_offsets list[Offsets]

End and start character for each span in each document.

required
include_edge_tokens bool

Indicates whether tokens at the edges of spans should be included in the embeddings.

True
normalize_spans bool

Indicates whether span embeddings should be L2 normalized.

True

Returns:

Name Type Description
span_embeddings list[ndarray]

Ragged array of each span embedding in each document.

span_offsets list[Offsets]

Offsets for the extracted spans. This can differ from the input as empty spans are removed in order to avoid NaNs.

Source code in turftopic/late.py
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
@staticmethod
def pool_spans(
    token_embeddings: list[np.ndarray],
    token_offsets: list[Offsets],
    span_offsets: list[Offsets],
    include_edge_tokens: bool = True,
    normalize_spans: bool = True,
) -> RaggedArray:
    """Pools vectors within the specified spans using in a bunch of documents.

    Parameters
    ----------
    token_embeddings: list[np.ndarray]
        Ragged array of token embeddings.
    token_offsets: list[Offsets]
        End and start character for each token in each document.
    span_offsets: list[Offsets]
        End and start character for each span in each document.
    include_edge_tokens: bool, default True
        Indicates whether tokens at the edges of spans
        should be included in the embeddings.
    normalize_spans: bool, default True
        Indicates whether span embeddings should be L2 normalized.

    Returns
    -------
    span_embeddings: list[np.ndarray]
        Ragged array of each span embedding in each document.
    span_offsets: list[Offsets]
        Offsets for the extracted spans.
        This can differ from the input as empty spans are removed in order to avoid NaNs.
    """
    return pool_spans(
        token_embeddings,
        token_offsets,
        span_offsets,
        include_edge_tokens,
        normalize_spans,
    )

print_representative_spans(topic_id, raw_documents=None, document_topic_matrix=None, embeddings=None, offsets=None, top_k=10, remove_whitespace=True)

Prints representative spans for a given topic.

Parameters:

Name Type Description Default
topic_id

ID of the topic to show spans for.

required
raw_documents

List of documents.

None
document_topic_matrix

Ragged document topic matrix.

None
embeddings list[ndarray] | None

Ragged embeddings.

None
offsets list[Offsets] | None

Span offsets.

None
top_k int

Number of spans to return for each topic.

10
remove_whitespace bool

Indicates whether unnecessary remove_whitespace should be removed from the returned spans.

True
Source code in turftopic/late.py
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
def print_representative_spans(
    self,
    topic_id,
    raw_documents=None,
    document_topic_matrix=None,
    embeddings: list[np.ndarray] | None = None,
    offsets: list[Offsets] | None = None,
    top_k: int = 10,
    remove_whitespace: bool = True,
):
    """Prints representative spans for a given topic.

    Parameters
    ----------
    topic_id
        ID of the topic to show spans for.
    raw_documents: list[str], default None
        List of documents.
    document_topic_matrix: list[np.ndarray], default None
        Ragged document topic matrix.
    embeddings: list[np.ndarray], default None
        Ragged embeddings.
    offsets: list[Offsets] = None
        Span offsets.
    top_k: int, default 10,
        Number of spans to return for each topic.
    remove_whitespace: bool, default rue,
        Indicates whether unnecessary remove_whitespace
        should be removed from the returned spans.
    """
    columns, *rows = self._representative_spans(
        topic_id,
        raw_documents,
        document_topic_matrix,
        embeddings,
        offsets,
        top_k,
        remove_whitespace,
    )
    table = Table(show_lines=True)
    table.add_column(
        "Document", justify="left", style="magenta", max_width=100
    )
    table.add_column("Score", style="blue", justify="right")
    for row in rows:
        table.add_row(*row)
    console = Console()
    console.print(table)

ragged_vectorize(raw_documents, offsets, train_vectorizer=False)

Vectorizes spans in a document.

Parameters:

Name Type Description Default
doc_topic_matrix

Ragged doc-topic matrix.

required
offsets Offsets

Span offsets.

required

Returns:

Type Description
list[ndarray]

Ragged document-term-matrix.

Source code in turftopic/late.py
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
def ragged_vectorize(
    self,
    raw_documents: list[str],
    offsets: Offsets,
    train_vectorizer=False,
):
    """Vectorizes spans in a document.

    Parameters
    ----------
    doc_topic_matrix: list[np.ndarray]
        Ragged doc-topic matrix.
    offsets: list[Offsets]
        Span offsets.

    Returns
    -------
    list[np.ndarray]
        Ragged document-term-matrix.
    """
    if train_vectorizer:
        self.vectorizer.fit(raw_documents)
    dtm = []
    for doc, offs in zip(raw_documents, offsets):
        _dtm = self.vectorizer.transform(
            [doc[start_ind:end_ind] for start_ind, end_ind in offs]
        )
        dtm.append(_dtm)
    return dtm

representative_spans_df(topic_id, raw_documents=None, document_topic_matrix=None, embeddings=None, offsets=None, top_k=10, remove_whitespace=True)

Produces a DataFrame of representative spans for a given topic.

Parameters:

Name Type Description Default
topic_id

ID of the topic to show spans for.

required
raw_documents

List of documents.

None
document_topic_matrix

Ragged document topic matrix.

None
embeddings list[ndarray] | None

Ragged embeddings.

None
offsets list[Offsets] | None

Span offsets.

None
top_k int

Number of spans to return for each topic.

10
remove_whitespace bool

Indicates whether unnecessary remove_whitespace should be removed from the returned spans.

True
Source code in turftopic/late.py
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
def representative_spans_df(
    self,
    topic_id,
    raw_documents=None,
    document_topic_matrix=None,
    embeddings: list[np.ndarray] | None = None,
    offsets: list[Offsets] | None = None,
    top_k: int = 10,
    remove_whitespace: bool = True,
):
    """Produces a DataFrame of representative spans for a given topic.

    Parameters
    ----------
    topic_id
        ID of the topic to show spans for.
    raw_documents: list[str], default None
        List of documents.
    document_topic_matrix: list[np.ndarray], default None
        Ragged document topic matrix.
    embeddings: list[np.ndarray], default None
        Ragged embeddings.
    offsets: list[Offsets] = None
        Span offsets.
    top_k: int, default 10,
        Number of spans to return for each topic.
    remove_whitespace: bool, default rue,
        Indicates whether unnecessary remove_whitespace
        should be removed from the returned spans.
    """
    raw_documents = getattr(self, "corpus", raw_documents)
    if raw_documents is None:
        if (getattr(self, "top_spans", None) is not None) and any(
            len(spans) >= 0 for spans in self.top_spans
        ):
            return [spans[:top_k] for spans in self.top_spans]
        else:
            raise ValueError(
                "You either have to pass a corpus, or top_spans has to be an attribute of the model."
            )
    if (document_topic_matrix is None) or (offsets is None):
        if self.pooling is not None:
            raise ValueError(
                "Cannot get top spans when the model is pooled. You can only use spans with a model that returns ragged arrays."
            )
        document_topic_matrix, offsets = self.transform(
            raw_documents, embeddings=embeddings
        )
    if not is_ragged(document_topic_matrix):
        raise ValueError(
            "Cannot get top spans from a pooled document_topic_matrix, it has to be ragged."
        )
    span_topic_matrix, _ = self.flatten_repr(document_topic_matrix)
    spans = []
    for doc, offs in zip(raw_documents, offsets):
        for span_start, span_end in offs:
            spans.append(doc[span_start:span_end])
    if remove_whitespace:
        spans = [" ".join(span.split()).strip() for span in spans]
    df = (
        super(LateModel, self)
        .representative_documents_df(
            topic_id,
            raw_documents=spans,
            document_topic_matrix=span_topic_matrix,
            top_k=top_k,
        )
        .rename(columns={"Document": "Span"})
    )
    return df

unflatten_repr(flat_repr, lengths) staticmethod

Unflattens flat array to ragged array.

Parameters:

Name Type Description Default
flat_repr

Flattened representation array.

required
lengths

Length of each document in the corpus.

required

Returns:

Name Type Description
repr list[ndarray]

Ragged representation array.

Source code in turftopic/late.py
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
@staticmethod
def unflatten_repr(flat_repr, lengths):
    """Unflattens flat array to ragged array.

    Parameters
    ----------
    flat_repr: ndarray
        Flattened representation array.
    lengths: list[int]
        Length of each document in the corpus.

    Returns
    -------
    repr: list[ndarray]
        Ragged representation array.

    """
    return unflatten_repr(flat_repr, lengths)

Encoder

turftopic.late.LateSentenceTransformer

Bases: SentenceTransformer

SentenceTransformer model that can produce token and window-level embeddings. Its output can be used by topic models that can use multi-vector document representations.

Warning

This is not checked yet in the library, but we recommend that you use SentenceTransformers that are a) Mean pooled b) L2 Normalized This will guarrantee that the token/window embeddings are in the same embedding space as the documents.

Source code in turftopic/late.py
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
class LateSentenceTransformer(SentenceTransformer):
    """SentenceTransformer model that can produce token and window-level embeddings.
    Its output can be used by topic models that can use multi-vector document representations.

    !!! warning
        This is not checked yet in the library,
        but we recommend that you use SentenceTransformers that are
        a) **Mean pooled**
        b) **L2 Normalized**
        This will guarrantee that the token/window embeddings are in the same embedding space as the documents.
    """

    has_used_token_level = False

    def encode(
        self, sentences: Union[str, list[str], np.ndarray], *args, **kwargs
    ):
        if not self.has_used_token_level:
            warnings.warn(
                "Encoder is contextual but topic model is not using contextual embeddings. Perhaps you wanted to use another topic model."
            )
        return super().encode(sentences, *args, **kwargs)

    def _encode_tokens(
        self,
        texts,
        **kwargs,
    ) -> RaggedArray:
        """
        Returns
        -------
        token_embeddings: list[np.ndarray]
            Embedding matrix of tokens for each document.
        offsets: list[list[tuple[int, int]]]
            Start and end character of each token in each document.
        """
        self.has_used_token_level = True
        token_embeddings = self.encode(
            texts,
            output_value="token_embeddings",
            **kwargs,
        )
        offsets = self.tokenizer(
            texts, return_offsets_mapping=True, verbose=False
        )["offset_mapping"]
        offsets = [
            offs[: len(embs)] for offs, embs in zip(offsets, token_embeddings)
        ]
        token_embeddings = [
            to_numpy(embs)
            for embs in token_embeddings
            if torch.is_tensor(embs)
        ]
        return token_embeddings, offsets

    def encode_tokens(
        self,
        sentences: list[str],
        **kwargs,
    ):
        """Produces contextual token embeddings over all documents.

        Parameters
        ----------
        sentences: list[str]
            Documents to encode contextually.
        batch_size: int, default 32
            Size of the batch of document to encode at once.
        show_progress_bar: bool, default True
            Indicates whether a progress bar should be displayed when encoding.

        Returns
        -------
        token_embeddings: list[np.ndarray]
            Embedding matrix of tokens for each document.
        offsets: list[list[tuple[int, int]]]
            Start and end character of each token in each document.
        """
        # This is needed because the above implementation does not normalize embeddings,
        # which normally happens to document embeddings.
        token_embeddings, offsets = self._encode_tokens(
            sentences,
            **kwargs,
        )
        token_embeddings = [normalize(emb) for emb in token_embeddings]
        return token_embeddings, offsets

    def encode_windows(
        self,
        sentences: list[str],
        window_size: int = 50,
        step_size: int = 40,
        **kwargs,
    ):
        """Produces contextual embeddings for a sliding window of tokens similar to C-Top2Vec.

        Parameters
        ----------
        sentences: list[str]
            Documents to encode contextually.
        batch_size: int, default 32
            Size of the batch of document to encode at once.
        window_size: int, default 50
            Size of the sliding window.
        step_size: int, default 40
            Step size of the window.
            If step_size < window_size, windows will overlap.
            If step_size == window_size, then windows are separate.
            If step_size > window_size, there will be gaps between the windows.
            In this case, we throw a warning, as this is probably unintended behaviour.
        show_progress_bar: bool, default True
            Indicates whether a progress bar should be displayed when encoding.

        Returns
        -------
        window_embeddings: list[np.ndarray]
            Embedding matrix of windows for each document.
        offsets: list[list[tuple[int, int]]]
            Start and end character of each token in each document.
        """
        token_embeddings, token_offsets = self._encode_tokens(
            sentences,
            **kwargs,
        )
        return sliding_window(
            token_embeddings,
            token_offsets,
            window_size=window_size,
            step_size=step_size,
        )

encode_tokens(sentences, **kwargs)

Produces contextual token embeddings over all documents.

Parameters:

Name Type Description Default
sentences list[str]

Documents to encode contextually.

required
batch_size

Size of the batch of document to encode at once.

required
show_progress_bar

Indicates whether a progress bar should be displayed when encoding.

required

Returns:

Name Type Description
token_embeddings list[ndarray]

Embedding matrix of tokens for each document.

offsets list[list[tuple[int, int]]]

Start and end character of each token in each document.

Source code in turftopic/late.py
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
def encode_tokens(
    self,
    sentences: list[str],
    **kwargs,
):
    """Produces contextual token embeddings over all documents.

    Parameters
    ----------
    sentences: list[str]
        Documents to encode contextually.
    batch_size: int, default 32
        Size of the batch of document to encode at once.
    show_progress_bar: bool, default True
        Indicates whether a progress bar should be displayed when encoding.

    Returns
    -------
    token_embeddings: list[np.ndarray]
        Embedding matrix of tokens for each document.
    offsets: list[list[tuple[int, int]]]
        Start and end character of each token in each document.
    """
    # This is needed because the above implementation does not normalize embeddings,
    # which normally happens to document embeddings.
    token_embeddings, offsets = self._encode_tokens(
        sentences,
        **kwargs,
    )
    token_embeddings = [normalize(emb) for emb in token_embeddings]
    return token_embeddings, offsets

encode_windows(sentences, window_size=50, step_size=40, **kwargs)

Produces contextual embeddings for a sliding window of tokens similar to C-Top2Vec.

Parameters:

Name Type Description Default
sentences list[str]

Documents to encode contextually.

required
batch_size

Size of the batch of document to encode at once.

required
window_size int

Size of the sliding window.

50
step_size int

Step size of the window. If step_size < window_size, windows will overlap. If step_size == window_size, then windows are separate. If step_size > window_size, there will be gaps between the windows. In this case, we throw a warning, as this is probably unintended behaviour.

40
show_progress_bar

Indicates whether a progress bar should be displayed when encoding.

required

Returns:

Name Type Description
window_embeddings list[ndarray]

Embedding matrix of windows for each document.

offsets list[list[tuple[int, int]]]

Start and end character of each token in each document.

Source code in turftopic/late.py
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
def encode_windows(
    self,
    sentences: list[str],
    window_size: int = 50,
    step_size: int = 40,
    **kwargs,
):
    """Produces contextual embeddings for a sliding window of tokens similar to C-Top2Vec.

    Parameters
    ----------
    sentences: list[str]
        Documents to encode contextually.
    batch_size: int, default 32
        Size of the batch of document to encode at once.
    window_size: int, default 50
        Size of the sliding window.
    step_size: int, default 40
        Step size of the window.
        If step_size < window_size, windows will overlap.
        If step_size == window_size, then windows are separate.
        If step_size > window_size, there will be gaps between the windows.
        In this case, we throw a warning, as this is probably unintended behaviour.
    show_progress_bar: bool, default True
        Indicates whether a progress bar should be displayed when encoding.

    Returns
    -------
    window_embeddings: list[np.ndarray]
        Embedding matrix of windows for each document.
    offsets: list[list[tuple[int, int]]]
        Start and end character of each token in each document.
    """
    token_embeddings, token_offsets = self._encode_tokens(
        sentences,
        **kwargs,
    )
    return sliding_window(
        token_embeddings,
        token_offsets,
        window_size=window_size,
        step_size=step_size,
    )