Package: octis
OCTIS (Optimizing and Comparing Topic models Is Simple)aims at training, analyzing and comparing
Topic Models, whose optimal hyperparameters are estimated by means of a Bayesian Optimization approach. This work has been accepted to the demo track of EACL2021.Click to read the paper!Table of ContentsInstallMain FeaturesExamples and TutorialsSome tutorials on Medium:Datasets and PreprocessingLoad a preprocessed datasetAvailable DatasetsLoad a Custom DatasetPreprocess a DatasetTopic Models and EvaluationTrain a modelAvailable ModelsEvaluate a modelAvailable metricsImplement your own ModelHyperparameter OptimizationDashboardHow to cite our workTeamProject and Development LeadCurrent ContributorsPast ContributorsCreditsInstallYou can install OCTIS with the following command:pip install octisYou can find the requirements in therequirements.txtfile.Main FeaturesPreprocess your own dataset or use one of the already-preprocessed benchmark datasetsWell-known topic models (both classical and neurals)Evaluate your model using different state-of-the-art evaluation metricsOptimize the models’ hyperparameters for a given metric using Bayesian OptimizationPython library for advanced usage or simple web dashboard for starting and controlling the optimization experimentsExamples and TutorialsTo easily understand how to use OCTIS, we invite you to try our tutorials out :)NameLinkHow to build a topic model and evaluate the results (LDA on 20Newsgroups)How to optimize the hyperparameters of a neural topic model (CTM on M10)Some tutorials on Medium:Two guides on how to use OCTIS with practical examples:A beginner’s guide to OCTIS vol. 1byEmil RijckenA beginner’s guide to OCTIS vol. 2byEmil RijckenA tutorial on topic modeling on song lyrics:OCTIS - The Future of Topic ModelingbyNicolas PogeantDatasets and PreprocessingLoad a preprocessed datasetTo load one of the already preprocessed datasets as follows:fromoctis.dataset.datasetimportDatasetdataset=Dataset()dataset.fetch_dataset("20NewsGroup")Just use one of the dataset names listed below. Note: it is case-sensitive!Available DatasetsName in OCTISSource# Docs# Words# LabelsLanguage20NewsGroup20Newsgroup16309161220EnglishBBC_NewsBBC-News222529495EnglishDBLPDBLP5459515134EnglishM10M108355169610EnglishDBPedia_ITDBPedia_IT425120475ItalianEuroparl_ITEuroparl_IT36132000NAItalianLoad a Custom DatasetOtherwise, you can load a custom preprocessed dataset in the following way:fromoctis.dataset.datasetimportDatasetdataset=Dataset()dataset.load_custom_dataset_from_folder("../path/to/the/dataset/folder")Make sure that the dataset is in the following format:corpus file: a .tsv file (tab-separated) that contains up to three columns, i.e. the document, the partitition, and the label associated to the document (optional).vocabulary: a .txt file where each line represents a word of the vocabularyThe partition can be “train” for the training partition, “test” for testing partition, or “val” for the validation partition. An example of dataset can be found here:sample_dataset.DisclaimerSimilarly toTensorFlow Datasetsand HuggingFace’snlplibrary, we just downloaded and prepared public datasets. We do not host or distribute these datasets, vouch for their quality or fairness, or claim that you have license to use the dataset. It is your responsibility to determine whether you have permission to use the dataset under the dataset’s license and to cite the right owner of the dataset.If you’re a dataset owner and wish to update any part of it, or do not want your dataset to be included in this library, please get in touch through a GitHub issue.If you’re a dataset owner and wish to include your dataset in this library, please get in touch through a GitHub issue.Preprocess a DatasetTo preprocess a dataset, import the preprocessing class and use the preprocess_dataset method.importosimportstringfromoctis.preprocessing.preprocessingimportPreprocessingos.chdir(os.path.pardir)# Initialize preprocessingpreprocessor=Preprocessing(vocabulary=None,max_features=None,remove_punctuation=True,punctuation=string.punctuation,lemmatize=True,stopword_list='english',min_chars=1,min_words_docs=0)# preprocessdataset=preprocessor.preprocess_dataset(documents_path=r'..\corpus.txt',labels_path=r'..\labels.txt')# save the preprocessed datasetdataset.save('hello_dataset')For more details on the preprocessing see the preprocessing demo example in the examples folder.Topic Models and EvaluationTrain a modelTo build a model, load a preprocessed dataset, set the model hyperparameters and usetrain_model()to train the model.fromoctis.dataset.datasetimportDatasetfromoctis.models.LDAimportLDA# Load a datasetdataset=Dataset()dataset.load_custom_dataset_from_folder("dataset_folder")model=LDA(num_topics=25)# Create modelmodel_output=model.train_model(dataset)# Train the modelIf the dataset is partitioned, you can:Train the model on the training set and test it on the test documentsTrain the model with the whole dataset, regardless of any partition.Available ModelsNameImplementationCTM(Bianchi et al. 2021)https://github.com/MilaNLProc/contextualized-topic-modelsETM(Dieng et al. 2020)https://github.com/adjidieng/ETMHDP(Blei et al. 2004)https://radimrehurek.com/gensim/LDA(Blei et al. 2003)https://radimrehurek.com/gensim/LSI(Landauer et al. 1998)https://radimrehurek.com/gensim/NMF(Lee and Seung 2000)https://radimrehurek.com/gensim/NeuralLDA(Srivastava and Sutton 2017)https://github.com/estebandito22/PyTorchAVITMProdLda(Srivastava and Sutton 2017)https://github.com/estebandito22/PyTorchAVITMIf you use one of these implementations, make sure to cite the right paper.If you implemented a model and wish to update any part of it, or do not want your model to be included in this library, please get in touch through a GitHub issue.If you implemented a model and wish to include your model in this library, please get in touch through a GitHub issue. Otherwise, if you want to include the model by yourself, see the following section.Evaluate a modelTo evaluate a model, choose a metric and use thescore()method of the metric class.fromoctis.evaluation_metrics.diversity_metricsimportTopicDiversitymetric=TopicDiversity(topk=10)# Initialize metrictopic_diversity_score=metric.score(model_output)# Compute score of the metricAvailable metricsClassification Metrics:F1-score:F1Score(dataset)Precision:PrecisionScore(dataset)Recall:RecallScore(dataset)Accuracy:AccuracyScore(dataset)Coherence Metrics:UMass Coherence:Coherence(measure='u_mass')C_V Coherence:Coherence(measure='c_v')UCI Coherence:Coherence(measure='c_uci')NPMI Coherence:Coherence(measure='c_npmi')Word Embedding-based Coherence Pairwise:WECoherencePairwise()Word Embedding-based Coherence Centroid:WECoherenceCentroid()Diversity Metrics:Topic Diversity:TopicDiversity()InvertedRBO:InvertedRBO()Word Embedding-based InvertedRBO Matches:WordEmbeddingsInvertedRBO()Word Embedding-based InvertedRBO Centroid:WordEmbeddingsInvertedRBOCentroid()Log odds ratio:LogOddsRatio()Kullback-Liebler Divergence:KLDivergence()Similarity Metrics:Ranked-Biased Overlap:RBO()Word Embedding-based RBO Matches:WordEmbeddingsRBOMatch()Word Embedding-based RBO Centroid:WordEmbeddingsRBOCentroid()Word Embeddings-based Pairwise Similarity:WordEmbeddingsPairwiseSimilarity()Word Embeddings-based Centroid Similarity:WordEmbeddingsCentroidSimilarity()Word Embeddings-based Weighted Sum Similarity:WordEmbeddingsWeightedSumSimilarity()Pairwise Jaccard Similarity:PairwiseJaccardSimilarity()Topic significance Metrics:KL Uniform:KL_uniform()KL Vacuous:KL_vacuous()KL Background:KL_background()Implement your own ModelModels inherit from the classAbstractModeldefined inoctis/models/model.py.
To build your own model your class must override thetrain_model(self, dataset, hyperparameters)method which always requires at least aDatasetobject and aDictionaryof hyperparameters as input and should return a dictionary with the output of the model as output.To better understand how a model work, let’s have a look at the LDA implementation.
The first step in developing a custom model is to define the dictionary of default hyperparameters values:hyperparameters={'corpus':None,'num_topics':100,'id2word':None,'alpha':'symmetric','eta':None,# ...'callbacks':None}Defining the default hyperparameters values allows users to work on a subset of them without having to assign a value to each parameter.The following step is thetrain_model()override:deftrain_model(self,dataset,hyperparameters={},top_words=10):The LDA method requires a dataset, the hyperparameters dictionary and an extra (optional) argument used to select how many of the most significative words track for each topic.With the hyperparameters defaults, the ones in input and the dataset you should be able to write your own code and return as output a dictionary with at least 3 entries:topics: the list of the most significative words foreach topic (list of lists of strings).topic-word-matrix: an NxV matrix of weights where N is the number of topics and V is the vocabulary length.topic-document-matrix: an NxD matrix of weights where N is the number of topics and D is the number of documents in the corpus.if your model supports the training/test partitioning it should also return:test-topic-document-matrix: the document topic matrix of the test set.Hyperparameter OptimizationTo optimize a model you need to select a dataset, a metric and the search space of the hyperparameters to optimize.
For the types of the hyperparameters, we usescikit-optimizetypes (https://scikit-optimize.github.io/stable/modules/space.html)fromoctis.optimization.optimizerimportOptimizerfromskopt.space.spaceimportReal# Define the search space. To see which hyperparameters to optimize, see the topic model's initialization signaturesearch_space={"alpha":Real(low=0.001,high=5.0),"eta":Real(low=0.001,high=5.0)}# Initialize an optimizer object and start the optimization.optimizer=Optimizer()optResult=optimizer.optimize(model,dataset,eval_metric,search_space,save_path="../results"# path to store the resultsnumber_of_call=30,# number of optimization iterationsmodel_runs=5)# number of runs of the topic model#save the results of th optimization in a csv fileoptResult.save_to_csv("results.csv")The result will provide best-seen value of the metric with the corresponding hyperparameter configuration, and the hyperparameters and metric value for each iteration of the optimization. To visualize this information, you have to set ‘plot’ attribute of Bayesian_optimization to True.You can find more here:optimizer READMEDashboardOCTIS includes a user friendly graphical interface for creating, monitoring and viewing experiments.
Following the implementation standards of datasets, models and metrics the dashboard will automatically update and allow you to use your own custom implementations.To run rhe dashboard you need to clone the repo.
While in the project directory run the following command:pythonOCTIS/dashboard/server.pyThe browser will open and you will be redirected to the dashboard.
In the dashboard you can:Create new experiments organized in batchVisualize and compare all the experimentsVisualize a custom experimentManage the experiment queueHow to cite our workThis work has been accepted at the demo track of EACL 2021!Click to read the paper!
If you decide to use this resource, please cite:@inproceedings{terragni2020octis,
    title={{OCTIS}: Comparing and Optimizing Topic Models is Simple!},
    author={Terragni, Silvia and Fersini, Elisabetta and Galuzzi, Bruno Giovanni and Tropeano, Pietro and Candelieri, Antonio},
    year={2021},
    booktitle={Proceedings of the 16th Conference of the European Chapter of the Association for Computational Linguistics: System Demonstrations},
    month = apr,
    year = "2021",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/2021.eacl-demos.31",
    pages = "263--270",
}

@inproceedings{DBLP:conf/clic-it/TerragniF21,
  author    = {Silvia Terragni and Elisabetta Fersini},
  editor    = {Elisabetta Fersini and Marco Passarotti and Viviana Patti},
  title     = {{OCTIS 2.0: Optimizing and Comparing Topic Models in Italian Is Even
               Simpler!}},
  booktitle = {Proceedings of the Eighth Italian Conference on Computational Linguistics,
               CLiC-it 2021, Milan, Italy, January 26-28, 2022},
  series    = {{CEUR} Workshop Proceedings},
  volume    = {3033},
  publisher = {CEUR-WS.org},
  year      = {2021},
  url       = {http://ceur-ws.org/Vol-3033/paper55.pdf},
}TeamProject and Development LeadSilvia Terragni<s.terragni4@campus.unimib.it>Elisabetta Fersini <elisabetta.fersini@unimib.it>Antonio Candelieri <antonio.candelieri@unimib.it>Current ContributorsPietro Tropeano <p.tropeano1@campus.unimib.it> Framework architecture, Preprocessing, Topic Models, Evaluation metrics and Web DashboardBruno Galuzzi <bruno.galuzzi@unimib.it> Bayesian OptimizationSilvia Terragni <s.terragni4@campus.unimib.it> Overall projectPast ContributorsLorenzo Famiglini <l.famiglini@campus.unimib.it> Neural models integrationDavide Pietrasanta <d.pietrasanta@campus.unimib.it> Bayesian OptimizationCreditsThis package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template. Thanks to all the developers that released their topic models’ implementations. A special thanks goes totenggaardwho helped us find many bugs in early octis releases and toEmil Rijckenwho kindly wrote two guides on how to use OCTIS :)