Package: embedded-topic-model
Embedded Topic ModelThis package was made to easily run embedded topic modelling on a given corpus.ETM is a topic model that marries the probabilistic topic modelling of Latent Dirichlet Allocation with the
contextual information brought by word embeddings-most specifically, word2vec. ETM models topics as points
in the word embedding space, arranging together topics and words with similar context.
As such, ETM can either learn word embeddings alongside topics, or be given pretrained embeddings to discover
the topic patterns on the corpus.ETM was originally published by Adji B. Dieng, Francisco J. R. Ruiz, and David M. Blei on a article titled"Topic Modeling in Embedding Spaces"in 2019. This code is an adaptation of theoriginalprovided with the article and is not affiliated in any manner with the original authors. Most of the original code was kept here, with some changes here and there, mostly for ease of usage. This package was created to facilitate research purposes. If you want a more stable and feature-rich package to train ETM and other models, take a look atOCTIS.With the tools provided here, you can run ETM on your dataset using simple steps.Index:beer: Installation:wrench: Usage:microscope: Examples:books: Citation:heart: Contributing:v: Acknowledgements:pushpin: License:beer: InstallationYou can install the package usingpipby running:pip install -U embedded_topic_model:wrench: UsageTo use ETM on your corpus, you must first preprocess the documents into a format understandable by the model.
This package has a quick-use preprocessing script. The only requirement is that the corpus must be composed
by a list of strings, where each string corresponds to a document in the corpus.You can preprocess your corpus as follows:fromembedded_topic_model.utilsimportpreprocessingimportjson# Loading a dataset in JSON format. As said, documents must be composed by string sentencescorpus_file='datasets/example_dataset.json'documents_raw=json.load(open(corpus_file,'r'))documents=[document['body']fordocumentindocuments_raw]# Preprocessing the datasetvocabulary,train_dataset,_,=preprocessing.create_etm_datasets(documents,min_df=0.01,max_df=0.75,train_size=0.85,)Then, you can train word2vec embeddings to use with the ETM model. This is optional, and if you're not interested
on training your embeddings, you can either pass a pretrained word2vec embeddings file for ETM or learn the embeddings
using ETM itself. If you want ETM to learn its word embeddings, just passtrain_embeddings=Trueas an instance parameter.To pretrain the embeddings, you can do the following:fromembedded_topic_model.utilsimportembedding# Training word2vec embeddingsembeddings_mapping=embedding.create_word2vec_embedding_from_dataset(documents)To create and fit the model using the training data, execute:fromembedded_topic_model.models.etmimportETM# Training an ETM instanceetm_instance=ETM(vocabulary,embeddings=embeddings_mapping,# You can pass here the path to a word2vec file or# a KeyedVectors instancenum_topics=8,epochs=100,debug_mode=True,train_embeddings=False,# Optional. If True, ETM will learn word embeddings jointly with# topic embeddings. By default, is False. If 'embeddings' argument# is being passed, this argument must not be True)etm_instance.fit(train_dataset)You can get the topic words with this method. Note that you can select how many word per topic you're interest in:t_w_mtx=etm_instance.get_topics(top_n_words=20)You can get the topic word matrix with this method. Note that it will return all word for each topic:t_w_mtx=etm_instance.get_topic_word_matrix()You can get the topic word distribution matrix and the document topic distribution matrix with the following methods, both return a normalized distribution matrix:t_w_dist_mtx=etm_instance.get_topic_word_dist()d_t_dist_mtx=etm_instance.get_document_topic_dist()Also, to obtain topic coherence or topic diversity of the model, you can do as follows:topics=etm_instance.get_topics(20)topic_coherence=etm_instance.get_topic_coherence()topic_diversity=etm_instance.get_topic_diversity()You can also predict topics for unseen documents with the following.fromembedded_topic_model.utilsimportpreprocessingfromembedded_topic_model.models.etmimportETMcorpus_file='datasets/example_dataset.json'documents_raw=json.load(open(corpus_file,'r'))documents=[document['body']fordocumentindocuments_raw]# Splits into train/test datasetstrain=documents[:len(documents)-100]test=documents[len(documents)-100:]# Model fitting# ...# The vocabulary must be the same one created during preprocessing of the training dataset (see above)preprocessed_test=preprocessing.create_bow_dataset(test,vocabulary)# Transforms test dataset and returns normalized document topic distributiontest_d_t_dist=etm_instance.transform(preprocessed_test)print(f'test_d_t_dist:{test_d_t_dist}')For further details, seeexamples.:microscope: ExamplestitlelinkETM example - Reddit (r/depression) datasetJupyter Notebook:books: CitationTo cite ETM, use the original article's citation:@article{dieng2019topic,
    title = {Topic modeling in embedding spaces},
    author = {Dieng, Adji B and Ruiz, Francisco J R and Blei, David M},
    journal = {arXiv preprint arXiv: 1907.04907},
    year = {2019}
}:heart: ContributingContributions are always welcomed :heart:! You can take a look atto see some guidelines. Feel free to contact through issues, to elaborate on desired enhancements and to check if work is already being done on the matter.:v: AcknowledgementsCredits given to Adji B. Dieng, Francisco J. R. Ruiz, and David M. Blei for the original work.:pushpin: LicenseLicensed underMITlicense.ChangelogThis changelog was inspired by thekeep-a-changelogproject and followssemantic versioning.[1.2.1] - 2023-09-06Changed(#cf35c3) fixes minimum python version to bepython>=3.9[1.2.0] - 2023-09-06Added(#61730d,#224995,#331fc0) adds support for macOS MPS devices and updates outdatednumpy/sklearncode - thanks to@d-jiao(#c48016,#2fe517,#c965b1,#5578ca,#5b0d85) adds security guidelines and request templatesChanged(#331fc0) updates actions pipeline, supported python versions and internal dependencies to the latest available liketorch,gensim, among others. Support forpython<=3.8was dropped as a result. Numerous security vulnerabilities were solved[1.1.0] - 2023-09-05Added(#3f27ee) addstransformmethod(#f98f3f) adds example jupyter notebook(#683bec) adds contributing and conduct guidelinesChanged(#f98f3f,#c918a4) updates documentation[1.0.2] - 2021-06-23Changeddeactivates debug mode by defaultdocuments get_most_similar_words method[1.0.1] - 2021-02-15Changedoptimizes original word2vec TXT file input for model trainingupdates README.md[1.0.0] - 2021-02-15Addedadds support for original word2vec pretrained embeddings files on both formats (BIN/TXT)Changedoptimizes handling of gensim's word2vec mapping file for better memory usage[0.1.1] - 2021-02-01Addedsupport for python 3.6[0.1.0] - 2021-02-01AddedETM training with partially tested support for original ETM features.ETM corpus preprocessing scripts - including word2vec embeddings training - adapted from the original code.adds methods to retrieve document-topic and topic-word probability distributions from the trained model.adds docstrings for tested API methods.adds unit and integration tests for ETM and preprocessing scripts.