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:
- Configure: Define data columns, training hyperparameters, and model architecture.
- Initialize: Create a
TabularModel instance with the configs. - Fit: Call
.fit(train=..., validation=...) to train the model. - Evaluate: Call
.evaluate(test_df) to get performance metrics. - Predict: Call
.predict(test_df) to get a DataFrame of predictions. - 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")