2021-04-22 10:04:56 +00:00
|
|
|
"""GLVQ example using the Iris dataset."""
|
|
|
|
|
|
|
|
import pytorch_lightning as pl
|
|
|
|
import torch
|
2021-04-29 15:05:41 +00:00
|
|
|
from prototorch.components import initializers as cinit
|
2021-04-23 15:27:47 +00:00
|
|
|
from prototorch.datasets.abstract import NumpyDataset
|
2021-04-29 15:05:41 +00:00
|
|
|
from prototorch.models.callbacks.visualization import VisGLVQ2D
|
2021-04-23 15:27:47 +00:00
|
|
|
from prototorch.models.glvq import GLVQ
|
2021-04-29 15:05:41 +00:00
|
|
|
from sklearn.datasets import load_iris
|
|
|
|
from torch.utils.data import DataLoader
|
2021-04-22 10:04:56 +00:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
# Dataset
|
|
|
|
x_train, y_train = load_iris(return_X_y=True)
|
|
|
|
x_train = x_train[:, [0, 2]]
|
|
|
|
train_ds = NumpyDataset(x_train, y_train)
|
|
|
|
|
|
|
|
# Dataloaders
|
|
|
|
train_loader = DataLoader(train_ds, num_workers=0, batch_size=150)
|
|
|
|
|
|
|
|
# Hyperparameters
|
2021-04-23 15:27:47 +00:00
|
|
|
hparams = dict(
|
|
|
|
nclasses=3,
|
2021-04-29 15:05:41 +00:00
|
|
|
prototypes_per_class=2,
|
|
|
|
prototype_initializer=cinit.StratifiedMeanInitializer(
|
|
|
|
torch.Tensor(x_train), torch.Tensor(y_train)),
|
|
|
|
lr=0.01,
|
2021-04-23 15:27:47 +00:00
|
|
|
)
|
2021-04-22 10:04:56 +00:00
|
|
|
|
|
|
|
# Initialize the model
|
2021-04-29 15:11:06 +00:00
|
|
|
model = GLVQ(hparams)
|
2021-04-22 10:04:56 +00:00
|
|
|
|
|
|
|
# Setup trainer
|
2021-04-29 15:05:41 +00:00
|
|
|
trainer = pl.Trainer(
|
|
|
|
max_epochs=50,
|
|
|
|
callbacks=[VisGLVQ2D(x_train, y_train)],
|
|
|
|
)
|
2021-04-22 10:04:56 +00:00
|
|
|
|
|
|
|
# Training loop
|
|
|
|
trainer.fit(model, train_loader)
|