prototorch_models/examples/gmlvq_mnist.py

81 lines
1.9 KiB
Python
Raw Normal View History

"""GMLVQ example using the MNIST dataset."""
2021-05-18 08:17:51 +00:00
import argparse
import prototorch as pt
import pytorch_lightning as pl
import torch
from torchvision import transforms
from torchvision.datasets import MNIST
if __name__ == "__main__":
2021-05-18 08:17:51 +00:00
# Command-line arguments
parser = argparse.ArgumentParser()
parser = pl.Trainer.add_argparse_args(parser)
args = parser.parse_args()
# Dataset
train_ds = MNIST(
"~/datasets",
train=True,
download=True,
transform=transforms.Compose([
transforms.ToTensor(),
]),
)
test_ds = MNIST(
"~/datasets",
train=False,
download=True,
transform=transforms.Compose([
transforms.ToTensor(),
]),
)
# Dataloaders
train_loader = torch.utils.data.DataLoader(train_ds,
num_workers=0,
batch_size=256)
test_loader = torch.utils.data.DataLoader(test_ds,
num_workers=0,
batch_size=256)
# Hyperparameters
2021-05-25 13:41:10 +00:00
num_classes = 10
prototypes_per_class = 2
hparams = dict(
input_dim=28 * 28,
latent_dim=28 * 28,
2021-05-25 13:41:10 +00:00
distribution=(num_classes, prototypes_per_class),
2021-05-18 08:17:51 +00:00
proto_lr=0.01,
bb_lr=0.01,
)
# Initialize the model
model = pt.models.ImageGMLVQ(
hparams,
optimizer=torch.optim.Adam,
prototype_initializer=pt.components.SMI(train_ds),
)
# Callbacks
2021-05-18 08:17:51 +00:00
vis = pt.models.VisImgComp(
data=train_ds,
2021-05-25 13:41:10 +00:00
num_columns=5,
2021-05-18 08:17:51 +00:00
show=False,
tensorboard=True,
2021-05-20 14:07:16 +00:00
random_data=20,
add_embedding=True,
2021-05-20 15:35:07 +00:00
embedding_data=100,
2021-05-20 14:07:16 +00:00
flatten_data=False,
2021-05-18 08:17:51 +00:00
)
# Setup trainer
2021-05-18 08:17:51 +00:00
trainer = pl.Trainer.from_argparse_args(
args,
callbacks=[vis],
)
# Training loop
trainer.fit(model, train_loader)