prototorch_models/examples/liramlvq_tecator.py

49 lines
1.2 KiB
Python
Raw Normal View History

2021-05-07 13:25:04 +00:00
"""Limited Rank Matrix LVQ example using the Tecator dataset."""
2021-05-04 13:11:16 +00:00
2021-05-07 13:25:04 +00:00
import prototorch as pt
2021-05-04 13:11:16 +00:00
import pytorch_lightning as pl
2021-05-07 13:25:04 +00:00
import torch
2021-05-04 13:11:16 +00:00
if __name__ == "__main__":
# Dataset
2021-05-07 13:25:04 +00:00
train_ds = pt.datasets.Tecator(root="~/datasets/", train=True)
2021-05-04 13:11:16 +00:00
2021-05-07 13:25:04 +00:00
# Reproducibility
pl.utilities.seed.seed_everything(seed=42)
2021-05-04 13:11:16 +00:00
2021-05-07 13:25:04 +00:00
# Dataloaders
train_loader = torch.utils.data.DataLoader(train_ds,
num_workers=0,
batch_size=32)
2021-05-04 13:11:16 +00:00
# Hyperparameters
hparams = dict(
nclasses=2,
prototypes_per_class=2,
2021-05-07 13:25:04 +00:00
input_dim=100,
2021-05-04 13:11:16 +00:00
latent_dim=2,
2021-05-07 13:25:04 +00:00
prototype_initializer=pt.components.SMI(train_ds),
lr=0.001,
2021-05-04 13:11:16 +00:00
)
# Initialize the model
2021-05-07 13:25:04 +00:00
model = pt.models.GMLVQ(hparams)
2021-05-04 13:11:16 +00:00
# Callbacks
2021-05-07 13:25:04 +00:00
vis = pt.models.VisSiameseGLVQ2D(train_ds, border=0.1)
2021-05-04 13:11:16 +00:00
# Setup trainer
2021-05-07 13:25:04 +00:00
trainer = pl.Trainer(max_epochs=200, callbacks=[vis])
2021-05-04 13:11:16 +00:00
# Training loop
trainer.fit(model, train_loader)
2021-05-10 12:30:02 +00:00
# Save the model
torch.save(model, "liramlvq_tecator.pt")
# Load a saved model
saved_model = torch.load("liramlvq_tecator.pt")
# Display the Lambda matrix
saved_model.show_lambda()