2021-04-27 12:35:17 +00:00
|
|
|
"""Siamese GLVQ example using all four dimensions of the Iris dataset."""
|
|
|
|
|
2021-05-07 13:25:04 +00:00
|
|
|
import prototorch as pt
|
2021-04-27 12:35:17 +00:00
|
|
|
import pytorch_lightning as pl
|
|
|
|
import torch
|
2021-05-06 12:10:09 +00:00
|
|
|
|
2021-04-27 12:35:17 +00:00
|
|
|
|
|
|
|
class Backbone(torch.nn.Module):
|
|
|
|
def __init__(self, input_size=4, hidden_size=10, latent_size=2):
|
|
|
|
super().__init__()
|
|
|
|
self.input_size = input_size
|
|
|
|
self.hidden_size = hidden_size
|
|
|
|
self.latent_size = latent_size
|
|
|
|
self.dense1 = torch.nn.Linear(self.input_size, self.hidden_size)
|
|
|
|
self.dense2 = torch.nn.Linear(self.hidden_size, self.latent_size)
|
2021-05-17 15:03:37 +00:00
|
|
|
self.activation = torch.nn.Sigmoid()
|
2021-04-27 12:35:17 +00:00
|
|
|
|
|
|
|
def forward(self, x):
|
2021-05-17 15:03:37 +00:00
|
|
|
x = self.activation(self.dense1(x))
|
|
|
|
out = self.activation(self.dense2(x))
|
2021-05-07 11:07:30 +00:00
|
|
|
return out
|
2021-04-27 12:35:17 +00:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
# Dataset
|
2021-05-11 15:22:02 +00:00
|
|
|
train_ds = pt.datasets.Iris()
|
2021-04-27 12:35:17 +00:00
|
|
|
|
2021-05-07 11:07:30 +00:00
|
|
|
# Reproducibility
|
|
|
|
pl.utilities.seed.seed_everything(seed=2)
|
|
|
|
|
2021-04-27 12:35:17 +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-27 12:35:17 +00:00
|
|
|
|
|
|
|
# Hyperparameters
|
|
|
|
hparams = dict(
|
2021-05-11 14:15:08 +00:00
|
|
|
distribution=[1, 2, 3],
|
|
|
|
proto_lr=0.01,
|
|
|
|
bb_lr=0.01,
|
2021-04-27 12:35:17 +00:00
|
|
|
)
|
|
|
|
|
2021-05-17 15:03:37 +00:00
|
|
|
# Initialize the backbone
|
|
|
|
backbone = Backbone()
|
|
|
|
|
2021-04-27 12:35:17 +00:00
|
|
|
# Initialize the model
|
2021-05-07 13:25:04 +00:00
|
|
|
model = pt.models.SiameseGLVQ(
|
2021-04-29 15:05:41 +00:00
|
|
|
hparams,
|
2021-05-12 14:36:22 +00:00
|
|
|
prototype_initializer=pt.components.SMI(train_ds),
|
2021-05-17 15:03:37 +00:00
|
|
|
backbone=backbone,
|
2021-05-19 14:30:19 +00:00
|
|
|
both_path_gradients=False,
|
2021-04-29 15:05:41 +00:00
|
|
|
)
|
2021-04-27 12:35:17 +00:00
|
|
|
|
|
|
|
# Model summary
|
|
|
|
print(model)
|
|
|
|
|
|
|
|
# Callbacks
|
2021-05-11 15:22:02 +00:00
|
|
|
vis = pt.models.VisSiameseGLVQ2D(data=train_ds, border=0.1)
|
2021-04-27 12:35:17 +00:00
|
|
|
|
|
|
|
# Setup trainer
|
2021-05-15 10:43:00 +00:00
|
|
|
trainer = pl.Trainer(max_epochs=100, callbacks=[vis], gpus=0)
|
2021-04-27 12:35:17 +00:00
|
|
|
|
|
|
|
# Training loop
|
|
|
|
trainer.fit(model, train_loader)
|