Skip to content

SensTopic (BETA)

SensTopic is a version of Semantic Signal Separation, that only discovers positive signals, while allowing components to be unbounded. This is achieved with an algorithm called Semi-nonnegative Matrix Factorization or SNMF.

⚠ This model is still in an experimental phase. More documentation and a paper are on their way. ⚠

SensTopic uses a very efficient implementation of the SNMF algorithm, that is implemented in raw NumPy, but also in JAX. If you want to enable hardware acceleration and JIT compilation, make sure to install JAX before running the model.

pip install jax

SensTopic produces the same quality of topics as \(S^3\) without having to interpret negative topic descriptions, and also has better scaling properties. Our implementation of SNMF is considerably faster than FastICA, which \(S^3\) is based on.

FastICA vs SNMF runtime on the 20 newsgroups dataset with different number of topics.

Here's an example of running SensTopic on the 20 Newsgroups dataset:

from sklearn.datasets import fetch_20newsgroups
from turftopic import SensTopic

corpus = fetch_20newsgroups(
    subset="all",
    remove=("headers", "footers", "quotes"),
).data

model = SensTopic(25)
model.fit(corpus)

model.print_topics()
Topic ID Highest Ranking
...
8 gospels, mormon, catholics, protestant, mormons, synagogues, seminary, catholic, liturgy, churches
9 encryption, encrypt, encrypting, crypt, cryptosystem, cryptography, cryptosystems, decryption, encrypted, spying
10 palestinians, israelis, palestinian, israeli, gaza, israel, gazans, palestine, zionist, aviv
11 nasa, spacecraft, spaceflight, satellites, interplanetary, astronomy, astronauts, astronomical, orbiting, astronomers
12 imagewriter, colormaps, bitmap, bitmaps, pkzip, imagemagick, colormap, formats, adobe, ghostscript
...

Sparsity

SensTopic has a sparsity hyper-parameter, that roughly dictates how many documents will be assigned to a single document, where many topics per document get penalized. This means that the model is both a matrix factorization model, but can also function as a soft clustering model, depending on this parameter. Unlike clustering models, however, it may assign multiple topics to documents that have them, and won't force every document to contain only one topic.

Higher values will make your model more like a clustering model, while lower values will make it more like a decomposition model:

Click to see code
import pandas as pd
import numpy as np
import plotly.express as px
from sentence_transformers import SentenceTransformer
from datasets import load_dataset

from turftopic import SensTopic

ds = load_dataset("gopalkalpande/bbc-news-summary", split="train")
corpus = list(ds["Summaries"])

encoder = SentenceTransformer("all-MiniLM-L6-v2")
embeddings = encoder.encode(corpus, show_progress_bar=True)

models = []
doc_topic_ms = []
sparsities = np.array(
    [
        0.05,
        0.1,
        0.25,
        0.5,
        0.75,
        1.0,
        2.5,
        5.0,
        10.0,
    ]
)
for i, sparsity in enumerate(sparsities):
    model = SensTopic(
        n_components=3, random_state=42, sparsity=sparsity, encoder=encoder
    )
    doc_topic = model.fit_transform(corpus, embeddings=embeddings)
    doc_topic = (doc_topic.T / doc_topic.sum(axis=1)).T
    models.append(model)
    doc_topic_ms.append(doc_topic)
a_name, b_name, c_name = models[0].topic_names
records = []
for i, doc_topic in enumerate(doc_topic_ms):
    for dt in doc_topic:
        a, b, c, *_ = dt
        records.append(
            {
                "sparsity": sparsities[i],
                a_name: a,
                b_name: b,
                c_name: c,
                "topic": models[0].topic_names[np.argmax(dt)],
            }
        )
df = pd.DataFrame.from_records(records)
fig = px.scatter_ternary(
    df, a=a_name, b=b_name, c=c_name, animation_frame="sparsity", color="topic"
)
fig.show()
Ternary plot of topic distribution in a 3 topic SensTopic model varying with sparsity.

You can see that as the sparsity increases, topics get clustered much more clearly, and more weight gets allocated to the edges of the graph.

To see how many topics there are in your document you can use the plot_topic_decay() method, that shows you how topic weights get assigned to documents.

model.plot_topic_decay()
Topic Decay in a SensTopic Model with sparsity=1.

Automatic number of topics

SensTopic can learn the number of topics in a given dataset. In order to determine this quantity, we use a version of the Bayesian Information Criterion modified for NMF. This does not work equally well for all corpora, but it can be a powerful tool when the number of topics is not known a-priori.

In this example the model finds 6 topics in the BBC News dataset:

# pip install datasets
from datasets import load_dataset

ds = load_dataset("gopalkalpande/bbc-news-summary", split="train")
corpus = list(ds["Summaries"])

model = SensTopic("auto")
model.fit(corpus)
model.print_topics()
Topic ID Highest Ranking
0 liverpool, mourinho, chelsea, premiership, arsenal, striker, madrid, midfield, uefa, manchester
1 oscar, bafta, oscars, cast, cinema, hollywood, actor, screenplay, actors, films
2 mobile, mobiles, broadband, devices, digital, internet, computers, microsoft, phones, telecoms
3 tory, blair, minister, ministers, parliamentary, mps, parliament, politicians, constituency, ukip
4 tennis, competing, federer, wimbledon, iaaf, olympic, tournament, athlete, rugby, olympics
5 gdp, stock, economy, earnings, investments, investment, invest, exports, finance, economies

Batch fitting

SensTopic models can be fit in mini-batches. This is done by fitting separate models on all batches, and continuously merging models of the new batches into the current model.

Info

To find more information on model merging and its variants, please look at Model Merging.

from itertools import batched

BATCH_SIZE = 2000
corpus: Iterable[str] = [...]
batches = batched(corpus, BATCH_SIZE)

model = SensTopic(
    sparsity=5.0,
    random_state=42,
)
for batch in batches:
    batch = list(batch)
    batch_doc_topic = model.partial_fit_transform(
        batch, merge_method="asymmetric_mean"
    )
model.print_topics()

Citation

Please cite Turftopic when using the SensTopic model:

