prototorch_models/examples/glvq_iris.py

42 lines
1.1 KiB
Python
Raw Normal View History

2021-04-21 12:54:07 +00:00
"""GLVQ example using the Iris dataset."""
import pytorch_lightning as pl
import torch
from prototorch.components import initializers as cinit
from prototorch.datasets.abstract import NumpyDataset
2021-04-21 12:54:07 +00:00
from sklearn.datasets import load_iris
2021-04-23 15:27:47 +00:00
from torch.utils.data import DataLoader
2021-04-21 12:54:07 +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-21 12:54:07 +00:00
if __name__ == "__main__":
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]]
train_ds = NumpyDataset(x_train, y_train)
2021-04-21 13:52:42 +00:00
# Dataloaders
2021-04-21 12:54:07 +00:00
train_loader = DataLoader(train_ds, num_workers=0, batch_size=150)
# Hyperparameters
hparams = dict(
nclasses=3,
prototypes_per_class=2,
prototype_initializer=cinit.StratifiedMeanInitializer(
torch.Tensor(x_train), torch.Tensor(y_train)),
lr=0.01,
)
2021-04-21 19:35:52 +00:00
# Initialize the model
model = GLVQ(hparams)
2021-04-21 19:35:52 +00:00
# Setup trainer
trainer = pl.Trainer(
max_epochs=50,
callbacks=[VisGLVQ2D(x_train, y_train)],
)
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)