OCTIS Documentation

repository·master·Indexed 21 days ago

https://github.com/mind-lab/octis

OCTIS is a framework for topic modeling that provides a comprehensive workflow including data preprocessing, model implementations (LDA, NMF, CTM, ETM), and evaluation metrics for coherence, diversity, classification, and topic significance. It features a Bayesian Optimization module for hyperparameter tuning and a local dashboard for creating, monitoring, and visualizing experiments.

Tokens
12K
Snippets
39
Records
58
Agent score
73%

What's inside OCTIS

  1. Overview of Octis Modules

    master

    Octis is organized into several functional modules that cover the end-to-end topic modeling workflow:

    • Dataset: Handles data loading and representation.
    • Data Preprocessing: Provides tools to clean and prepare text data for modeling.
    • Evaluation Measures: Contains various metrics to assess model quality, categorized into:
      • Coherence Metrics: Measuring topic semantic consistency.
      • Diversity Metrics: Measuring the variety of topics.
      • Classification Metrics: Evaluating topic performance via classification tasks.
      • Topic Significance Metrics: Assessing the importance of topics.
    • Optimization: Includes optimizers and tools to find optimal model hyperparameters.
    • Models: Implements various topic modeling algorithms including LDA, NMF, CTM, and ETM.
  2. Overview of ETM (Embedding Topic Model)

    master

    ETM (Embedding Topic Model) is a topic modeling approach that defines words and topics within the same embedding space. It is designed to be robust to large vocabularies containing rare words and stop words.

    In ETM, the likelihood of a word is modeled as a Categorical distribution where the natural parameter is the dot product between the word embedding and the embedding of its assigned topic. This allows the model to learn both interpretable topics and word embeddings simultaneously.

  3. Use Octis Models (LDA, NMF, CTM, ETM)

    master
    Octis provides several topic modeling implementations. You can use standard models like LDA (Latent Dirichlet Allocation), NMF_scikit (Non-negative Matrix Factorization via scikit-learn), or more advanced neural/probabilistic models like CTM (Correlated Topic Model) and ETM (Embedded Topic Model). The NFM model is also available.
  4. Optimize model hyperparameters with Octis

    master
    To find the best parameters for your topic models, use the optimization modules. This includes core optimizer logic and optimizer_tool utilities to automate the search for optimal model configurations.
  5. Use the EarlyStopping class to prevent overfitting

    master

    The EarlyStopping class in pytorchtool.py is a regularization tool designed to prevent overfitting in PyTorch models. It monitors validation loss during training and terminates the training loop if the loss fails to decrease for a specified number of epochs.

    Key features:

    • Validation Monitoring: Tracks validation loss across epochs.
    • Checkpointing: Automatically saves a model checkpoint whenever the validation loss decreases.
    • Patience Control: The patience argument determines how many consecutive epochs to wait for an improvement in validation loss before stopping the training.

    To use it, instantiate the class and call its methods within your training loop to evaluate the loss and decide whether to continue or stop.

    # Conceptual usage pattern
    # (Refer to MNIST_Early_Stopping_example.ipynb for a full implementation)
    from octis.models.early_stopping.pytorchtool import EarlyStopping
    
    # patience: number of epochs to wait after last improvement
    esp = EarlyStopping(patience=20)
    
    # Inside training loop:
    # esp.check(validation_loss, model)
  6. OCTIS Dashboard terminology

    master

    Understanding these core concepts is essential for using the dashboard effectively:

    • Batch: A set of related experiments grouped together by a common batch name.
    • Model runs: In optimization, because evaluation metrics can be noisy, the objective function is calculated as the median of a specified number of model runs (multiple runs of a topic model using the same hyperparameter configuration).
  7. Evaluate topic models with Octis metrics

    master

    Octis provides a comprehensive suite of evaluation metrics to assess the quality of your topic models. Depending on your goal, you can use:

    • Coherence Metrics (octis.evaluation_metrics.coherence_metrics)
    • Diversity Metrics (octis.evaluation_metrics.diversity_metrics)
    • Classification Metrics (octis.evaluation_metrics.classification_metrics)
    • Topic Significance Metrics (octis.evaluation_metrics.topic_significance_metrics)
  8. How to implement a custom model

    master

    To add a new model to OCTIS, your class must inherit from AbstractModel (defined in octis/models/model.py).

    Implementation Steps

    1. Define Hyperparameters: Create a dictionary of default hyperparameter values. This allows users to override only specific parameters.
    2. Override train_model: Implement the train_model(self, dataset, hyperparameters={}, top_words=10) method.

    Required Return Format

    The train_model method must return a dictionary containing at least:

    • topics: A list of lists of strings (the most significant words for each topic).
    • topic-word-matrix: An $N imes V$ matrix of weights ($N$ = topics, $V$ = vocabulary length).
    • topic-document-matrix: An $N imes D$ matrix of weights ($N$ = topics, $D$ = number of documents).

    If your model supports training/test partitioning, you should also return:

    • test-topic-document-matrix: The document-topic matrix for the test set.
    # Example hyperparameter definition
    hyperparameters = {
        'corpus': None, 
        'num_topics': 100, 
        'id2word': None, 
        'alpha': 'symmetric', 
        'eta': None, 
        'callbacks': None
    }
    
    # Example method signature to override
    def train_model(self, dataset, hyperparameters={}, top_words=10):
        # ... implementation ...
        return {
            'topics': list_of_lists, 
            'topic-word-matrix': matrix_nv, 
            'topic-document-matrix': matrix_nd
        }
  9. Perform Hyperparameter Optimization

    master

    To optimize a topic model, you must provide a dataset, an evaluation metric, and a search space defined using scikit-optimize types. The Optimizer class handles the optimization process.

    Optimization Workflow

    1. Define Search Space: Use skopt.space.space types (like Real) to define the range for hyperparameters. Refer to the specific topic model's initialization signature to identify which hyperparameters are available.
    2. Initialize Optimizer: Create an instance of octis.optimization.optimizer.Optimizer.
    3. Run Optimization: Call .optimize() with your model, dataset, metric, and search space.
    4. Save Results: Use .save_to_csv() on the resulting object to persist the optimization history.

    Visualization

    To visualize the optimization process, set the plot attribute of the Bayesian_optimization object to True.

    from octis.optimization.optimizer import Optimizer
    from skopt.space.space import Real
    
    # Define the search space using scikit-optimize types
    search_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 results
        number_of_call=30,       # number of optimization iterations
        model_runs=5             # number of runs of the topic model
    )
    
    # Save the results of the optimization in a csv file
    optResult.save_to_csv("results.csv")
  10. Train a topic model with `train_model()`

    master

    To train a topic model in OCTIS, you need to load a preprocessed Dataset, initialize a model class (e.g., LDA) with specific hyperparameters, and call the train_model() method.

    If your dataset is partitioned, you can choose to:

    • Train on the training set and evaluate on the test documents.
    • Train on the entire dataset, ignoring partitions.

    The train_model() method returns a dictionary containing the model's output (e.g., topics, matrices).

    from octis.dataset.dataset import Dataset
    from octis.models.LDA import LDA
    
    # Load a dataset
    dataset = Dataset()
    dataset.load_custom_dataset_from_folder("dataset_folder")
    
    model = LDA(num_topics=25)  # Create model
    model_output = model.train_model(dataset) # Train the model