prototorch_models/examples/glvq_iris.py

44 lines
1.1 KiB
Python
Raw Normal View History

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
# Hyperparameters
2021-05-11 14:15:08 +00:00
nclasses = 3
prototypes_per_class = 2
hparams = dict(
2021-05-11 14:15:08 +00:00
distribution=(nclasses, prototypes_per_class),
lr=0.01,
)
2021-04-21 19:35:52 +00:00
# Initialize the model
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
# Setup trainer
trainer = pl.Trainer(
2021-05-13 13:22:01 +00:00
gpus=-1,
max_epochs=50,
2021-05-07 13:25:04 +00:00
callbacks=[vis],
)
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)