PyTorch Tabular Documentation

repository·main·Indexed 23 days ago

https://github.com/pytorch-tabular/pytorch_tabular

A high-level framework for deep learning on tabular data, providing a unified interface and leveraging PyTorch Lightning for scalable training. Version 1.2.0 supports various architectures including TabNet, NODE, FT Transformer, TabTransformer, AutoInt, and GANDALF, as well as semi-supervised learning via Denoising AutoEncoders. The library includes core classes like TabularModel for training, TabularDatamodule for data management, and TabularModelTuner for hyperparameter optimization.

Tokens
46K
Snippets
76
Records
194
Agent score
79%

What's inside PyTorch Tabular

  1. Overview of PyTorch Tabular

    main

    PyTorch Tabular is a library designed to simplify applying deep learning techniques to tabular data (structured data like spreadsheets or databases). It is built on top of PyTorch, PyTorch Lightning, and pandas to provide a low-resistance, highly customizable, and scalable workflow for both research and production environments.

    Key features include:

    • Easy Customization: Tailor models and pipelines to specific requirements.
    • Scalable Tooling: Designed for efficient deployment in production.
    • Integration: Leverages the Pythonic nature of PyTorch, the training simplicity of PyTorch Lightning, and the data manipulation strengths of pandas.
  2. Configure model heads with Head Configuration classes

    main

    Beyond core pipeline configurations, PyTorch Tabular provides specific configuration classes for different model 'heads' (the final layers of a model that produce the specific output type).

    Available head configurations include:

    • pytorch_tabular.models.common.heads.LinearHeadConfig: For standard linear output heads.
    • pytorch_tabular.models.common.heads.MixtureDensityHeadConfig: For heads that output parameters of a mixture density network (often used for probabilistic regression).
  3. Apply feature transformations to continuous columns

    main

    PyTorch Tabular provides several methods to transform continuous features to improve model performance. By default, normalize_continuous_features is set to True, which scales features using a StandardScaler.

    You can further refine feature distributions using the continuous_feature_transform parameter with the following options:

    Parametric Transformations (Gaussian mapping)

    These aim to map data to a Gaussian distribution to stabilize variance and minimize skewness:

    • yeo-johnson: Works for any distribution.
    • box-cox: Can only be applied to strictly positive data.

    Non-parametric Transformations (Rank-based)

    These use rank transformations to smooth distributions and are less sensitive to outliers, though they may distort correlations:

    • quantile_normal: Transforms features to a normal distribution.
    • quantile_uniform: Transforms features to a uniform distribution.
  4. Core Configuration classes in PyTorch Tabular

    main

    PyTorch Tabular uses several specialized configuration classes to manage different stages of the machine learning pipeline. These classes allow you to define settings for data processing, model architecture, training logic, and experiment management.

    The core configuration classes are:

    • pytorch_tabular.config.DataConfig: Manages data loading, preprocessing, and feature engineering settings.
    • pytorch_tabular.config.ModelConfig: Defines the base architecture and parameters for the tabular models.
    • pytorch_tabular.config.SSLModelConfig: Configuration specifically for Self-Supervised Learning (SSL) models.
    • pytorch_tabular.config.TrainerConfig: Controls the training loop, including epochs, batch size, and device settings.
    • pytorch_tabular.config.ExperimentConfig: Manages high-level experiment settings and reproducibility.
    • pytorch_tabular.config.OptimizerConfig: Configures the optimization algorithm (e.g., learning rate, weight decay).
    • pytorch_tabular.config.ExperimentRunManager: Handles the management and logging of individual experiment runs.
  5. Available Deep Learning Models in PyTorch Tabular

    main

    PyTorch Tabular supports a wide variety of architectures for classification, regression, and semi-supervised learning:

    Standard Architectures

    • FeedForward Network with Category Embedding: A simple FF network using embedding layers for categorical columns.
    • Neural Oblivious Decision Ensembles (NODE): A model designed to compete with Gradient Boosting models.
    • TabNet: Uses Sparse Attention to model outputs through multiple decision-making steps.
    • Mixture Density Networks: A regression model providing probabilistic predictions via Gaussian components.
    • AutoInt: Learns feature interactions automatically using self-attentive neural networks.
    • TabTransformer: Adapts the Transformer model to create contextual representations for categorical features.
    • FT Transformer: A Transformer-based architecture for tabular data.
    • Gated Additive Tree Ensemble (GATE): Uses a gating mechanism and an ensemble of differentiable, non-linear decision trees.
    • GANDALF: A more efficient, pared-down version of GATE.
    • DANETs: Uses Abstract Layers (AbstLay) to group correlative features and generate higher-level semantic abstractions.

    Semi-Supervised Learning

    • Denoising AutoEncoder: Learns robust feature representations to compensate for noise in datasets.
  6. Use Model Stacking for Ensemble Learning

    main

    Model stacking is an ensemble technique that combines multiple base models to create a more powerful predictive model. Each base model processes input features independently, and their outputs are concatenated before the final prediction. This allows the model to leverage different learning patterns from various backbone architectures.

    To use stacking, choose StackingModelConfig and provide a list of base model configurations.

    Supported architectures for stacking:

    • Category Embedding Model
    • TabNet Model
    • FTTransformer Model
    • Gated Additive Tree Ensemble Model
    • DANet Model
    • AutoInt Model
    • GANDALF Model
    • Node Model

    Configuration parameter:

    • model_configs: List[ModelConfig] — A list of configurations for each base model. Each entry must be a valid PyTorch Tabular model config (e.g., NodeConfig, GANDALFConfig).
  7. How PyTorch Tabular models are structured

    main

    In PyTorch Tabular, every model is composed of three distinct functional components that work together to process data and produce predictions:

    1. Embedding Layer: Processes categorical and continuous features into a single unified tensor.
    2. Backbone: The core architecture that performs representation learning on the output of the embedding layer, producing a tensor of learned features.
    3. Head: Takes the backbone's output and performs the final classification or regression to produce the final prediction.

    You can customize these components and their specific parameters using model-specific configuration classes.

  8. How Self-Supervised Learning works

    main

    Self-supervised learning follows a specific three-step lifecycle in PyTorch Tabular:

    1. Pretraining: Use TabularModel.pretrain() to train on data. Note that the input DataFrames do not need a target column; even if a target is defined in DataConfig, it will be ignored during this phase.
    2. Creating a Finetune Model: Use TabularModel.create_finetune_model() to create a new TabularModel instance initialized with the weights from your pretrained model.
    3. Finetuning: Use TabularModel.finetune() on the model created in step 2. Unlike pretraining, the DataFrames passed to finetune must contain the target column.
  9. How Self-Supervised Learning (SSL) works in PyTorch Tabular

    main

    Self-Supervised Learning (SSL) in PyTorch Tabular follows an encoder-decoder architecture designed to build background knowledge from unlabeled data before fine-tuning on labeled data.

    The Workflow

    1. Pre-training: Train the model on a large unlabeled dataset to learn feature representations.
    2. Fine-tuning: Use the pre-trained model as a backbone for a downstream task (e.g., regression or classification) and train on a smaller labeled dataset.

    Model Components

    • Embedding Layer: Processes categorical and continuous features into a single tensor.
    • Featurizer: Performs representation learning on the embedding layer output to produce learned features.
    • Encoder: Compulsory component that learns the representation.
    • Decoder: Optional component (defaults to nn.Identity) used to transform the intermediate representation back into a reconstruction (e.g., in Denoising AutoEncoders).

    Implementation Requirements

    To implement a custom SSL model, you must inherit from SSLBaseModel and implement the following methods:

    • embedding_layer (property)
    • featurizer (property)
    • _setup_loss (sets up the loss function)
    • _setup_metrics (sets up metrics)
    • calculate_loss (calculates loss)
    • calculate_metrics (calculates metrics)
    • forward (defines the forward pass)
    • featurize (returns learned features from the featurizer)
  10. How the Supervised Learning APIs work

    main

    PyTorch Tabular provides two ways to train models:

    1. High-Level API: Uses the .fit() and .cross_validate() methods. This is the recommended approach for most users as it abstracts the complexity of the training loop.
    2. Low-Level API: Provides more granular control by splitting the process into three distinct steps. This is useful for implementing custom logic like ensembling or complex cross-validation.

    Low-Level API Workflow:

    1. prepare_dataloader: Sets up the TabularDataModule. You can use save_datamodule and load_datamodule to reuse this step.
    2. prepare_model: Takes the datamodule and initializes the model instance.
    3. train: Takes the datamodule and model to perform the actual training loop.
  11. Basic usage of PyTorch Tabular for training and prediction

    main

    You can use PyTorch Tabular to train a model, evaluate it on a test set, generate predictions, and manage model persistence (save/load). The workflow involves defining four configuration objects: DataConfig, TrainerConfig, OptimizerConfig, and a specific model configuration (e.g., CategoryEmbeddingModelConfig), then passing them to the TabularModel class.

    Key steps in the lifecycle:

    1. Configure: Define data columns, training hyperparameters, and model architecture.
    2. Initialize: Create a TabularModel instance with the configs.
    3. Fit: Call .fit(train=..., validation=...) to train the model.
    4. Evaluate: Call .evaluate(test_df) to get performance metrics.
    5. Predict: Call .predict(test_df) to get a DataFrame of predictions.
    6. Persist: Use .save_model(path) and TabularModel.load_model(path) to save and restore models.
    from pytorch_tabular import TabularModel
    from pytorch_tabular.models import CategoryEmbeddingModelConfig
    from pytorch_tabular.config import (
        DataConfig,
        OptimizerConfig,
        TrainerConfig,
    )
    
    data_config = DataConfig(
        target=[
            "target"
        ],  # target should always be a list.
        continuous_cols=num_col_names,
        categorical_cols=cat_col_names,
    )
    trainer_config = TrainerConfig(
        auto_lr_find=True,  # Runs the LRFinder to automatically derive a learning rate
        batch_size=1024,
        max_epochs=100,
    )
    optimizer_config = OptimizerConfig()
    
    model_config = CategoryEmbeddingModelConfig(
        task="classification",
        layers="1024-512-512",  # Number of nodes in each layer
        activation="LeakyReLU",  # Activation between each layers
        learning_rate=1e-3,
    )
    
    tabular_model = TabularModel(
        data_config=data_config,
        model_config=model_config,
        optimizer_config=optimizer_config,
        trainer_config=trainer_config,
    )
    tabular_model.fit(train=train, validation=val)
    result = tabular_model.evaluate(test)
    pred_df = tabular_model.predict(test)
    tabular_model.save_model("examples/basic")
    loaded_model = TabularModel.load_model("examples/basic")
  12. Use target_range for regression tasks

    main

    For regression problems, you can provide a target_range to help the model learn the bounds of the output variable. This is often more effective than forcing the model to learn the bounds from scratch.

    • For a single target: Provide a tuple (min, max).
    • For multi-target regression: Provide a list of tuples, where each tuple corresponds to a target.

    Note: This parameter is ignored for classification tasks.

    Example for a single target:

    target_range = [(train[target].min() * 0.8, train[target].max() * 1.2)]