@article{
  Kardos2025,
  title = {Turftopic: Topic Modelling with Contextual Representations from Sentence Transformers},
  doi = {10.21105/joss.08183},
  url = {https://doi.org/10.21105/joss.08183},
  year = {2025},
  publisher = {The Open Journal},
  volume = {10},
  number = {111},
  pages = {8183},
  author = {Kardos, Márton and Enevoldsen, Kenneth C. and Kostkan, Jan and Kristensen-McLachlan, Ross Deans and Rocca, Roberta},
  journal = {Journal of Open Source Software} 
}

API Reference

turftopic.models.senstopic.SensTopic

Bases: ContextualModel, DynamicTopicModel, MultimodalModel

Semi-nonnegative Semantic Signal Separation.

from turftopic import SensTopic

corpus: list[str] = ["some text", "more text", ...]

model = SensTopic(10).fit(corpus)
model.print_topics()

Parameters:

Name Type Description Default
n_components Union[int, Literal['auto']]

Number of topics. If "auto", the number of topics is determined using BIC.

'auto'
encoder Union[Encoder, str, MultimodalEncoder]

Model to encode documents/terms, all-MiniLM-L6-v2 is the default.

'sentence-transformers/all-MiniLM-L6-v2'
vectorizer Optional[CountVectorizer]

Vectorizer used for term extraction. Can be used to prune or filter the vocabulary.

None
max_iter int

Maximum number of iterations for S-NMF.

200
feature_importance Literal['axial', 'angular', 'combined']

Defines whether the word's position on an axis ('axial'), it's angle to the axis ('angular') or their combination ('combined') should determine the word's importance for a topic.

'combined'
random_state Optional[int]

Random state to use so that results are exactly reproducible.

None
sparsity float

L1 penalty applied to document-topic proportions. Higher values push the model to assign fewer topics to a single document, while lower values will distribute topics across documents.

1
multilevel bool

If True, the model will also contain subtopics for each topic.

False
trf_kwargs

Keyword arguments to apply when loading the Encoder model.

None
encode_kwargs

Keyword arguments to apply encoding documents with the encoder.

None
Source code in turftopic/models/senstopic.py
  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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
class SensTopic(ContextualModel, DynamicTopicModel, MultimodalModel):
    """Semi-nonnegative Semantic Signal Separation.

    ```python
    from turftopic import SensTopic

    corpus: list[str] = ["some text", "more text", ...]

    model = SensTopic(10).fit(corpus)
    model.print_topics()
    ```

    Parameters
    ----------
    n_components: int, default "auto"
        Number of topics.
        If "auto", the number of topics is determined using BIC.
    encoder: str or SentenceTransformer
        Model to encode documents/terms, all-MiniLM-L6-v2 is the default.
    vectorizer: CountVectorizer, default None
        Vectorizer used for term extraction.
        Can be used to prune or filter the vocabulary.
    max_iter: int, default 200
        Maximum number of iterations for S-NMF.
    feature_importance: "axial", "angular" or "combined", default "combined"
        Defines whether the word's position on an axis ('axial'), it's angle to the axis ('angular')
        or their combination ('combined') should determine the word's importance for a topic.
    random_state: int, default None
        Random state to use so that results are exactly reproducible.
    sparsity: float, default 1
        L1 penalty applied to document-topic proportions.
        Higher values push the model to assign fewer topics to a single document,
        while lower values will distribute topics across documents.
    multilevel: bool, default False
        If True, the model will also contain subtopics for each topic.
    trf_kwargs: dict, default None
        Keyword arguments to apply when loading the Encoder model.
    encode_kwargs: dict, default None
        Keyword arguments to apply encoding documents with the encoder.
    """

    def __init__(
        self,
        n_components: Union[int, Literal["auto"]] = "auto",
        encoder: Union[
            Encoder, str, MultimodalEncoder
        ] = "sentence-transformers/all-MiniLM-L6-v2",
        vectorizer: Optional[CountVectorizer] = None,
        max_iter: int = 200,
        feature_importance: Literal[
            "axial", "angular", "combined"
        ] = "combined",
        random_state: Optional[int] = None,
        sparsity: float = 1,
        multilevel: bool = False,
        trf_kwargs=None,
        encode_kwargs=None,
    ):
        self.n_components = n_components
        self.encoder = encoder
        self.trf_kwargs = trf_kwargs
        self.encode_kwargs = encode_kwargs
        self.feature_importance = feature_importance
        self.load_encoder()
        self.validate_encoder()
        if vectorizer is None:
            self.vectorizer = default_vectorizer()
        else:
            self.vectorizer = vectorizer
        self.max_iter = max_iter
        self.random_state = random_state
        self.sparsity = sparsity
        self.multilevel = multilevel

    def estimate_components(
        self, feature_importance: Literal["axial", "angular", "combined"]
    ) -> np.ndarray:
        """Reestimates components based on the chosen feature_importance method."""
        if feature_importance == "axial":
            self.components_ = self.axial_components_
        elif feature_importance == "angular":
            self.components_ = self.angular_components_
        elif feature_importance == "combined":
            self.components_ = (
                np.square(self.axial_components_) * self.angular_components_
            )
        if hasattr(self, "axial_temporal_components_"):
            if feature_importance == "axial":
                self.temporal_components_ = self.axial_temporal_components_
            elif feature_importance == "angular":
                self.temporal_components_ = self.angular_temporal_components_
            elif feature_importance == "combined":
                self.temporal_components_ = (
                    np.square(self.axial_temporal_components_)
                    * self.angular_temporal_components_
                )
        return self.components_

    def fit_supervised(
        self,
        raw_documents,
        y: np.ndarray,
        embeddings: Optional[np.ndarray] = None,
    ):
        console = Console()
        self.embeddings = embeddings
        with console.status("Fitting model") as status:
            if self.embeddings is None:
                status.update("Encoding documents")
                self.embeddings = self.encode_documents(raw_documents)
                console.log("Documents encoded.")
            doc_topic = y
            self.n_components_ = y.shape[1]
            self.decomposition = SNMF(
                self.n_components_,
                max_iter=self.max_iter,
                sparsity=self.sparsity,
                random_state=self.random_state,
                G=y,
            )
            status.update("Calculating components")
            self.decomposition.fit(embeddings)
            console.log("Components calculated.")
            status.update("Extracting terms.")
            vocab = self.vectorizer.fit(raw_documents).get_feature_names_out()
            console.log("Term extraction done.")
            if getattr(self, "vocab_embeddings", None) is None:
                status.update("Encoding vocabulary")
                self.vocab_embeddings = self.encode_vocabulary_items(vocab)
            if self.vocab_embeddings.shape[1] != self.embeddings.shape[1]:
                raise ValueError(
                    NOT_MATCHING_ERROR.format(
                        n_dims=self.embeddings.shape[1],
                        n_word_dims=self.vocab_embeddings.shape[1],
                    )
                )
            console.log("Vocabulary encoded.")
            status.update("Estimating term importances")
            vocab_topic = self.decomposition.transform(self.vocab_embeddings)
            self.axial_components_ = vocab_topic.T
            if self.feature_importance == "axial":
                self.components_ = self.axial_components_
            elif self.feature_importance == "angular":
                self.components_ = self.angular_components_
            elif self.feature_importance == "combined":
                self.components_ = (
                    np.square(self.axial_components_)
                    * self.angular_components_
                )
            self.top_documents = self.get_top_documents(
                raw_documents, document_topic_matrix=doc_topic
            )
            self.document_topic_matrix = doc_topic
            console.log("Model fitting done.")
            self.hierarchy = TopicNode.create_root(
                self, self.components_, self.document_topic_matrix
            )
            if self.multilevel:
                status.update("Estimating subtopics.")
                self.add_subtopics()
                console.log("Subtopics estimated.")
        return self

    def fit_transform(
        self, raw_documents, y=None, embeddings: Optional[np.ndarray] = None
    ) -> np.ndarray:
        console = Console()
        self.embeddings = embeddings
        with console.status("Fitting model") as status:
            if self.embeddings is None:
                status.update("Encoding documents")
                self.embeddings = self.encode_documents(raw_documents)
                console.log("Documents encoded.")
            if self.n_components == "auto":
                status.update("Finding the number of components.")
                self.n_components_ = optimize_n_components(
                    partial(
                        bic_snmf, X=self.embeddings, sparsity=self.sparsity
                    ),
                    min_n=1,
                    verbose=True,
                )
                console.log("N components set at: " + str(self.n_components_))
            else:
                self.n_components_ = self.n_components
            self.decomposition = SNMF(
                self.n_components_,
                max_iter=self.max_iter,
                sparsity=self.sparsity,
                random_state=self.random_state,
            )
            status.update("Decomposing embeddings")
            doc_topic = self.decomposition.fit_transform(self.embeddings, y=y)
            console.log("Decomposition done.")
            status.update("Extracting terms.")
            vocab = self.vectorizer.fit(raw_documents).get_feature_names_out()
            console.log("Term extraction done.")
            if getattr(self, "vocab_embeddings", None) is None:
                status.update("Encoding vocabulary")
                self.vocab_embeddings = self.encode_vocabulary_items(vocab)
            if self.vocab_embeddings.shape[1] != self.embeddings.shape[1]:
                raise ValueError(
                    NOT_MATCHING_ERROR.format(
                        n_dims=self.embeddings.shape[1],
                        n_word_dims=self.vocab_embeddings.shape[1],
                    )
                )
            console.log("Vocabulary encoded.")
            status.update("Estimating term importances")
            vocab_topic = self.decomposition.transform(self.vocab_embeddings)
            self.axial_components_ = vocab_topic.T
            if self.feature_importance == "axial":
                self.components_ = self.axial_components_
            elif self.feature_importance == "angular":
                self.components_ = self.angular_components_
            elif self.feature_importance == "combined":
                self.components_ = (
                    np.square(self.axial_components_)
                    * self.angular_components_
                )
            self.top_documents = self.get_top_documents(
                raw_documents, document_topic_matrix=doc_topic
            )
            self.document_topic_matrix = doc_topic
            console.log("Model fitting done.")
            self.hierarchy = TopicNode.create_root(
                self, self.components_, self.document_topic_matrix
            )
            if self.multilevel:
                status.update("Estimating subtopics.")
                self.add_subtopics()
                console.log("Subtopics estimated.")
        return doc_topic

    def add_subtopics(self):
        node = self.hierarchy
        doc_topic_matrix = np.stack(
            [child.document_topic_vector for child in node.children]
        ).T
        self.submodels_ = []
        labels = doc_topic_matrix.argmax(axis=1)
        for i_child, old_child in enumerate(node.children):
            _emb = self.embeddings[labels == i_child]
            if self.n_components == "auto":
                snmf = init_snmf_auto(
                    _emb,
                    sparsity=self.sparsity,
                    random_state=self.random_state,
                )
            else:
                snmf = SNMF(
                    n_components=self.n_components,
                    sparsity=self.sparsity,
                    random_state=self.random_state,
                )
            if snmf.n_components == 1:
                continue
            self.submodels_.append(snmf)
            _dt = snmf.fit_transform(_emb)
            components = snmf.transform(self.vocab_embeddings).T
            doc_topic = snmf.transform(self.embeddings)
            old_child.children = []
            for topic_id, comp, doc_top in zip(
                np.arange(components.shape[0]), components, doc_topic.T
            ):
                old_child.children.append(
                    TopicNode(
                        self,
                        path=(*old_child.path, topic_id),
                        word_importance=comp,
                        document_topic_vector=doc_top,
                        children=None,
                    )
                )

    def partial_fit_transform(
        self,
        raw_documents,
        y=None,
        embeddings=None,
        timestamps=None,
        n_new_components: int = "auto",
        match_threshold=0.7,
        merge_method: str | Callable = "asymmetric_mean",
        weighted=True,
    ):
        """Updates topic model by merging it with another one trained on the new data.
        Can also be used in a dynamic setting, in these cases,
        it is assumed that all new documents belong to one new timeslice.

        IMPORTANT: When using dynamic online fitting, use an asymmetric merging method (asymmetric_mean or keep_first)

        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
            Precomputed document encodings.
        n_new_components: int, default "auto"
            Determines how many topics will get extracted from the new data.
            If "auto", the number of topics gets determined by the BIC.
        match_threshold: float, default 0.7
            Cosine similarity threshold, above which topics are to be considered the same.
        merge_method: {'symmetric_mean', 'asymmetric_mean', 'keep_first'} or Callable, default 'symmetric_mean'
            Method for merging the two topic models.
             - `'symmetric_mean'` Treats the two models as equal, and takes the mean of matching topics.
               Matches are found by building a graph of topic connections based on the similarity threshold.
               Each new topic will be one graph component.
             - `'asymmetric_mean'` Merges new topics into the old topics and takes their mean.
             - `'keep_first'` Keeps all components untouched in the current model,
               and only adds new components from the new model that do not match.
        weighted: bool, default True
            Indicates whether the merge aggregation should be weighted by the number of documents the
            two models have seen.
        Returns
        -------
        ndarray of shape (n_documents, n_topics)
            Document-topic matrix.
        """
        if timestamps is not None:
            if isinstance(merge_method, str) and merge_method.startswith(
                "symmetric_mean"
            ):
                raise ValueError(
                    "partial_fit with symmetric merging only works in a non-dynamic setting. Use an asymmetric merging function when online fitting a model."
                )
            if (getattr(self, "components_", None) is None) or (
                getattr(self, "time_bin_edges", None) is None
            ):
                return self.fit_transform_dynamic(
                    raw_documents,
                    embeddings=embeddings,
                    timestamps=timestamps,
                    bins=1,
                )
        if getattr(self, "components_", None) is None:
            if timestamps is None:
                return self.fit_transform(raw_documents, embeddings=embeddings)
        if timestamps is not None:
            last_edge = self.time_bin_edges[-1]
            is_before = [(ts <= last_edge) for ts in timestamps]
            n_before = np.sum(is_before)
            if n_before:
                raise ValueError(
                    "When using partial fitting on a dynamic model, all new documents have to be in a new time slice. "
                    f"Currently there are {n_before} documents from before {last_edge}. Remove these before fitting."
                )
        if embeddings is None:
            embeddings = self.encode_documents(raw_documents)
        if n_new_components == "auto":
            n_new_components = optimize_n_components(
                partial(
                    bic_snmf,
                    X=embeddings,
                    sparsity=self.sparsity,
                ),
                min_n=1,
                verbose=True,
                tolerance=10,
            )
        new_decomp = SNMF(
            n_new_components,
            max_iter=self.max_iter,
            sparsity=self.sparsity,
            random_state=self.random_state,
        )
        new_doc_topic = new_decomp.fit_transform(embeddings)
        self.decomposition, self.merge_history_ = (
            self.decomposition.merge_with(
                new_decomp,
                merge_method=merge_method,
                match_threshold=match_threshold,
                weighted=weighted,
            )
        )
        if isinstance(merge_method, str) and (merge_method == "keep_first"):
            n_diff = self.decomposition.n_components - self.n_components_
            # Updating topic names:
            old_topic_names = getattr(self, "topic_names_", None)
            if old_topic_names is not None:
                delattr(self, "topic_names_")
                self.topic_names_ = [
                    *old_topic_names,
                    *self.topic_names[-n_diff:],
                ]
            for new_dt in new_doc_topic[:, -n_diff:].T:
                top = np.argsort(-new_dt)[:10]
                for i_top in top:
                    self.top_documents.append(raw_documents[i_top])
        else:
            self.top_documents = self.get_top_documents(
                raw_documents=raw_documents,
                document_topic_matrix=new_doc_topic,
            )
            try:
                delattr(self, "topic_names_")
            except AttributeError:
                pass
        if timestamps is not None:
            n_diff = self.decomposition.n_components - self.n_components_
            if n_diff < 0:
                raise ValueError(
                    "partial_fit with symmetric merging only works in a non-dynamic setting. Use an asymmetric merging function when online fitting a model."
                )
            self.time_bin_edges.append(
                max(timestamps) + timedelta(microseconds=1)
            )
            t_components = []
            t_importance = []
            for t_component, t_imp in zip(
                self.axial_temporal_components_, self.temporal_importance_
            ):
                t_component = np.pad(
                    t_component,
                    [(0, n_diff), (0, 0)],
                    mode="constant",
                    constant_values=0,
                )
                t_imp = np.pad(
                    t_imp,
                    (0, n_diff),
                    mode="constant",
                    constant_values=0,
                )
                t_components.append(t_component)
                t_importance.append(t_imp)
            t_dt = np.zeros(
                (new_doc_topic.shape[0], self.decomposition.n_components)
            )
            for i_new, joint_index in enumerate(self.merge_history_[1]):
                t_dt[:, joint_index] = new_doc_topic[:, i_new]
            new_imp, new_comp = self._fit_timebin(embeddings, t_dt)
            t_components.append(new_comp)
            t_importance.append(new_imp)
            self.axial_temporal_components_ = np.stack(t_components)
            self.temporal_importance_ = np.stack(t_importance)
        self.n_components_ = self.decomposition.n_components
        new_vectorizer = clone(self.vectorizer).fit(raw_documents)
        self.update_vocabulary(new_vectorizer)
        vocab_topic = self.decomposition.transform(self.vocab_embeddings)
        self.axial_components_ = vocab_topic.T
        self.estimate_components(self.feature_importance)
        return self.decomposition.transform(embeddings)

    def partial_fit(
        self,
        raw_documents,
        y=None,
        embeddings=None,
        timestamps=None,
        n_new_components: int = "auto",
        match_threshold=0.7,
        merge_method: str | Callable = "asymmetric_mean",
        weighted=True,
    ):
        """Updates topic model by merging it with another one trained on the new data.
        Can also be used in a dynamic setting, in these cases,
        it is assumed that all new documents belong to one new timeslice.

        IMPORTANT: When using dynamic online fitting, use an asymmetric merging method (asymmetric_mean or keep_first)

        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
            Precomputed document encodings.
        n_new_components: int, default "auto"
            Determines how many topics will get extracted from the new data.
            If "auto", the number of topics gets determined by the BIC.
        match_threshold: float, default 0.7
            Cosine similarity threshold, above which topics are to be considered the same.
        merge_method: {'symmetric_mean', 'asymmetric_mean', 'keep_first'} or Callable, default 'symmetric_mean'
            Method for merging the two topic models.
             - `'symmetric_mean'` Treats the two models as equal, and takes the mean of matching topics.
               Matches are found by building a graph of topic connections based on the similarity threshold.
               Each new topic will be one graph component.
             - `'asymmetric_mean'` Merges new topics into the old topics and takes their mean.
             - `'keep_first'` Keeps all components untouched in the current model,
               and only adds new components from the new model that do not match.
        weighted: bool, default True
            Indicates whether the merge aggregation should be weighted by the number of documents the
            two models have seen.

        Returns
        -------
        Self
            Updated topic model.
        """
        self.partial_fit_transform(
            raw_documents,
            y=y,
            embeddings=embeddings,
            timestamps=timestamps,
            n_new_components=n_new_components,
            match_threshold=match_threshold,
            merge_method=merge_method,
            weighted=weighted,
        )
        return self

    def merge_with(
        self,
        other: SensTopic,
        match_threshold=0.7,
        merge_method: str | Callable = "asymmetric_mean",
        weighted=True,
    ):
        """Updates topic model by merging it with another one trained on the new data.

        !!! warning:
            Only static properties of a model will be taken into account when merging.
            Attributes associated with top exemplars and temporal data will be **DELETED** from the model.
            The model will be modified in-place.
            We recommend that you save the original model to disk to avoid losing data.

        Parameters
        ----------
        other: SensTopic
            Other topic model to merge this one with.
        match_threshold: float, default 0.7
            Cosine similarity threshold, above which topics are to be considered the same.
        merge_method: {'symmetric_mean', 'asymmetric_mean', 'keep_first'} or Callable, default 'symmetric_mean'
            Method for merging the two topic models.
             - `'symmetric_mean'` Treats the two models as equal, and takes the mean of matching topics.
               Matches are found by building a graph of topic connections based on the similarity threshold.
               Each new topic will be one graph component.
             - `'asymmetric_mean'` Merges new topics into the old topics and takes their mean.
             - `'keep_first'` Keeps all components untouched in the current model,
               and only adds new components from the new model that do not match.
        weighted: bool, default True
            Indicates whether the merge aggregation should be weighted by the number of documents the
            two models have seen.

        Returns
        -------
        Self
        """
        self.update_vocabulary(other)
        self.decomposition, self.merge_history_ = (
            self.decomposition.merge_with(
                other.decomposition,
                match_threshold=match_threshold,
                merge_method=merge_method,
                weighted=weighted,
            )
        )
        vocab_topic = self.decomposition.transform(self.vocab_embeddings)
        self.axial_components_ = vocab_topic.T
        if self.feature_importance == "axial":
            self.components_ = self.axial_components_
        elif self.feature_importance == "angular":
            self.components_ = self.angular_components_
        elif self.feature_importance == "combined":
            self.components_ = (
                np.square(self.axial_components_) * self.angular_components_
            )
        if hasattr(self, "top_documents"):
            delattr(self, "top_documents")
        if hasattr(self, "top_images"):
            delattr(self, "top_images")
        if hasattr(self, "temporal_components_"):
            delattr(self, "temporal_components_")
        if hasattr(self, "temporal_importance_"):
            delattr(self, "temporal_importance_")
        self.hierarchy = merge_hierarchies(
            self.hierarchy,
            other.hierarchy,
            self.components_,
            self.merge_history_,
            self.vectorizer,
            self,
        )
        return self

    @classmethod
    def merge_models(
        cls,
        models: list[SensTopic],
        match_threshold=0.7,
        merge_method: str | Callable = "asymmetric_mean",
        weighted=True,
    ):
        """Merges multiple SensTopic models together.
        The original models will not be modified.

        Parameters
        ----------
        models: list[SensTopic]
            SensTopic models to merge together.
        match_threshold: float, default 0.7
            Cosine similarity threshold, above which topics are to be considered the same.
        merge_method: {'symmetric_mean', 'asymmetric_mean', 'keep_first'} or Callable, default 'symmetric_mean'
            Method for merging the two topic models.
             - `'symmetric_mean'` Treats the two models as equal, and takes the mean of matching topics.
               Matches are found by building a graph of topic connections based on the similarity threshold.
               Each new topic will be one graph component.
             - `'asymmetric_mean'` Merges new topics into the old topics and takes their mean.
             - `'keep_first'` Keeps all components untouched in the current model,
               and only adds new components from the new model that do not match.
        weighted: bool, default True
            Indicates whether the merge aggregation should be weighted by the number of documents the
            two models have seen.

        Returns
        -------
        SensTopic
            Merged model.
        """
        if len(models) == 0:
            raise ValueError("List is empty, cannot merge zero topic models.")
        model = deepcopy(models[0])
        for new_model in models[1:]:
            model.merge_with(
                new_model,
                match_threshold=match_threshold,
                merge_method=merge_method,
                weighted=weighted,
            )
        return model

    def transform(self, raw_documents, embeddings=None):
        if embeddings is None:
            embeddings = self.encode_documents(raw_documents)
        return self.decomposition.transform(embeddings)

    def fit_transform_multimodal(
        self,
        raw_documents: list[str],
        images: list[ImageRepr],
        y=None,
        embeddings: Optional[MultimodalEmbeddings] = None,
    ) -> np.ndarray:
        self.validate_embeddings(embeddings)
        console = Console()
        self.images = images
        self.multimodal_embeddings = embeddings
        with console.status("Fitting model") as status:
            if self.multimodal_embeddings is None:
                status.update("Encoding documents")
                self.multimodal_embeddings = self.encode_multimodal(
                    raw_documents, images
                )
                console.log("Documents encoded.")
            self.embeddings = self.multimodal_embeddings["document_embeddings"]
            if self.n_components == "auto":
                status.update("Finding the number of components.")
                self.n_components_ = optimize_n_components(
                    partial(
                        bic_snmf, X=self.embeddings, sparsity=self.sparsity
                    ),
                    min_n=1,
                    verbose=True,
                )
                console.log("N components set at: " + str(self.n_components_))
            else:
                self.n_components_ = self.n_components
            self.decomposition = SNMF(
                self.n_components_,
                max_iter=self.max_iter,
                sparsity=self.sparsity,
                random_state=self.random_state,
            )
            status.update("Decomposing embeddings")
            doc_topic = self.decomposition.fit_transform(self.embeddings, y=y)
            console.log("Decomposition done.")
            status.update("Extracting terms.")
            vocab = self.vectorizer.fit(raw_documents).get_feature_names_out()
            console.log("Term extraction done.")
            status.update("Encoding vocabulary")
            self.vocab_embeddings = self.encode_documents(vocab)
            if self.vocab_embeddings.shape[1] != self.embeddings.shape[1]:
                raise ValueError(
                    NOT_MATCHING_ERROR.format(
                        n_dims=self.embeddings.shape[1],
                        n_word_dims=self.vocab_embeddings.shape[1],
                    )
                )
            console.log("Vocabulary encoded.")
            status.update("Estimating term importances")
            vocab_topic = self.decomposition.transform(self.vocab_embeddings)
            self.axial_components_ = vocab_topic.T
            if self.feature_importance == "axial":
                self.components_ = self.axial_components_
            elif self.feature_importance == "angular":
                self.components_ = self.angular_components_
            elif self.feature_importance == "combined":
                self.components_ = (
                    np.square(self.axial_components_)
                    * self.angular_components_
                )
            console.log("Model fitting done.")
            status.update("Transforming images")
            self.image_topic_matrix = self.transform(
                [], embeddings=self.multimodal_embeddings["image_embeddings"]
            )
            self.top_images = self.collect_top_images(
                images, self.image_topic_matrix
            )
            self.top_documents = self.get_top_documents(
                raw_documents, document_topic_matrix=doc_topic
            )
            console.log("Images transformed")
        return doc_topic

    def _fit_timebin(self, t_X, t_dt):
        t_imp = t_dt.mean(axis=0)
        t_F = self.decomposition.fit_timeslice(t_X, t_dt).T
        t_G = self.decomposition.transform(self.vocab_embeddings, F=t_F)
        t_components_ = t_G.T
        return t_imp, t_components_

    def fit_transform_dynamic(
        self,
        raw_documents,
        timestamps: list[datetime],
        embeddings: Optional[np.ndarray] = None,
        bins: Union[int, list[datetime]] = 10,
    ) -> np.ndarray:
        if getattr(self, "components_", None) is None:
            document_topic_matrix = self.fit_transform(
                raw_documents, embeddings=embeddings
            )
        else:
            document_topic_matrix = self.transform(
                raw_documents, embeddings=embeddings
            )
        console = Console()
        with console.status("Fitting temporally conditioned topics") as status:
            status.update("Labelling documents based on time bins.")
            time_labels, self.time_bin_edges = self.bin_timestamps(
                timestamps, bins
            )
            console.log("Documents binned.")
            status.update("Initializing components.")
            n_comp, n_vocab = self.components_.shape
            n_bins = len(self.time_bin_edges) - 1
            self.axial_temporal_components_ = np.full(
                (n_bins, n_comp, n_vocab),
                np.nan,
                dtype=self.components_.dtype,
            )
            console.log("Components initialized.")
            self.temporal_importance_ = np.zeros((n_bins, n_comp))
        for i_timebin in track(
            np.unique(time_labels),
            description="Calculating temporal components for each time slice.",
            console=console,
        ):
            t_dt = document_topic_matrix[time_labels == i_timebin]
            t_X = self.embeddings[time_labels == i_timebin]
            t_imp, t_comp = self._fit_timebin(t_X, t_dt)
            self.temporal_importance_[i_timebin, :] = t_imp
            self.axial_temporal_components_[i_timebin, :, :] = t_comp
        console.log("Temporal components computed.")
        with console.status("Post-processing components."):
            self.estimate_components(
                self.feature_importance,
            )
        console.log("Temporal fitting done.")
        return document_topic_matrix

    @property
    def angular_components_(self):
        """Reweights words based on their angle in ICA-space to the axis
        base vectors.
        """
        if not hasattr(self, "axial_components_"):
            raise NotFittedError("Model has not been fitted yet.")
        word_vectors = self.axial_components_.T
        n_topics = self.axial_components_.shape[0]
        axis_vectors = np.eye(n_topics)
        cosine_components = cosine_similarity(axis_vectors, word_vectors)
        return cosine_components

    @property
    def angular_temporal_components_(self):
        """Reweights words based on their angle in ICA-space to the axis
        base vectors in a dynamic model.
        """
        if not hasattr(self, "axial_temporal_components_"):
            raise NotFittedError("Model has not been fitted dynamically.")
        components = []
        for axial_components in self.axial_temporal_components_:
            word_vectors = axial_components.T
            n_topics = axial_components.shape[0]
            axis_vectors = np.eye(n_topics)
            cosine_components = cosine_similarity(axis_vectors, word_vectors)
            components.append(cosine_components)
        return np.stack(components)

    def plot_topic_decay(self):
        try:
            import plotly.graph_objects as go
        except (ImportError, ModuleNotFoundError) as e:
            raise ModuleNotFoundError(
                "Please install plotly if you intend to use plots in Turftopic."
            ) from e
        doc_topic = self.document_topic_matrix
        topic_proportions = []
        for dt in doc_topic:
            sum_dt = dt.sum()
            if sum_dt > 0:
                dt /= sum_dt
            dt = -np.sort(-dt)
            topic_proportions.append(dt)
        topic_proportions = np.stack(topic_proportions)
        med_prop = np.median(topic_proportions, axis=0)
        upper = np.quantile(topic_proportions, 0.975, axis=0)
        lower = np.quantile(topic_proportions, 0.025, axis=0)
        fig = go.Figure(
            [
                go.Scatter(
                    name="Median",
                    x=np.arange(self.n_components_),
                    y=med_prop,
                    mode="lines",
                    line=dict(color="rgb(31, 119, 180)"),
                ),
                go.Scatter(
                    name="Upper Bound",
                    x=np.arange(self.n_components_),
                    y=upper,
                    mode="lines",
                    marker=dict(color="#444"),
                    line=dict(width=0),
                    showlegend=False,
                ),
                go.Scatter(
                    name="Lower Bound",
                    x=np.arange(self.n_components_),
                    y=lower,
                    marker=dict(color="#444"),
                    line=dict(width=0),
                    mode="lines",
                    fillcolor="rgba(68, 68, 68, 0.3)",
                    fill="tonexty",
                    showlegend=False,
                ),
            ]
        )
        fig = fig.update_layout(
            template="plotly_white",
            xaxis_title="Topic Rank",
            yaxis_title="Topic Proportion",
            title="Topic Decay",
            font=dict(family="Merriweather", size=16),
        )
        return fig

    def plot_components(
        self, hover_text: Optional[list[str]] = None, **kwargs
    ):
        """Creates an interactive browser plot of the topics in your data using plotly.

        Parameters
        ----------
        hover_text: list of str, optional
            Text to show when hovering over a document.

        Returns
        -------
        plot
            Interactive datamap plot, you can call the `.show()` method to
            display it in your default browser or save it as static HTML using `.write_html()`.
        """
        doc_topic = self.document_topic_matrix
        coords = TSNE(2, metric="cosine").fit_transform(doc_topic)
        labels = np.argmax(doc_topic, axis=1)
        topics_present = np.sort(np.unique(labels))
        names = [self.topic_names[i] for i in topics_present]
        if getattr(self, "topic_descriptions", None) is not None:
            desc = [self.topic_descriptions[i] for i in topics_present]
        else:
            desc = None
        all_words = self.get_top_words()
        keywords = [all_words[i] for i in topics_present]
        fig = build_datamapplot(
            coords,
            labels=labels,
            topic_names=names,
            top_words=keywords,
            hover_text=hover_text,
            topic_descriptions=desc,
            classes=topics_present,
            # Boundaries are unlikely to be very clear
            cluster_boundary_polygons=False,
        )
        return fig

    def plot_components_datamapplot(
        self, hover_text: Optional[list[str]] = None, **kwargs
    ):
        """Creates an interactive browser plot of the topics in your data using datamapplot.

        Parameters
        ----------
        hover_text: list of str, optional
            Text to show when hovering over a document.

        Returns
        -------
        plot
            Interactive datamap plot, you can call the `.show()` method to
            display it in your default browser or save it as static HTML using `.write_html()`.
        """
        doc_topic = self.document_topic_matrix
        coords = TSNE(2, metric="cosine").fit_transform(doc_topic)
        labels = np.argmax(doc_topic, axis=1)
        topics_present = np.sort(np.unique(labels))
        names = [self.topic_names[i] for i in topics_present]
        if getattr(self, "topic_descriptions", None) is not None:
            desc = [self.topic_descriptions[i] for i in topics_present]
        else:
            desc = None
        all_words = self.get_top_words()
        keywords = [all_words[i] for i in topics_present]
        fig = build_datamapplot(
            coords,
            labels=labels,
            topic_names=names,
            top_words=keywords,
            hover_text=hover_text,
            topic_descriptions=desc,
            classes=topics_present,
            # Boundaries are unlikely to be very clear
            cluster_boundary_polygons=False,
        )
        return fig

angular_components_ property

Reweights words based on their angle in ICA-space to the axis base vectors.

angular_temporal_components_ property

Reweights words based on their angle in ICA-space to the axis base vectors in a dynamic model.

estimate_components(feature_importance)

Reestimates components based on the chosen feature_importance method.

Source code in turftopic/models/senstopic.py
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
def estimate_components(
    self, feature_importance: Literal["axial", "angular", "combined"]
) -> np.ndarray:
    """Reestimates components based on the chosen feature_importance method."""
    if feature_importance == "axial":
        self.components_ = self.axial_components_
    elif feature_importance == "angular":
        self.components_ = self.angular_components_
    elif feature_importance == "combined":
        self.components_ = (
            np.square(self.axial_components_) * self.angular_components_
        )
    if hasattr(self, "axial_temporal_components_"):
        if feature_importance == "axial":
            self.temporal_components_ = self.axial_temporal_components_
        elif feature_importance == "angular":
            self.temporal_components_ = self.angular_temporal_components_
        elif feature_importance == "combined":
            self.temporal_components_ = (
                np.square(self.axial_temporal_components_)
                * self.angular_temporal_components_
            )
    return self.components_

merge_models(models, match_threshold=0.7, merge_method='asymmetric_mean', weighted=True) classmethod

Merges multiple SensTopic models together. The original models will not be modified.

Parameters:

Name Type Description Default
models list[SensTopic]

SensTopic models to merge together.

required
match_threshold

Cosine similarity threshold, above which topics are to be considered the same.

0.7
merge_method str | Callable

Method for merging the two topic models. - 'symmetric_mean' Treats the two models as equal, and takes the mean of matching topics. Matches are found by building a graph of topic connections based on the similarity threshold. Each new topic will be one graph component. - 'asymmetric_mean' Merges new topics into the old topics and takes their mean. - 'keep_first' Keeps all components untouched in the current model, and only adds new components from the new model that do not match.

'asymmetric_mean'
weighted

Indicates whether the merge aggregation should be weighted by the number of documents the two models have seen.

True

Returns:

Type Description
SensTopic

Merged model.

Source code in turftopic/models/senstopic.py
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
@classmethod
def merge_models(
    cls,
    models: list[SensTopic],
    match_threshold=0.7,
    merge_method: str | Callable = "asymmetric_mean",
    weighted=True,
):
    """Merges multiple SensTopic models together.
    The original models will not be modified.

    Parameters
    ----------
    models: list[SensTopic]
        SensTopic models to merge together.
    match_threshold: float, default 0.7
        Cosine similarity threshold, above which topics are to be considered the same.
    merge_method: {'symmetric_mean', 'asymmetric_mean', 'keep_first'} or Callable, default 'symmetric_mean'
        Method for merging the two topic models.
         - `'symmetric_mean'` Treats the two models as equal, and takes the mean of matching topics.
           Matches are found by building a graph of topic connections based on the similarity threshold.
           Each new topic will be one graph component.
         - `'asymmetric_mean'` Merges new topics into the old topics and takes their mean.
         - `'keep_first'` Keeps all components untouched in the current model,
           and only adds new components from the new model that do not match.
    weighted: bool, default True
        Indicates whether the merge aggregation should be weighted by the number of documents the
        two models have seen.

    Returns
    -------
    SensTopic
        Merged model.
    """
    if len(models) == 0:
        raise ValueError("List is empty, cannot merge zero topic models.")
    model = deepcopy(models[0])
    for new_model in models[1:]:
        model.merge_with(
            new_model,
            match_threshold=match_threshold,
            merge_method=merge_method,
            weighted=weighted,
        )
    return model

merge_with(other, match_threshold=0.7, merge_method='asymmetric_mean', weighted=True)

Updates topic model by merging it with another one trained on the new data.

!!! warning: Only static properties of a model will be taken into account when merging. Attributes associated with top exemplars and temporal data will be DELETED from the model. The model will be modified in-place. We recommend that you save the original model to disk to avoid losing data.

Parameters:

Name Type Description Default
other SensTopic

Other topic model to merge this one with.

required
match_threshold

Cosine similarity threshold, above which topics are to be considered the same.

0.7
merge_method str | Callable

Method for merging the two topic models. - 'symmetric_mean' Treats the two models as equal, and takes the mean of matching topics. Matches are found by building a graph of topic connections based on the similarity threshold. Each new topic will be one graph component. - 'asymmetric_mean' Merges new topics into the old topics and takes their mean. - 'keep_first' Keeps all components untouched in the current model, and only adds new components from the new model that do not match.

'asymmetric_mean'
weighted

Indicates whether the merge aggregation should be weighted by the number of documents the two models have seen.

True

Returns:

Type Description
Self
Source code in turftopic/models/senstopic.py
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
def merge_with(
    self,
    other: SensTopic,
    match_threshold=0.7,
    merge_method: str | Callable = "asymmetric_mean",
    weighted=True,
):
    """Updates topic model by merging it with another one trained on the new data.

    !!! warning:
        Only static properties of a model will be taken into account when merging.
        Attributes associated with top exemplars and temporal data will be **DELETED** from the model.
        The model will be modified in-place.
        We recommend that you save the original model to disk to avoid losing data.

    Parameters
    ----------
    other: SensTopic
        Other topic model to merge this one with.
    match_threshold: float, default 0.7
        Cosine similarity threshold, above which topics are to be considered the same.
    merge_method: {'symmetric_mean', 'asymmetric_mean', 'keep_first'} or Callable, default 'symmetric_mean'
        Method for merging the two topic models.
         - `'symmetric_mean'` Treats the two models as equal, and takes the mean of matching topics.
           Matches are found by building a graph of topic connections based on the similarity threshold.
           Each new topic will be one graph component.
         - `'asymmetric_mean'` Merges new topics into the old topics and takes their mean.
         - `'keep_first'` Keeps all components untouched in the current model,
           and only adds new components from the new model that do not match.
    weighted: bool, default True
        Indicates whether the merge aggregation should be weighted by the number of documents the
        two models have seen.

    Returns
    -------
    Self
    """
    self.update_vocabulary(other)
    self.decomposition, self.merge_history_ = (
        self.decomposition.merge_with(
            other.decomposition,
            match_threshold=match_threshold,
            merge_method=merge_method,
            weighted=weighted,
        )
    )
    vocab_topic = self.decomposition.transform(self.vocab_embeddings)
    self.axial_components_ = vocab_topic.T
    if self.feature_importance == "axial":
        self.components_ = self.axial_components_
    elif self.feature_importance == "angular":
        self.components_ = self.angular_components_
    elif self.feature_importance == "combined":
        self.components_ = (
            np.square(self.axial_components_) * self.angular_components_
        )
    if hasattr(self, "top_documents"):
        delattr(self, "top_documents")
    if hasattr(self, "top_images"):
        delattr(self, "top_images")
    if hasattr(self, "temporal_components_"):
        delattr(self, "temporal_components_")
    if hasattr(self, "temporal_importance_"):
        delattr(self, "temporal_importance_")
    self.hierarchy = merge_hierarchies(
        self.hierarchy,
        other.hierarchy,
        self.components_,
        self.merge_history_,
        self.vectorizer,
        self,
    )
    return self

partial_fit(raw_documents, y=None, embeddings=None, timestamps=None, n_new_components='auto', match_threshold=0.7, merge_method='asymmetric_mean', weighted=True)

Updates topic model by merging it with another one trained on the new data. Can also be used in a dynamic setting, in these cases, it is assumed that all new documents belong to one new timeslice.

IMPORTANT: When using dynamic online fitting, use an asymmetric merging method (asymmetric_mean or keep_first)

Parameters:

Name Type Description Default
raw_documents

Documents to fit the model on.

required
y

Ignored, exists for sklearn compatibility.

None
embeddings

Precomputed document encodings.

None
n_new_components int

Determines how many topics will get extracted from the new data. If "auto", the number of topics gets determined by the BIC.

'auto'
match_threshold

Cosine similarity threshold, above which topics are to be considered the same.

0.7
merge_method str | Callable

Method for merging the two topic models. - 'symmetric_mean' Treats the two models as equal, and takes the mean of matching topics. Matches are found by building a graph of topic connections based on the similarity threshold. Each new topic will be one graph component. - 'asymmetric_mean' Merges new topics into the old topics and takes their mean. - 'keep_first' Keeps all components untouched in the current model, and only adds new components from the new model that do not match.

'asymmetric_mean'
weighted

Indicates whether the merge aggregation should be weighted by the number of documents the two models have seen.

True

Returns:

Type Description
Self

Updated topic model.

Source code in turftopic/models/senstopic.py
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
def partial_fit(
    self,
    raw_documents,
    y=None,
    embeddings=None,
    timestamps=None,
    n_new_components: int = "auto",
    match_threshold=0.7,
    merge_method: str | Callable = "asymmetric_mean",
    weighted=True,
):
    """Updates topic model by merging it with another one trained on the new data.
    Can also be used in a dynamic setting, in these cases,
    it is assumed that all new documents belong to one new timeslice.

    IMPORTANT: When using dynamic online fitting, use an asymmetric merging method (asymmetric_mean or keep_first)

    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
        Precomputed document encodings.
    n_new_components: int, default "auto"
        Determines how many topics will get extracted from the new data.
        If "auto", the number of topics gets determined by the BIC.
    match_threshold: float, default 0.7
        Cosine similarity threshold, above which topics are to be considered the same.
    merge_method: {'symmetric_mean', 'asymmetric_mean', 'keep_first'} or Callable, default 'symmetric_mean'
        Method for merging the two topic models.
         - `'symmetric_mean'` Treats the two models as equal, and takes the mean of matching topics.
           Matches are found by building a graph of topic connections based on the similarity threshold.
           Each new topic will be one graph component.
         - `'asymmetric_mean'` Merges new topics into the old topics and takes their mean.
         - `'keep_first'` Keeps all components untouched in the current model,
           and only adds new components from the new model that do not match.
    weighted: bool, default True
        Indicates whether the merge aggregation should be weighted by the number of documents the
        two models have seen.

    Returns
    -------
    Self
        Updated topic model.
    """
    self.partial_fit_transform(
        raw_documents,
        y=y,
        embeddings=embeddings,
        timestamps=timestamps,
        n_new_components=n_new_components,
        match_threshold=match_threshold,
        merge_method=merge_method,
        weighted=weighted,
    )
    return self

partial_fit_transform(raw_documents, y=None, embeddings=None, timestamps=None, n_new_components='auto', match_threshold=0.7, merge_method='asymmetric_mean', weighted=True)

Updates topic model by merging it with another one trained on the new data. Can also be used in a dynamic setting, in these cases, it is assumed that all new documents belong to one new timeslice.

IMPORTANT: When using dynamic online fitting, use an asymmetric merging method (asymmetric_mean or keep_first)

Parameters:

Name Type Description Default
raw_documents

Documents to fit the model on.

required
y

Ignored, exists for sklearn compatibility.

None
embeddings

Precomputed document encodings.

None
n_new_components int

Determines how many topics will get extracted from the new data. If "auto", the number of topics gets determined by the BIC.

'auto'
match_threshold

Cosine similarity threshold, above which topics are to be considered the same.

0.7
merge_method str | Callable

Method for merging the two topic models. - 'symmetric_mean' Treats the two models as equal, and takes the mean of matching topics. Matches are found by building a graph of topic connections based on the similarity threshold. Each new topic will be one graph component. - 'asymmetric_mean' Merges new topics into the old topics and takes their mean. - 'keep_first' Keeps all components untouched in the current model, and only adds new components from the new model that do not match.

'asymmetric_mean'
weighted

Indicates whether the merge aggregation should be weighted by the number of documents the two models have seen.

True

Returns:

Type Description
ndarray of shape (n_documents, n_topics)

Document-topic matrix.

Source code in turftopic/models/senstopic.py
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
def partial_fit_transform(
    self,
    raw_documents,
    y=None,
    embeddings=None,
    timestamps=None,
    n_new_components: int = "auto",
    match_threshold=0.7,
    merge_method: str | Callable = "asymmetric_mean",
    weighted=True,
):
    """Updates topic model by merging it with another one trained on the new data.
    Can also be used in a dynamic setting, in these cases,
    it is assumed that all new documents belong to one new timeslice.

    IMPORTANT: When using dynamic online fitting, use an asymmetric merging method (asymmetric_mean or keep_first)

    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
        Precomputed document encodings.
    n_new_components: int, default "auto"
        Determines how many topics will get extracted from the new data.
        If "auto", the number of topics gets determined by the BIC.
    match_threshold: float, default 0.7
        Cosine similarity threshold, above which topics are to be considered the same.
    merge_method: {'symmetric_mean', 'asymmetric_mean', 'keep_first'} or Callable, default 'symmetric_mean'
        Method for merging the two topic models.
         - `'symmetric_mean'` Treats the two models as equal, and takes the mean of matching topics.
           Matches are found by building a graph of topic connections based on the similarity threshold.
           Each new topic will be one graph component.
         - `'asymmetric_mean'` Merges new topics into the old topics and takes their mean.
         - `'keep_first'` Keeps all components untouched in the current model,
           and only adds new components from the new model that do not match.
    weighted: bool, default True
        Indicates whether the merge aggregation should be weighted by the number of documents the
        two models have seen.
    Returns
    -------
    ndarray of shape (n_documents, n_topics)
        Document-topic matrix.
    """
    if timestamps is not None:
        if isinstance(merge_method, str) and merge_method.startswith(
            "symmetric_mean"
        ):
            raise ValueError(
                "partial_fit with symmetric merging only works in a non-dynamic setting. Use an asymmetric merging function when online fitting a model."
            )
        if (getattr(self, "components_", None) is None) or (
            getattr(self, "time_bin_edges", None) is None
        ):
            return self.fit_transform_dynamic(
                raw_documents,
                embeddings=embeddings,
                timestamps=timestamps,
                bins=1,
            )
    if getattr(self, "components_", None) is None:
        if timestamps is None:
            return self.fit_transform(raw_documents, embeddings=embeddings)
    if timestamps is not None:
        last_edge = self.time_bin_edges[-1]
        is_before = [(ts <= last_edge) for ts in timestamps]
        n_before = np.sum(is_before)
        if n_before:
            raise ValueError(
                "When using partial fitting on a dynamic model, all new documents have to be in a new time slice. "
                f"Currently there are {n_before} documents from before {last_edge}. Remove these before fitting."
            )
    if embeddings is None:
        embeddings = self.encode_documents(raw_documents)
    if n_new_components == "auto":
        n_new_components = optimize_n_components(
            partial(
                bic_snmf,
                X=embeddings,
                sparsity=self.sparsity,
            ),
            min_n=1,
            verbose=True,
            tolerance=10,
        )
    new_decomp = SNMF(
        n_new_components,
        max_iter=self.max_iter,
        sparsity=self.sparsity,
        random_state=self.random_state,
    )
    new_doc_topic = new_decomp.fit_transform(embeddings)
    self.decomposition, self.merge_history_ = (
        self.decomposition.merge_with(
            new_decomp,
            merge_method=merge_method,
            match_threshold=match_threshold,
            weighted=weighted,
        )
    )
    if isinstance(merge_method, str) and (merge_method == "keep_first"):
        n_diff = self.decomposition.n_components - self.n_components_
        # Updating topic names:
        old_topic_names = getattr(self, "topic_names_", None)
        if old_topic_names is not None:
            delattr(self, "topic_names_")
            self.topic_names_ = [
                *old_topic_names,
                *self.topic_names[-n_diff:],
            ]
        for new_dt in new_doc_topic[:, -n_diff:].T:
            top = np.argsort(-new_dt)[:10]
            for i_top in top:
                self.top_documents.append(raw_documents[i_top])
    else:
        self.top_documents = self.get_top_documents(
            raw_documents=raw_documents,
            document_topic_matrix=new_doc_topic,
        )
        try:
            delattr(self, "topic_names_")
        except AttributeError:
            pass
    if timestamps is not None:
        n_diff = self.decomposition.n_components - self.n_components_
        if n_diff < 0:
            raise ValueError(
                "partial_fit with symmetric merging only works in a non-dynamic setting. Use an asymmetric merging function when online fitting a model."
            )
        self.time_bin_edges.append(
            max(timestamps) + timedelta(microseconds=1)
        )
        t_components = []
        t_importance = []
        for t_component, t_imp in zip(
            self.axial_temporal_components_, self.temporal_importance_
        ):
            t_component = np.pad(
                t_component,
                [(0, n_diff), (0, 0)],
                mode="constant",
                constant_values=0,
            )
            t_imp = np.pad(
                t_imp,
                (0, n_diff),
                mode="constant",
                constant_values=0,
            )
            t_components.append(t_component)
            t_importance.append(t_imp)
        t_dt = np.zeros(
            (new_doc_topic.shape[0], self.decomposition.n_components)
        )
        for i_new, joint_index in enumerate(self.merge_history_[1]):
            t_dt[:, joint_index] = new_doc_topic[:, i_new]
        new_imp, new_comp = self._fit_timebin(embeddings, t_dt)
        t_components.append(new_comp)
        t_importance.append(new_imp)
        self.axial_temporal_components_ = np.stack(t_components)
        self.temporal_importance_ = np.stack(t_importance)
    self.n_components_ = self.decomposition.n_components
    new_vectorizer = clone(self.vectorizer).fit(raw_documents)
    self.update_vocabulary(new_vectorizer)
    vocab_topic = self.decomposition.transform(self.vocab_embeddings)
    self.axial_components_ = vocab_topic.T
    self.estimate_components(self.feature_importance)
    return self.decomposition.transform(embeddings)

plot_components(hover_text=None, **kwargs)

Creates an interactive browser plot of the topics in your data using plotly.

Parameters:

Name Type Description Default
hover_text Optional[list[str]]

Text to show when hovering over a document.

None

Returns:

Type Description
plot

Interactive datamap plot, you can call the .show() method to display it in your default browser or save it as static HTML using .write_html().

Source code in turftopic/models/senstopic.py
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
def plot_components(
    self, hover_text: Optional[list[str]] = None, **kwargs
):
    """Creates an interactive browser plot of the topics in your data using plotly.

    Parameters
    ----------
    hover_text: list of str, optional
        Text to show when hovering over a document.

    Returns
    -------
    plot
        Interactive datamap plot, you can call the `.show()` method to
        display it in your default browser or save it as static HTML using `.write_html()`.
    """
    doc_topic = self.document_topic_matrix
    coords = TSNE(2, metric="cosine").fit_transform(doc_topic)
    labels = np.argmax(doc_topic, axis=1)
    topics_present = np.sort(np.unique(labels))
    names = [self.topic_names[i] for i in topics_present]
    if getattr(self, "topic_descriptions", None) is not None:
        desc = [self.topic_descriptions[i] for i in topics_present]
    else:
        desc = None
    all_words = self.get_top_words()
    keywords = [all_words[i] for i in topics_present]
    fig = build_datamapplot(
        coords,
        labels=labels,
        topic_names=names,
        top_words=keywords,
        hover_text=hover_text,
        topic_descriptions=desc,
        classes=topics_present,
        # Boundaries are unlikely to be very clear
        cluster_boundary_polygons=False,
    )
    return fig

plot_components_datamapplot(hover_text=None, **kwargs)

Creates an interactive browser plot of the topics in your data using datamapplot.

Parameters:

Name Type Description Default
hover_text Optional[list[str]]

Text to show when hovering over a document.

None

Returns:

Type Description
plot

Interactive datamap plot, you can call the .show() method to display it in your default browser or save it as static HTML using .write_html().

Source code in turftopic/models/senstopic.py
 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
def plot_components_datamapplot(
    self, hover_text: Optional[list[str]] = None, **kwargs
):
    """Creates an interactive browser plot of the topics in your data using datamapplot.

    Parameters
    ----------
    hover_text: list of str, optional
        Text to show when hovering over a document.

    Returns
    -------
    plot
        Interactive datamap plot, you can call the `.show()` method to
        display it in your default browser or save it as static HTML using `.write_html()`.
    """
    doc_topic = self.document_topic_matrix
    coords = TSNE(2, metric="cosine").fit_transform(doc_topic)
    labels = np.argmax(doc_topic, axis=1)
    topics_present = np.sort(np.unique(labels))
    names = [self.topic_names[i] for i in topics_present]
    if getattr(self, "topic_descriptions", None) is not None:
        desc = [self.topic_descriptions[i] for i in topics_present]
    else:
        desc = None
    all_words = self.get_top_words()
    keywords = [all_words[i] for i in topics_present]
    fig = build_datamapplot(
        coords,
        labels=labels,
        topic_names=names,
        top_words=keywords,
        hover_text=hover_text,
        topic_descriptions=desc,
        classes=topics_present,
        # Boundaries are unlikely to be very clear
        cluster_boundary_polygons=False,
    )
    return fig