-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathind_moon.py
202 lines (172 loc) · 7.75 KB
/
ind_moon.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
import os
import numpy as np
from sklearn.metrics import pairwise_distances
import matplotlib.pyplot as plt
import matplotlib.patheffects as PathEffects
from scipy.sparse import csr_matrix
import networkx as nx
from scipy.linalg import orthogonal_procrustes
import torch
import torch.optim as optim
from torch_geometric.data import Data
from sklearn.manifold import TSNE
from util import Net, GIN, GAT, moon, stationary, reconstruct, dG
np.random.seed(0)
torch.manual_seed(0)
n_test = 10000
m = 500
x_test, n_test = moon(n_test)
K_test = int(np.sqrt(n_test) * np.log2(n_test) / 10)
D = pairwise_distances(x_test)
fr_test = np.arange(n_test).repeat(K_test).reshape(-1)
to_test = np.argsort(D, axis=1)[:, 1:K_test + 1].reshape(-1)
A_test = csr_matrix((np.ones(n_test * K_test) / K_test, (fr_test, to_test)))
edge_index_test = np.vstack([fr_test, to_test])
edge_index_test = torch.tensor(edge_index_test, dtype=torch.long)
X_test = torch.tensor([[K_test, n_test] for i in range(n_test)], dtype=torch.float)
net = Net()
optimizer = optim.Adam(net.parameters(), lr=0.001)
net.train()
for i in range(100):
# Note 1: In the original formulation, $g$, i.e., the neural network for the scale function, should be used in reconstruct(K, pr, n, m, fr, to), namely, in the definition of $s$. We factorize $s$ and multiply g after we reconstruct the features. This is mathematically equivalent. We do this to avoid memory overflow due to long backpropagation.
# Note 2: We roughly standardize n for stability by (n - 3000) / 3000. This does not affect the representational power of GNNs by merging them into the network parameters.
n = np.random.randint(1000, 5001)
x, n = moon(n)
K = int(np.sqrt(n) * np.log2(n) / 10)
D = pairwise_distances(x)
fr = np.arange(n).repeat(K).reshape(-1)
to = np.argsort(D, axis=1)[:, 1:K + 1].reshape(-1)
A = csr_matrix((np.ones(n * K) / K, (fr, to)))
pr = stationary(A)
pr = np.maximum(pr, 1e-9)
rec_orig = reconstruct(K, pr, n, m, fr, to)
rec_orig = torch.FloatTensor(rec_orig)
g = net(torch.FloatTensor([(n - 3000) / 3000]))
rec = rec_orig * (g ** 0.5)
loss = dG(torch.FloatTensor(x), rec)
print(n, float(g), float(loss))
optimizer.zero_grad()
loss.backward()
optimizer.step()
pr = stationary(A_test)
pr = np.maximum(pr, 1e-9)
rec_orig = reconstruct(K_test, pr, n_test, m, fr_test, to_test)
rec_orig = torch.FloatTensor(rec_orig)
g = net(torch.FloatTensor([(n_test - 3000) / 3000]))
rec = rec_orig * (g ** 0.5)
R, _ = orthogonal_procrustes(x_test, rec.detach().numpy())
rec_proposed = rec.detach().numpy() @ R.T
loss_proposed = float(dG(torch.FloatTensor(x_test), rec))
net = GIN(m)
optimizer = optim.Adam(net.parameters(), lr=0.001)
net.train()
for epoch in range(100):
n = np.random.randint(1000, 5001)
x, n = moon(n)
K = int(np.sqrt(n) * np.log2(n) / 10)
D = pairwise_distances(x)
fr = np.arange(n).repeat(K).reshape(-1)
to = np.argsort(D, axis=1)[:, 1:K + 1].reshape(-1)
edge_index = np.vstack([fr, to])
edge_index = torch.tensor(edge_index, dtype=torch.long)
X = torch.tensor([[K, n] for i in range(n)], dtype=torch.float)
ind = torch.eye(n)[:, torch.randperm(n)[:m]]
X_extended = torch.hstack([X, ind])
data = Data(x=X_extended, edge_index=edge_index)
rec = net(data)
loss = dG(torch.FloatTensor(x), rec)
print(float(loss))
optimizer.zero_grad()
loss.backward()
optimizer.step()
ind = torch.eye(n_test)[:, torch.randperm(n_test)[:m]]
X_extended = torch.hstack([X_test, ind])
data = Data(x=X_extended, edge_index=edge_index_test)
rec = net(data)
R, _ = orthogonal_procrustes(x_test, rec.detach().numpy())
rec_GIN = rec.detach().numpy() @ R.T
loss_GIN = float(dG(torch.FloatTensor(x_test), rec))
net = GAT(m)
optimizer = optim.Adam(net.parameters(), lr=0.001)
net.train()
for epoch in range(100):
n = np.random.randint(1000, 5001)
x, n = moon(n)
K = int(np.sqrt(n) * np.log2(n) / 10)
D = pairwise_distances(x)
fr = np.arange(n).repeat(K).reshape(-1)
to = np.argsort(D, axis=1)[:, 1:K + 1].reshape(-1)
edge_index = np.vstack([fr, to])
edge_index = torch.tensor(edge_index, dtype=torch.long)
X = torch.tensor([[K, n] for i in range(n)], dtype=torch.float)
ind = torch.eye(n)[:, torch.randperm(n)[:m]]
X_extended = torch.hstack([X, ind])
data = Data(x=X_extended, edge_index=edge_index)
rec = net(data)
loss = dG(torch.FloatTensor(x), rec)
print(float(loss))
optimizer.zero_grad()
loss.backward()
optimizer.step()
ind = torch.eye(n_test)[:, torch.randperm(n_test)[:m]]
X_extended = torch.hstack([X_test, ind])
data = Data(x=X_extended, edge_index=edge_index_test)
rec = net(data)
R, _ = orthogonal_procrustes(x_test, rec.detach().numpy())
rec_GAT = rec.detach().numpy() @ R.T
loss_GAT = float(dG(torch.FloatTensor(x_test), rec))
ind = torch.eye(n_test)[:, torch.randperm(n_test)[:m]]
X_extended = torch.hstack([X_test, ind])
X_embedded = TSNE(n_components=2, random_state=0, init='pca').fit_transform(X_extended.numpy())
loss_tSNE = float(dG(torch.FloatTensor(x_test), X_embedded))
c = x_test[:, 0].argsort().argsort()
fig = plt.figure(figsize=(14, 4))
ax = fig.add_subplot(2, 3, 1)
ax.scatter(x_test[:, 0], x_test[:, 1], c=c, s=10, rasterized=True)
ax.set_xticks([])
ax.set_yticks([])
ax.set_facecolor('#eeeeee')
txt = ax.text(0.05, 0.05, 'Ground Truth', color='k', fontsize=14, weight='bold', transform=ax.transAxes)
txt.set_path_effects([PathEffects.withStroke(linewidth=5, foreground='#eeeeee')])
visible = plt.imread('./imgs/visible.png')
visible_ax = fig.add_axes([0.24, 0.77, 0.1, 0.1], anchor='NE', zorder=1)
visible_ax.imshow(visible)
visible_ax.axis('off')
G = nx.DiGraph()
G.add_edges_from([(fr_test[i], to_test[i]) for i in range(len(fr_test))])
ax = fig.add_subplot(2, 3, 2)
pos = nx.spring_layout(G, k=0.18, seed=0)
nx.draw_networkx(G, ax=ax, pos=pos, node_size=0.5, node_color='#005aff', labels={i: '' for i in range(n_test)}, edge_color='#84919e', width=0.0005, arrowsize=0.1)
txt = ax.text(0.05, 0.05, 'Input Graph', color='k', fontsize=14, weight='bold', transform=ax.transAxes)
txt.set_path_effects([PathEffects.withStroke(linewidth=5, foreground='w')])
ax.set_rasterization_zorder(3)
ax = fig.add_subplot(2, 3, 3)
ax.scatter(X_embedded[:, 0], X_embedded[:, 1], c=c, s=10, rasterized=True)
ax.set_xticks([])
ax.set_yticks([])
txt = ax.text(0.05, 0.05, 'tSNE(X) $d_G = {:.2f}$'.format(loss_tSNE), color='k', fontsize=14, weight='bold', transform=ax.transAxes)
txt.set_path_effects([PathEffects.withStroke(linewidth=5, foreground='w')])
ax = fig.add_subplot(2, 3, 4)
ax.scatter(rec_proposed[:, 0], rec_proposed[:, 1], c=c, s=10, rasterized=True)
ax.set_xticks([])
ax.set_yticks([])
txt = ax.text(0.05, 0.05, 'Proposed $d_G = \\mathbf{' + f'{loss_proposed:.3f}' + '}$', color='k', fontsize=14, weight='bold', transform=ax.transAxes)
txt.set_path_effects([PathEffects.withStroke(linewidth=5, foreground='w')])
ax = fig.add_subplot(2, 3, 5)
ax.scatter(rec_GIN[:, 0], rec_GIN[:, 1], c=c, s=10, rasterized=True)
ax.set_xticks([])
ax.set_yticks([])
txt = ax.text(0.05, 0.05, 'GIN $d_G = {:.2f}$'.format(loss_GIN), color='k', fontsize=14, weight='bold', transform=ax.transAxes)
txt.set_path_effects([PathEffects.withStroke(linewidth=5, foreground='w')])
ax = fig.add_subplot(2, 3, 6)
ax.scatter(rec_GAT[:, 0], rec_GAT[:, 1], c=c, s=10, rasterized=True)
ax.set_xticks([])
ax.set_yticks([])
txt = ax.text(0.05, 0.05, 'GAT $d_G = {:.2f}$'.format(loss_GAT), color='k', fontsize=14, weight='bold', transform=ax.transAxes)
txt.set_path_effects([PathEffects.withStroke(linewidth=5, foreground='w')])
fig.subplots_adjust()
if not os.path.exists('imgs'):
os.mkdir('imgs')
fig.savefig('imgs/ind_moon.png', bbox_inches='tight', dpi=300)
fig.savefig('imgs/ind_moon.pdf', bbox_inches='tight', dpi=300)
fig.savefig('imgs/ind_moon.svg', bbox_inches='tight', dpi=300)