2021-04-21 12:54:07 +00:00
|
|
|
"""GLVQ example using the Iris dataset."""
|
|
|
|
|
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
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2021-04-21 13:52:42 +00:00
|
|
|
# Dataset
|
2021-05-07 13:25:04 +00:00
|
|
|
from sklearn.datasets import load_iris
|
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
|
|
|
|
hparams = dict(
|
|
|
|
nclasses=3,
|
|
|
|
prototypes_per_class=2,
|
2021-05-07 13:25:04 +00:00
|
|
|
prototype_initializer=pt.components.SMI(train_ds),
|
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-07 13:25:04 +00:00
|
|
|
model = pt.models.GLVQ(hparams)
|
|
|
|
|
|
|
|
# Callbacks
|
|
|
|
vis = pt.models.VisGLVQ2D(data=(x_train, y_train))
|
2021-04-21 19:35:52 +00:00
|
|
|
|
2021-05-06 12:10:09 +00:00
|
|
|
# Setup trainer
|
|
|
|
trainer = pl.Trainer(
|
|
|
|
max_epochs=50,
|
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)
|