Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WECT implementation #31

Merged
merged 1 commit into from
Aug 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
"""Demo for using the Weighted Euler Characteristic transform
in an optimiblzation routine.

This example demonstrates how the WECT can be used to optimize
a neural networks predictions to match the topological signature
of a target.
"""
from torch import nn
import torch
from torch_topological.nn import EulerDistance, WeightedEulerCurve
import torch.optim as optim


class NN(nn.Module):
def __init__(self, inp_dim, hidden_dim, out_dim):
super(NN, self).__init__()
self.fc1 = torch.nn.Linear(inp_dim, hidden_dim)
self.fc2 = torch.nn.Linear(hidden_dim, hidden_dim)
self.fc3 = torch.nn.Linear(hidden_dim, out_dim)
self.out_dim = out_dim

def forward(self, x_):
x = x_.clone()
x = torch.nn.functional.relu(self.fc1(x))
x = torch.nn.functional.relu(self.fc2(x))
x = self.fc3(x)
x = torch.nn.functional.sigmoid(x)
out = int(self.out_dim ** (1 / 3))
return x.reshape([out, out, out])


if __name__ == "__main__":
torch.manual_seed(4)
z = 3
arr = torch.ones([z, z, z], requires_grad=False)
model = NN(z * z * z, 100, z * z * z)
arr2 = torch.rand([z, z, z], requires_grad=False)
arr2[arr2 > 0.5] = 1
arr2[arr2 <= 0.5] = 0
ec = WeightedEulerCurve(prod=True)
dist = EulerDistance()
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
ans = 100
while ans > 0.05:
optimizer.zero_grad()
ans = dist(ec(model(arr.flatten())), ec(arr2))
ans.backward()
optimizer.step()
with torch.no_grad():
print(
"L2 distance:",
dist(model(arr.flatten()), arr2),
" Euler Distance:",
ans,
)
5 changes: 4 additions & 1 deletion torch_topological/nn/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
from .alpha_complex import AlphaComplex
from .cubical_complex import CubicalComplex
from .vietoris_rips_complex import VietorisRipsComplex

from .weighted_euler_characteristic_transform import WeightedEulerCurve
from .weighted_euler_characteristic_transform import EulerDistance

__all__ = [
'AlphaComplex',
Expand All @@ -26,4 +27,6 @@
'SlicedWassersteinDistance',
'SlicedWassersteinKernel',
'MultiScaleKernel',
'WeightedEulerCurve',
'EulerDistance'
]
Loading