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-05-07 13:25:04 +00:00
|
|
|
import prototorch as pt
|
2021-04-21 12:54:07 +00:00
|
|
|
import pytorch_lightning as pl
|
|
|
|
import torch
|
2021-05-21 15:55:55 +00:00
|
|
|
from sklearn.datasets import load_iris
|
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-04-21 12:54:07 +00:00
|
|
|
x_train, y_train = load_iris(return_X_y=True)
|
|
|
|
x_train = x_train[:, [0, 2]]
|
2021-05-07 13:25:04 +00:00
|
|
|
train_ds = pt.datasets.NumpyDataset(x_train, y_train)
|
2021-04-21 13:52:42 +00:00
|
|
|
|
|
|
|
# Dataloaders
|
2021-05-07 13:25:04 +00:00
|
|
|
train_loader = torch.utils.data.DataLoader(train_ds,
|
|
|
|
num_workers=0,
|
|
|
|
batch_size=150)
|
2021-04-21 12:54:07 +00:00
|
|
|
|
2021-05-06 12:10:09 +00:00
|
|
|
# Hyperparameters
|
2021-05-25 13:41:10 +00:00
|
|
|
num_classes = 3
|
2021-05-11 14:15:08 +00:00
|
|
|
prototypes_per_class = 2
|
2021-05-06 12:10:09 +00:00
|
|
|
hparams = dict(
|
2021-05-25 13:41:10 +00:00
|
|
|
distribution=(num_classes, prototypes_per_class),
|
2021-05-06 12:10:09 +00:00
|
|
|
lr=0.01,
|
2021-04-21 17:16:57 +00:00
|
|
|
)
|
2021-04-21 19:35:52 +00:00
|
|
|
|
|
|
|
# Initialize the model
|
2021-05-12 14:36:22 +00:00
|
|
|
model = pt.models.GLVQ(hparams,
|
|
|
|
optimizer=torch.optim.Adam,
|
|
|
|
prototype_initializer=pt.components.SMI(train_ds))
|
2021-05-07 13:25:04 +00:00
|
|
|
|
|
|
|
# Callbacks
|
2021-05-13 13:22:01 +00:00
|
|
|
vis = pt.models.VisGLVQ2D(data=(x_train, y_train), block=False)
|
2021-04-21 19:35:52 +00:00
|
|
|
|
2021-05-06 12:10:09 +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-05-06 12:10:09 +00:00
|
|
|
)
|
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)
|