2021-07-06 15:12:51 +00:00
|
|
|
"""Median-LVQ example using the Iris dataset."""
|
|
|
|
|
|
|
|
import argparse
|
2022-05-17 10:03:43 +00:00
|
|
|
import warnings
|
2021-07-06 15:12:51 +00:00
|
|
|
|
|
|
|
import prototorch as pt
|
|
|
|
import pytorch_lightning as pl
|
|
|
|
import torch
|
2023-06-20 15:30:21 +00:00
|
|
|
from lightning_fabric.utilities.seed import seed_everything
|
2022-05-17 10:03:43 +00:00
|
|
|
from prototorch.models import MedianLVQ, VisGLVQ2D
|
|
|
|
from pytorch_lightning.callbacks import EarlyStopping
|
|
|
|
from pytorch_lightning.utilities.warnings import PossibleUserWarning
|
|
|
|
from torch.utils.data import DataLoader
|
|
|
|
|
|
|
|
warnings.filterwarnings("ignore", category=PossibleUserWarning)
|
|
|
|
warnings.filterwarnings("ignore", category=UserWarning)
|
2021-07-06 15:12:51 +00:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2022-05-17 10:03:43 +00:00
|
|
|
# Reproducibility
|
|
|
|
seed_everything(seed=4)
|
2021-07-06 15:12:51 +00:00
|
|
|
# Command-line arguments
|
|
|
|
parser = argparse.ArgumentParser()
|
2023-06-20 15:30:21 +00:00
|
|
|
parser.add_argument("--gpus", type=int, default=0)
|
|
|
|
parser.add_argument("--fast_dev_run", type=bool, default=False)
|
2021-07-06 15:12:51 +00:00
|
|
|
args = parser.parse_args()
|
|
|
|
|
|
|
|
# Dataset
|
|
|
|
train_ds = pt.datasets.Iris(dims=[0, 2])
|
|
|
|
|
|
|
|
# Dataloaders
|
2022-05-17 10:03:43 +00:00
|
|
|
train_loader = DataLoader(
|
2021-07-06 15:12:51 +00:00
|
|
|
train_ds,
|
|
|
|
batch_size=len(train_ds), # MedianLVQ cannot handle mini-batches
|
|
|
|
)
|
|
|
|
|
|
|
|
# Initialize the model
|
2022-05-17 10:03:43 +00:00
|
|
|
model = MedianLVQ(
|
2021-07-06 15:12:51 +00:00
|
|
|
hparams=dict(distribution=(3, 2), lr=0.01),
|
|
|
|
prototypes_initializer=pt.initializers.SSCI(train_ds),
|
|
|
|
)
|
|
|
|
|
|
|
|
# Compute intermediate input and output sizes
|
|
|
|
model.example_input_array = torch.zeros(4, 2)
|
|
|
|
|
|
|
|
# Callbacks
|
2022-05-17 10:03:43 +00:00
|
|
|
vis = VisGLVQ2D(data=train_ds)
|
|
|
|
es = EarlyStopping(
|
2021-07-06 15:12:51 +00:00
|
|
|
monitor="train_acc",
|
|
|
|
min_delta=0.01,
|
|
|
|
patience=5,
|
|
|
|
mode="max",
|
|
|
|
verbose=True,
|
|
|
|
check_on_train_epoch_end=True,
|
|
|
|
)
|
|
|
|
|
|
|
|
# Setup trainer
|
2023-06-20 15:30:21 +00:00
|
|
|
trainer = pl.Trainer(
|
|
|
|
accelerator="cuda" if args.gpus else "cpu",
|
|
|
|
devices=args.gpus if args.gpus else "auto",
|
|
|
|
fast_dev_run=args.fast_dev_run,
|
2022-05-17 10:03:43 +00:00
|
|
|
callbacks=[
|
|
|
|
vis,
|
|
|
|
es,
|
|
|
|
],
|
|
|
|
max_epochs=1000,
|
|
|
|
log_every_n_steps=1,
|
|
|
|
detect_anomaly=True,
|
2021-07-06 15:12:51 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
# Training loop
|
|
|
|
trainer.fit(model, train_loader)
|