2021-04-22 14:01:44 +00:00
|
|
|
"""CBC example using the Iris dataset."""
|
|
|
|
|
|
|
|
import numpy as np
|
|
|
|
import pytorch_lightning as pl
|
|
|
|
import torch
|
|
|
|
from matplotlib import pyplot as plt
|
2021-05-06 12:10:09 +00:00
|
|
|
from prototorch.components import initializers as cinit
|
|
|
|
from prototorch.datasets.abstract import NumpyDataset
|
2021-04-22 14:01:44 +00:00
|
|
|
from sklearn.datasets import load_iris
|
2021-04-23 15:27:47 +00:00
|
|
|
from torch.utils.data import DataLoader
|
2021-04-22 14:01:44 +00:00
|
|
|
|
2021-05-06 12:10:09 +00:00
|
|
|
from prototorch.models.cbc import CBC, euclidean_similarity
|
2021-04-22 14:01:44 +00:00
|
|
|
|
|
|
|
|
|
|
|
class VisualizationCallback(pl.Callback):
|
2021-05-06 12:10:09 +00:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
x_train,
|
|
|
|
y_train,
|
|
|
|
prototype_model=True,
|
|
|
|
title="Prototype Visualization",
|
|
|
|
cmap="viridis",
|
|
|
|
):
|
2021-04-22 14:01:44 +00:00
|
|
|
super().__init__()
|
|
|
|
self.x_train = x_train
|
|
|
|
self.y_train = y_train
|
|
|
|
self.title = title
|
|
|
|
self.fig = plt.figure(self.title)
|
|
|
|
self.cmap = cmap
|
2021-05-06 12:10:09 +00:00
|
|
|
self.prototype_model = prototype_model
|
2021-04-22 14:01:44 +00:00
|
|
|
|
|
|
|
def on_epoch_end(self, trainer, pl_module):
|
2021-05-06 12:10:09 +00:00
|
|
|
if self.prototype_model:
|
|
|
|
protos = pl_module.components
|
|
|
|
color = pl_module.prototype_labels
|
|
|
|
else:
|
|
|
|
protos = pl_module.components
|
|
|
|
color = "k"
|
2021-04-22 14:01:44 +00:00
|
|
|
ax = self.fig.gca()
|
|
|
|
ax.cla()
|
|
|
|
ax.set_title(self.title)
|
|
|
|
ax.set_xlabel("Data dimension 1")
|
|
|
|
ax.set_ylabel("Data dimension 2")
|
|
|
|
ax.scatter(x_train[:, 0], x_train[:, 1], c=y_train, edgecolor="k")
|
|
|
|
ax.scatter(
|
|
|
|
protos[:, 0],
|
|
|
|
protos[:, 1],
|
2021-05-06 12:10:09 +00:00
|
|
|
c=color,
|
2021-04-22 14:01:44 +00:00
|
|
|
cmap=self.cmap,
|
|
|
|
edgecolor="k",
|
|
|
|
marker="D",
|
2021-04-23 15:27:47 +00:00
|
|
|
s=50,
|
|
|
|
)
|
2021-04-22 14:01:44 +00:00
|
|
|
x = np.vstack((x_train, protos))
|
|
|
|
x_min, x_max = x[:, 0].min() - 1, x[:, 0].max() + 1
|
|
|
|
y_min, y_max = x[:, 1].min() - 1, x[:, 1].max() + 1
|
|
|
|
xx, yy = np.meshgrid(np.arange(x_min, x_max, 1 / 50),
|
|
|
|
np.arange(y_min, y_max, 1 / 50))
|
|
|
|
mesh_input = np.c_[xx.ravel(), yy.ravel()]
|
|
|
|
y_pred = pl_module.predict(torch.Tensor(mesh_input))
|
|
|
|
y_pred = y_pred.reshape(xx.shape)
|
|
|
|
|
|
|
|
ax.contourf(xx, yy, y_pred, cmap=self.cmap, alpha=0.35)
|
|
|
|
ax.set_xlim(left=x_min + 0, right=x_max - 0)
|
|
|
|
ax.set_ylim(bottom=y_min + 0, top=y_max - 0)
|
|
|
|
plt.pause(0.1)
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
# Dataset
|
|
|
|
x_train, y_train = load_iris(return_X_y=True)
|
|
|
|
x_train = x_train[:, [0, 2]]
|
|
|
|
train_ds = NumpyDataset(x_train, y_train)
|
|
|
|
|
|
|
|
# Dataloaders
|
|
|
|
train_loader = DataLoader(train_ds, num_workers=0, batch_size=150)
|
|
|
|
|
|
|
|
# Hyperparameters
|
2021-04-23 15:27:47 +00:00
|
|
|
hparams = dict(
|
|
|
|
input_dim=x_train.shape[1],
|
2021-05-06 12:10:09 +00:00
|
|
|
nclasses=len(np.unique(y_train)),
|
|
|
|
num_components=9,
|
|
|
|
component_initializer=cinit.StratifiedMeanInitializer(
|
|
|
|
torch.Tensor(x_train), torch.Tensor(y_train)),
|
2021-04-23 15:27:47 +00:00
|
|
|
lr=0.01,
|
|
|
|
)
|
2021-04-22 14:01:44 +00:00
|
|
|
|
|
|
|
# Initialize the model
|
2021-05-06 12:10:09 +00:00
|
|
|
model = CBC(
|
|
|
|
hparams,
|
|
|
|
data=[x_train, y_train],
|
|
|
|
similarity=euclidean_similarity,
|
|
|
|
)
|
2021-04-22 14:01:44 +00:00
|
|
|
|
|
|
|
# Callbacks
|
2021-05-06 12:10:09 +00:00
|
|
|
dvis = VisualizationCallback(x_train,
|
|
|
|
y_train,
|
|
|
|
prototype_model=False,
|
|
|
|
title="CBC Iris Example")
|
2021-04-22 14:01:44 +00:00
|
|
|
|
|
|
|
# Setup trainer
|
|
|
|
trainer = pl.Trainer(
|
2021-05-06 12:10:09 +00:00
|
|
|
max_epochs=50,
|
2021-04-22 14:01:44 +00:00
|
|
|
callbacks=[
|
2021-05-06 12:10:09 +00:00
|
|
|
dvis,
|
2021-04-22 14:01:44 +00:00
|
|
|
],
|
|
|
|
)
|
|
|
|
|
|
|
|
# Training loop
|
2021-05-06 12:10:09 +00:00
|
|
|
trainer.fit(model, train_loader)
|