2021-11-15 08:57:44 +00:00
|
|
|
"""Localized-GTLVQ example using the Moons dataset."""
|
2021-11-10 17:04:24 +00:00
|
|
|
|
|
|
|
import argparse
|
2022-05-17 10:03:43 +00:00
|
|
|
import logging
|
|
|
|
import warnings
|
2021-11-10 17:04:24 +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 GTLVQ, VisGLVQ2D
|
|
|
|
from pytorch_lightning.callbacks import EarlyStopping
|
|
|
|
from pytorch_lightning.utilities.seed import seed_everything
|
|
|
|
from pytorch_lightning.utilities.warnings import PossibleUserWarning
|
|
|
|
from torch.utils.data import DataLoader
|
|
|
|
|
|
|
|
warnings.filterwarnings("ignore", category=PossibleUserWarning)
|
|
|
|
warnings.filterwarnings("ignore", category=UserWarning)
|
2021-11-10 17:04:24 +00:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
# Command-line arguments
|
|
|
|
parser = argparse.ArgumentParser()
|
|
|
|
parser = pl.Trainer.add_argparse_args(parser)
|
|
|
|
args = parser.parse_args()
|
|
|
|
|
|
|
|
# Reproducibility
|
2022-05-17 10:03:43 +00:00
|
|
|
seed_everything(seed=2)
|
2021-11-10 17:04:24 +00:00
|
|
|
|
|
|
|
# Dataset
|
|
|
|
train_ds = pt.datasets.Moons(num_samples=300, noise=0.2, seed=42)
|
|
|
|
|
|
|
|
# Dataloaders
|
2022-05-17 10:03:43 +00:00
|
|
|
train_loader = DataLoader(
|
|
|
|
train_ds,
|
|
|
|
batch_size=256,
|
|
|
|
shuffle=True,
|
|
|
|
)
|
2021-11-10 17:04:24 +00:00
|
|
|
|
|
|
|
# Hyperparameters
|
2021-11-15 08:50:33 +00:00
|
|
|
# Latent_dim should be lower than input dim.
|
|
|
|
hparams = dict(distribution=[1, 3], input_dim=2, latent_dim=1)
|
2021-11-10 17:04:24 +00:00
|
|
|
|
|
|
|
# Initialize the model
|
2022-05-17 10:03:43 +00:00
|
|
|
model = GTLVQ(hparams,
|
|
|
|
prototypes_initializer=pt.initializers.SMCI(train_ds))
|
2021-11-10 17:04:24 +00:00
|
|
|
|
|
|
|
# Compute intermediate input and output sizes
|
|
|
|
model.example_input_array = torch.zeros(4, 2)
|
|
|
|
|
|
|
|
# Summary
|
2022-05-17 10:03:43 +00:00
|
|
|
logging.info(model)
|
2021-11-10 17:04:24 +00:00
|
|
|
|
|
|
|
# Callbacks
|
2022-05-17 10:03:43 +00:00
|
|
|
vis = VisGLVQ2D(data=train_ds)
|
|
|
|
es = EarlyStopping(
|
2021-11-10 17:04:24 +00:00
|
|
|
monitor="train_acc",
|
|
|
|
min_delta=0.001,
|
|
|
|
patience=20,
|
|
|
|
mode="max",
|
|
|
|
verbose=False,
|
|
|
|
check_on_train_epoch_end=True,
|
|
|
|
)
|
|
|
|
|
|
|
|
# Setup trainer
|
|
|
|
trainer = pl.Trainer.from_argparse_args(
|
|
|
|
args,
|
|
|
|
callbacks=[
|
|
|
|
vis,
|
|
|
|
es,
|
|
|
|
],
|
2022-05-17 10:03:43 +00:00
|
|
|
max_epochs=1000,
|
|
|
|
log_every_n_steps=1,
|
|
|
|
detect_anomaly=True,
|
2021-11-10 17:04:24 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
# Training loop
|
|
|
|
trainer.fit(model, train_loader)
|