2021-06-02 00:40:29 +00:00
|
|
|
"""Dynamically prune 'loser' prototypes in GLVQ-type models."""
|
2021-06-02 00:36:37 +00:00
|
|
|
|
|
|
|
import argparse
|
|
|
|
|
|
|
|
import prototorch as pt
|
|
|
|
import pytorch_lightning as pl
|
|
|
|
import torch
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
# Command-line arguments
|
|
|
|
parser = argparse.ArgumentParser()
|
|
|
|
parser = pl.Trainer.add_argparse_args(parser)
|
|
|
|
args = parser.parse_args()
|
|
|
|
|
|
|
|
# Dataset
|
|
|
|
num_classes = 4
|
|
|
|
num_features = 2
|
|
|
|
num_clusters = 1
|
|
|
|
train_ds = pt.datasets.Random(num_samples=500,
|
|
|
|
num_classes=num_classes,
|
|
|
|
num_features=num_features,
|
|
|
|
num_clusters=num_clusters,
|
|
|
|
separation=3.0,
|
|
|
|
seed=42)
|
|
|
|
|
|
|
|
# Dataloaders
|
|
|
|
train_loader = torch.utils.data.DataLoader(train_ds, batch_size=256)
|
|
|
|
|
|
|
|
# Hyperparameters
|
|
|
|
prototypes_per_class = num_clusters * 5
|
|
|
|
hparams = dict(
|
|
|
|
distribution=(num_classes, prototypes_per_class),
|
2021-06-04 13:56:46 +00:00
|
|
|
lr=0.1,
|
2021-06-02 00:36:37 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
# Initialize the model
|
|
|
|
model = pt.models.CELVQ(
|
|
|
|
hparams,
|
|
|
|
prototype_initializer=pt.components.Ones(2, scale=3),
|
|
|
|
)
|
|
|
|
|
|
|
|
# Callbacks
|
|
|
|
vis = pt.models.VisGLVQ2D(train_ds)
|
2021-06-02 01:53:21 +00:00
|
|
|
pruning = pt.models.PruneLoserPrototypes(
|
2021-06-02 00:36:37 +00:00
|
|
|
threshold=0.01, # prune prototype if it wins less than 1%
|
2021-06-04 13:56:46 +00:00
|
|
|
idle_epochs=20, # pruning too early may cause problems
|
|
|
|
prune_quota_per_epoch=2, # prune at most 2 prototypes per epoch
|
|
|
|
frequency=1, # prune every epoch
|
2021-06-02 00:36:37 +00:00
|
|
|
verbose=True,
|
|
|
|
)
|
2021-06-03 11:38:16 +00:00
|
|
|
es = pl.callbacks.EarlyStopping(
|
|
|
|
monitor="train_loss",
|
|
|
|
min_delta=0.001,
|
2021-06-04 13:56:46 +00:00
|
|
|
patience=20,
|
2021-06-02 10:44:34 +00:00
|
|
|
mode="min",
|
2021-06-04 13:56:46 +00:00
|
|
|
verbose=True,
|
2021-06-03 11:38:16 +00:00
|
|
|
check_on_train_epoch_end=True,
|
2021-06-02 10:44:34 +00:00
|
|
|
)
|
2021-06-02 00:36:37 +00:00
|
|
|
|
|
|
|
# Setup trainer
|
|
|
|
trainer = pl.Trainer.from_argparse_args(
|
|
|
|
args,
|
|
|
|
callbacks=[
|
|
|
|
vis,
|
|
|
|
pruning,
|
2021-06-02 10:44:34 +00:00
|
|
|
es,
|
2021-06-02 00:36:37 +00:00
|
|
|
],
|
2021-06-04 13:56:46 +00:00
|
|
|
progress_bar_refresh_rate=0,
|
2021-06-02 00:36:37 +00:00
|
|
|
terminate_on_nan=True,
|
|
|
|
weights_summary=None,
|
|
|
|
accelerator="ddp",
|
|
|
|
)
|
|
|
|
|
|
|
|
# Training loop
|
|
|
|
trainer.fit(model, train_loader)
|