2021-09-01 08:49:57 +00:00
|
|
|
"""GMLVQ example using the Iris dataset."""
|
|
|
|
|
|
|
|
import argparse
|
2022-05-17 10:03:43 +00:00
|
|
|
import warnings
|
2021-09-01 08:49:57 +00:00
|
|
|
|
|
|
|
import prototorch as pt
|
|
|
|
import pytorch_lightning as pl
|
|
|
|
import torch
|
2022-05-17 10:03:43 +00:00
|
|
|
from prototorch.models import GMLVQ, VisGMLVQ2D
|
|
|
|
from pytorch_lightning.utilities.seed import seed_everything
|
|
|
|
from pytorch_lightning.utilities.warnings import PossibleUserWarning
|
2021-09-01 08:49:57 +00:00
|
|
|
from torch.optim.lr_scheduler import ExponentialLR
|
2022-05-17 10:03:43 +00:00
|
|
|
from torch.utils.data import DataLoader
|
|
|
|
|
|
|
|
warnings.filterwarnings("ignore", category=PossibleUserWarning)
|
|
|
|
warnings.filterwarnings("ignore", category=UserWarning)
|
2021-09-01 08:49:57 +00:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2022-05-17 10:03:43 +00:00
|
|
|
|
|
|
|
# Reproducibility
|
|
|
|
seed_everything(seed=4)
|
|
|
|
|
2021-09-01 08:49:57 +00:00
|
|
|
# Command-line arguments
|
|
|
|
parser = argparse.ArgumentParser()
|
|
|
|
parser = pl.Trainer.add_argparse_args(parser)
|
|
|
|
args = parser.parse_args()
|
|
|
|
|
|
|
|
# Dataset
|
|
|
|
train_ds = pt.datasets.Iris()
|
|
|
|
|
|
|
|
# Dataloaders
|
2022-05-17 10:03:43 +00:00
|
|
|
train_loader = DataLoader(train_ds, batch_size=64)
|
2021-09-01 08:49:57 +00:00
|
|
|
|
|
|
|
# Hyperparameters
|
|
|
|
hparams = dict(
|
|
|
|
input_dim=4,
|
|
|
|
latent_dim=4,
|
|
|
|
distribution={
|
|
|
|
"num_classes": 3,
|
|
|
|
"per_class": 2
|
|
|
|
},
|
|
|
|
proto_lr=0.01,
|
|
|
|
bb_lr=0.01,
|
|
|
|
)
|
|
|
|
|
|
|
|
# Initialize the model
|
2022-05-17 10:03:43 +00:00
|
|
|
model = GMLVQ(
|
2021-09-01 08:49:57 +00:00
|
|
|
hparams,
|
|
|
|
optimizer=torch.optim.Adam,
|
|
|
|
prototypes_initializer=pt.initializers.SMCI(train_ds),
|
|
|
|
lr_scheduler=ExponentialLR,
|
|
|
|
lr_scheduler_kwargs=dict(gamma=0.99, verbose=False),
|
|
|
|
)
|
|
|
|
|
|
|
|
# Compute intermediate input and output sizes
|
|
|
|
model.example_input_array = torch.zeros(4, 4)
|
|
|
|
|
|
|
|
# Callbacks
|
2022-05-17 10:03:43 +00:00
|
|
|
vis = VisGMLVQ2D(data=train_ds)
|
2021-09-01 08:49:57 +00:00
|
|
|
|
|
|
|
# Setup trainer
|
|
|
|
trainer = pl.Trainer.from_argparse_args(
|
|
|
|
args,
|
2022-05-17 10:03:43 +00:00
|
|
|
callbacks=[
|
|
|
|
vis,
|
|
|
|
],
|
|
|
|
max_epochs=100,
|
|
|
|
log_every_n_steps=1,
|
|
|
|
detect_anomaly=True,
|
2021-09-01 08:49:57 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
# Training loop
|
|
|
|
trainer.fit(model, train_loader)
|