-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathalpha_complex.py
57 lines (41 loc) · 1.6 KB
/
alpha_complex.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
"""Example demonstrating the computation of alpha complexes.
This simple example demonstrates how to use alpha complexes to change
the appearance of a point cloud, following the `TopologyLayer
<https://github.com/bruel-gabrielsson/TopologyLayer>`_ package.
This example is still a **work in progress**.
"""
from torch_topological.nn import AlphaComplex
from torch_topological.nn import SummaryStatisticLoss
from torch_topological.utils import SelectByDimension
import numpy as np
import matplotlib.pyplot as plt
import torch
if __name__ == '__main__':
np.random.seed(42)
data = np.random.rand(100, 2)
alpha_complex = AlphaComplex()
loss_fn = SummaryStatisticLoss(
summary_statistic='polynomial_function',
p=2,
q=0
)
X = torch.nn.Parameter(torch.as_tensor(data), requires_grad=True)
opt = torch.optim.Adam([X], lr=1e-2)
for i in range(100):
# We are only interested in working with persistence diagrams of
# dimension 1.
selector = SelectByDimension(1)
# Let's think step by step; apparently, AIs like that! So let's
# first get the persistence information of our complex. We pass
# it through the selector to remove diagrams we do not need.
pers_info = alpha_complex(X)
pers_info = selector(pers_info)
# Evaluate the loss; notice that we want to *maximise* it in
# order to improve the holes in the data.
loss = -loss_fn(pers_info)
opt.zero_grad()
loss.backward()
opt.step()
X = X.detach().numpy()
plt.scatter(X[:, 0], X[:, 1])
plt.show()