| 1 |
|
| 2 |
""" |
| 3 |
============================== |
| 4 |
Graph classification with Template Based Fused Gromov Wasserstein |
| 5 |
============================== |
| 6 |
|
| 7 |
This example first illustrates how to train a graph classification gnn based on the Template Fused Gromov Wasserstein layer as proposed in [52] . |
| 8 |
|
| 9 |
[53] C. Vincent-Cuaz, R. Flamary, M. Corneli, T. Vayer, N. Courty (2022).Template based graph neural network with optimal transport distances. Advances in Neural Information Processing Systems, 35. |
| 10 |
|
| 11 |
""" |
| 12 |
|
| 13 |
|
| 14 |
> |
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
import matplotlib.pyplot as pl |
| 23 |
import torch |
| 24 |
import networkx as nx |
| 25 |
from torch.utils.data import random_split |
| 26 |
from torch_geometric.loader import DataLoader |
| 27 |
from torch_geometric.utils import to_networkx, one_hot |
| 28 |
from torch_geometric.utils import stochastic_blockmodel_graph as sbm |
| 29 |
from torch_geometric.data import Data as GraphData |
| 30 |
import torch.nn as nn |
| 31 |
from torch_geometric.nn import Linear, GCNConv |
| 32 |
from ot.gnn import TFGWPooling |
| 33 |
from sklearn.manifold import TSNE |
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
torch.manual_seed(0) |
| 45 |
|
| 46 |
n_graphs = 50 |
| 47 |
n_nodes = 10 |
| 48 |
n_node_classes = 2 |
| 49 |
|
| 50 |
|
| 51 |
P1 = [[0.8]] |
| 52 |
P2 = [[0.9, 0.1], [0.1, 0.9]] |
| 53 |
|
| 54 |
|
| 55 |
block_sizes1 = [n_nodes] |
| 56 |
block_sizes2 = [n_nodes // 2, n_nodes // 2] |
| 57 |
|
| 58 |
|
| 59 |
x1 = torch.tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) |
| 60 |
x1 = one_hot(x1, num_classes=n_node_classes) |
| 61 |
x1 = torch.reshape(x1, (n_nodes, n_node_classes)) |
| 62 |
|
| 63 |
x2 = torch.tensor([0, 0, 0, 0, 0, 1, 1, 1, 1, 1]) |
| 64 |
x2 = one_hot(x2, num_classes=n_node_classes) |
| 65 |
x2 = torch.reshape(x2, (n_nodes, n_node_classes)) |
| 66 |
|
| 67 |
graphs1 = [ |
| 68 |
GraphData(x=x1, edge_index=sbm(block_sizes1, P1), y=torch.tensor([0])) |
| 69 |
for i in range(n_graphs) |
| 70 |
] |
| 71 |
graphs2 = [ |
| 72 |
GraphData(x=x2, edge_index=sbm(block_sizes2, P2), y=torch.tensor([1])) |
| 73 |
for i in range(n_graphs) |
| 74 |
] |
| 75 |
|
| 76 |
graphs = graphs1 + graphs2 |
| 77 |
|
| 78 |
|
| 79 |
train_graphs, test_graphs = random_split(graphs, [n_graphs, n_graphs]) |
| 80 |
|
| 81 |
train_loader = DataLoader(train_graphs, batch_size=10, shuffle=True) |
| 82 |
test_loader = DataLoader(test_graphs, batch_size=10, shuffle=False) |
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
fontsize = 10 |
| 94 |
|
| 95 |
pl.figure(0, figsize=(8, 2.5)) |
| 96 |
pl.clf() |
| 97 |
pl.subplot(121) |
| 98 |
pl.axis("off") |
| 99 |
pl.title("Graph of class 1", fontsize=fontsize) |
| 100 |
G = to_networkx(graphs1[0], to_undirected=True) |
| 101 |
pos = nx.spring_layout(G, seed=0) |
| 102 |
nx.draw_networkx(G, pos, with_labels=False, node_color="tab:blue") |
| 103 |
|
| 104 |
pl.subplot(122) |
| 105 |
pl.axis("off") |
| 106 |
pl.title("Graph of class 2", fontsize=fontsize) |
| 107 |
G = to_networkx(graphs2[0], to_undirected=True) |
| 108 |
pos = nx.spring_layout(G, seed=0) |
| 109 |
nx.draw_networkx( |
| 110 |
G, pos, with_labels=False, nodelist=[0, 1, 2, 3, 4], node_color="tab:blue" |
| 111 |
) |
| 112 |
nx.draw_networkx( |
| 113 |
G, pos, with_labels=False, nodelist=[5, 6, 7, 8, 9], node_color="tab:red" |
| 114 |
) |
| 115 |
|
| 116 |
pl.tight_layout() |
| 117 |
pl.show() |
| 118 |
|
| 119 |
|
| 120 |
|
| 121 |
|
| 122 |
|
| 123 |
|
| 124 |
|
| 125 |
|
| 126 |
class pooling_TFGW(nn.Module): |
| 127 |
""" |
| 128 |
Pooling architecture using the TFGW layer. |
| 129 |
""" |
| 130 |
|
| 131 |
def __init__( |
| 132 |
self, |
| 133 |
n_features, |
| 134 |
n_templates, |
| 135 |
n_template_nodes, |
| 136 |
n_classes, |
| 137 |
n_hidden_layers, |
| 138 |
feature_init_mean=0.0, |
| 139 |
feature_init_std=1.0, |
| 140 |
): |
| 141 |
""" |
| 142 |
Pooling architecture using the TFGW layer. |
| 143 |
""" |
| 144 |
super().__init__() |
| 145 |
|
| 146 |
self.n_templates = n_templates |
| 147 |
self.n_template_nodes = n_template_nodes |
| 148 |
self.n_hidden_layers = n_hidden_layers |
| 149 |
self.n_features = n_features |
| 150 |
|
| 151 |
self.conv = GCNConv(self.n_features, self.n_hidden_layers) |
| 152 |
|
| 153 |
self.TFGW = TFGWPooling( |
| 154 |
self.n_hidden_layers, |
| 155 |
self.n_templates, |
| 156 |
self.n_template_nodes, |
| 157 |
feature_init_mean=feature_init_mean, |
| 158 |
feature_init_std=feature_init_std, |
| 159 |
) |
| 160 |
|
| 161 |
self.linear = Linear(self.n_templates, n_classes) |
| 162 |
|
| 163 |
def forward(self, x, edge_index, batch=None): |
| 164 |
x = self.conv(x, edge_index) |
| 165 |
|
| 166 |
x = self.TFGW(x, edge_index, batch) |
| 167 |
|
| 168 |
x_latent = x |
| 169 |
|
| 170 |
x = self.linear(x) |
| 171 |
|
| 172 |
return x, x_latent |
| 173 |
|
| 174 |
|
| 175 |
|
| 176 |
|
| 177 |
|
| 178 |
|
| 179 |
|
| 180 |
n_epochs = 25 |
| 181 |
|
| 182 |
|
| 183 |
embeddings_for_TSNE = [] |
| 184 |
classes = [] |
| 185 |
|
| 186 |
model = pooling_TFGW( |
| 187 |
n_features=2, |
| 188 |
n_templates=2, |
| 189 |
n_template_nodes=2, |
| 190 |
n_classes=2, |
| 191 |
n_hidden_layers=2, |
| 192 |
feature_init_mean=0.5, |
| 193 |
feature_init_std=0.5, |
| 194 |
) |
| 195 |
|
| 196 |
optimizer = torch.optim.Adam(model.parameters(), lr=0.005, weight_decay=0.0005) |
| 197 |
criterion = torch.nn.CrossEntropyLoss() |
| 198 |
|
| 199 |
all_accuracy = [] |
| 200 |
all_loss = [] |
| 201 |
|
| 202 |
for epoch in range(n_epochs): |
| 203 |
losses = [] |
| 204 |
accs = [] |
| 205 |
|
| 206 |
for data in train_loader: |
| 207 |
out, latent_embedding = model(data.x, data.edge_index, data.batch) |
| 208 |
loss = criterion(out, data.y) |
| 209 |
loss.backward() |
| 210 |
optimizer.step() |
| 211 |
|
| 212 |
pred = out.argmax(dim=1) |
| 213 |
train_correct = pred == data.y |
| 214 |
train_acc = int(train_correct.sum()) / len(data) |
| 215 |
|
| 216 |
accs.append(train_acc) |
| 217 |
losses.append(loss.item()) |
| 218 |
|
| 219 |
|
| 220 |
if epoch == n_epochs - 1: |
| 221 |
embeddings_for_TSNE.append(latent_embedding) |
| 222 |
classes.append(data.y) |
| 223 |
|
| 224 |
print( |
| 225 |
f"Epoch: {epoch:03d}, Loss: {torch.mean(torch.tensor(losses)):.4f},Train Accuracy: {torch.mean(torch.tensor(accs)):.4f}" |
| 226 |
) |
| 227 |
|
| 228 |
all_accuracy.append(torch.mean(torch.tensor(accs))) |
| 229 |
all_loss.append(torch.mean(torch.tensor(losses))) |
| 230 |
|
| 231 |
|
| 232 |
pl.figure(1, figsize=(8, 2.5)) |
| 233 |
pl.clf() |
| 234 |
pl.subplot(121) |
| 235 |
pl.plot(all_loss) |
| 236 |
pl.xlabel("epochs") |
| 237 |
pl.title("Loss") |
| 238 |
|
| 239 |
pl.subplot(122) |
| 240 |
pl.plot(all_accuracy) |
| 241 |
pl.xlabel("epochs") |
| 242 |
pl.title("Accuracy") |
| 243 |
|
| 244 |
pl.tight_layout() |
| 245 |
pl.show() |
| 246 |
|
| 247 |
|
| 248 |
|
| 249 |
test_accs = [] |
| 250 |
|
| 251 |
for data in test_loader: |
| 252 |
out, latent_embedding = model(data.x, data.edge_index, data.batch) |
| 253 |
pred = out.argmax(dim=1) |
| 254 |
test_correct = pred == data.y |
| 255 |
test_acc = int(test_correct.sum()) / len(data) |
| 256 |
test_accs.append(test_acc) |
| 257 |
embeddings_for_TSNE.append(latent_embedding) |
| 258 |
classes.append(data.y) |
| 259 |
|
| 260 |
classes = torch.hstack(classes) |
| 261 |
|
| 262 |
print(f"Test Accuracy: {torch.mean(torch.tensor(test_acc)):.4f}") |
| 263 |
|
| 264 |
|
| 265 |
|
| 266 |
|
| 267 |
|
| 268 |
|
| 269 |
indices = torch.randint( |
| 270 |
2 * n_graphs, (60,) |
| 271 |
) |
| 272 |
latent_embeddings = torch.vstack(embeddings_for_TSNE).detach().numpy()[indices, :] |
| 273 |
|
| 274 |
TSNE_embeddings = TSNE(n_components=2, perplexity=20, random_state=1).fit_transform( |
| 275 |
latent_embeddings |
| 276 |
) |
| 277 |
|
| 278 |
class_0 = classes[indices] == 0 |
| 279 |
class_1 = classes[indices] == 1 |
| 280 |
|
| 281 |
TSNE_embeddings_0 = TSNE_embeddings[class_0, :] |
| 282 |
TSNE_embeddings_1 = TSNE_embeddings[class_1, :] |
| 283 |
|
| 284 |
pl.figure(2, figsize=(6, 2.5)) |
| 285 |
pl.scatter( |
| 286 |
TSNE_embeddings_0[:, 0], |
| 287 |
TSNE_embeddings_0[:, 1], |
| 288 |
alpha=0.5, |
| 289 |
marker="o", |
| 290 |
label="class 1", |
| 291 |
) |
| 292 |
pl.scatter( |
| 293 |
TSNE_embeddings_1[:, 0], |
| 294 |
TSNE_embeddings_1[:, 1], |
| 295 |
alpha=0.5, |
| 296 |
marker="o", |
| 297 |
label="class 2", |
| 298 |
) |
| 299 |
pl.legend() |
| 300 |
pl.title("TSNE in the latent space after training") |
| 301 |
pl.show() |
| 302 |
|
| 303 |
|
| 304 |
|