prototorch_models/examples/glvq_iris.py

56 lines
1.3 KiB
Python
Raw Normal View History

2021-04-21 12:54:07 +00:00
"""GLVQ example using the Iris dataset."""
2021-05-21 15:55:55 +00:00
import argparse
2021-06-04 13:55:06 +00:00
import prototorch as pt
2021-04-21 12:54:07 +00:00
import pytorch_lightning as pl
import torch
2021-06-04 13:55:06 +00:00
from torch.optim.lr_scheduler import ExponentialLR
2021-04-21 12:54:07 +00:00
if __name__ == "__main__":
2021-05-21 15:55:55 +00:00
# Command-line arguments
parser = argparse.ArgumentParser()
parser = pl.Trainer.add_argparse_args(parser)
args = parser.parse_args()
2021-04-21 13:52:42 +00:00
# Dataset
2021-05-30 22:52:16 +00:00
train_ds = pt.datasets.Iris(dims=[0, 2])
2021-04-21 13:52:42 +00:00
# Dataloaders
2021-05-30 22:52:16 +00:00
train_loader = torch.utils.data.DataLoader(train_ds, batch_size=64)
2021-04-21 12:54:07 +00:00
# Hyperparameters
hparams = dict(
2021-05-25 18:57:54 +00:00
distribution={
"num_classes": 3,
"per_class": 4
2021-05-25 18:57:54 +00:00
},
lr=0.01,
)
2021-04-21 19:35:52 +00:00
# Initialize the model
2021-06-04 13:55:06 +00:00
model = pt.models.GLVQ(
hparams,
optimizer=torch.optim.Adam,
prototypes_initializer=pt.initializers.SMCI(train_ds),
2021-06-04 13:55:06 +00:00
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, 2)
2021-05-07 13:25:04 +00:00
# Callbacks
2021-05-30 22:52:16 +00:00
vis = pt.models.VisGLVQ2D(data=train_ds)
2021-04-21 19:35:52 +00:00
# Setup trainer
2021-05-21 15:55:55 +00:00
trainer = pl.Trainer.from_argparse_args(
args,
2021-05-07 13:25:04 +00:00
callbacks=[vis],
2021-06-04 13:55:06 +00:00
weights_summary="full",
accelerator="ddp",
)
2021-04-21 12:54:07 +00:00
2021-04-21 13:52:42 +00:00
# Training loop
2021-04-21 12:54:07 +00:00
trainer.fit(model, train_loader)