-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodels.py
170 lines (137 loc) · 6.83 KB
/
models.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
from typing import Optional, Callable
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from torch_scatter import scatter_add
from layers import ProposedConv
from torch_geometric.nn import GCNConv
class HyperEncoder(nn.Module):
def __init__(self, in_dim, edge_dim, node_dim, num_layers=2, act: Callable = nn.PReLU()):
super(HyperEncoder, self).__init__()
self.in_dim = in_dim
self.edge_dim = edge_dim
self.node_dim = node_dim
self.num_layers = num_layers
self.act = act
self.convs = nn.ModuleList()
if num_layers == 1:
self.convs.append(ProposedConv(self.in_dim, self.edge_dim, self.node_dim, cached=False, act=act))
else:
self.convs.append(ProposedConv(self.in_dim, self.edge_dim, self.node_dim, cached=False, act=act))
for _ in range(self.num_layers - 2):
self.convs.append(ProposedConv(self.node_dim, self.edge_dim, self.node_dim, cached=False, act=act))
self.convs.append(ProposedConv(self.node_dim, self.edge_dim, self.node_dim, cached=False, act=act))
self.reset_parameters()
def reset_parameters(self):
for conv in self.convs:
conv.reset_parameters()
def forward(self, x: Tensor, hyperedge_index: Tensor, num_nodes: int, num_edges: int):
for i in range(self.num_layers):
x, e = self.convs[i](x, hyperedge_index, num_nodes, num_edges)
x = self.act(x)
return x, e
class SimHGCL(nn.Module):
def __init__(self, encoder: HyperEncoder, proj_dim: int):
super(SimHGCL, self).__init__()
self.encoder = encoder
self.in_dim = self.encoder.in_dim
self.node_dim = self.encoder.node_dim
self.fc1_n = nn.Linear(self.node_dim, proj_dim)
self.fc2_n = nn.Linear(proj_dim, self.node_dim)
self.act = nn.ReLU()
self.conv1 = GCNConv(self.in_dim, self.node_dim)
self.conv2 = GCNConv(self.node_dim, self.node_dim)
self.reset_parameters()
def reset_parameters(self):
self.encoder.reset_parameters()
self.fc1_n.reset_parameters()
self.fc2_n.reset_parameters()
self.conv1.reset_parameters()
self.conv2.reset_parameters()
def forward(self, x: Tensor, hyperedge_index: Tensor,
num_nodes: Optional[int] = None, num_edges: Optional[int] = None):
if num_nodes is None:
num_nodes = int(hyperedge_index[0].max()) + 1
if num_edges is None:
num_edges = int(hyperedge_index[1].max()) + 1
node_idx = torch.arange(0, num_nodes, device=x.device)
edge_idx = torch.arange(num_edges, num_edges + num_nodes, device=x.device)
self_loop = torch.stack([node_idx, edge_idx])
self_loop_hyperedge_index = torch.cat([hyperedge_index, self_loop], 1)
n, e = self.encoder(x, self_loop_hyperedge_index, num_nodes, num_edges + num_nodes)
return n, e[:num_edges]
def forward_gcn(self, x: Tensor, edge_index: Tensor, edge_attr = None):
x = self.conv1(x, edge_index, edge_attr)
x = self.act(x)
x = F.dropout(x)
x = self.conv2(x, edge_index, edge_attr)
return x
def without_selfloop(self, x: Tensor, hyperedge_index: Tensor, node_mask: Optional[Tensor] = None,
num_nodes: Optional[int] = None, num_edges: Optional[int] = None):
if num_nodes is None:
num_nodes = int(hyperedge_index[0].max()) + 1
if num_edges is None:
num_edges = int(hyperedge_index[1].max()) + 1
if node_mask is not None:
node_idx = torch.where(~node_mask)[0]
edge_idx = torch.arange(num_edges, num_edges + len(node_idx), device=x.device)
self_loop = torch.stack([node_idx, edge_idx])
self_loop_hyperedge_index = torch.cat([hyperedge_index, self_loop], 1)
n, e = self.encoder(x, self_loop_hyperedge_index, num_nodes, num_edges + len(node_idx))
return n, e[:num_edges]
else:
return self.encoder(x, hyperedge_index, num_nodes, num_edges)
def f(self, x, tau):
return torch.exp(x / tau)
def node_projection(self, z: Tensor):
return self.fc2_n(F.elu(self.fc1_n(z)))
def cosine_similarity(self, z1: Tensor, z2: Tensor):
z1 = F.normalize(z1)
z2 = F.normalize(z2)
return torch.mm(z1, z2.t())
def __semi_loss(self, h1: Tensor, h2: Tensor, tau: float, num_negs: Optional[int]):
if num_negs is None:
between_sim = self.f(self.cosine_similarity(h1, h2), tau)
return -torch.log(between_sim.diag() / between_sim.sum(1))
else:
pos_sim = self.f(F.cosine_similarity(h1, h2), tau)
negs = []
for _ in range(num_negs):
negs.append(h2[torch.randperm(h2.size(0))])
negs = torch.stack(negs, dim=-1)
neg_sim = self.f(F.cosine_similarity(h1.unsqueeze(-1).tile(num_negs), negs), tau)
return -torch.log(pos_sim / (pos_sim + neg_sim.sum(1)))
def __semi_loss_batch(self, h1: Tensor, h2: Tensor, tau: float, batch_size: int):
device = h1.device
num_samples = h1.size(0)
num_batches = (num_samples - 1) // batch_size + 1
indices = torch.arange(0, num_samples, device=device)
losses = []
for i in range(num_batches):
mask = indices[i * batch_size: (i + 1) * batch_size]
between_sim = self.f(self.cosine_similarity(h1[mask], h2), tau)
loss = -torch.log(between_sim[:, i * batch_size: (i + 1) * batch_size].diag() / between_sim.sum(1))
losses.append(loss)
return torch.cat(losses)
def __loss(self, z1: Tensor, z2: Tensor, tau: float, batch_size: Optional[int],
num_negs: Optional[int], mean: bool):
if batch_size is None or num_negs is not None:
l1 = self.__semi_loss(z1, z2, tau, num_negs)
l2 = self.__semi_loss(z2, z1, tau, num_negs)
else:
l1 = self.__semi_loss_batch(z1, z2, tau, batch_size)
l2 = self.__semi_loss_batch(z2, z1, tau, batch_size)
loss = (l1 + l2) * 0.5
loss = loss.mean() if mean else loss.sum()
return loss
def node_level_loss(self, n1: Tensor, n2: Tensor, node_tau: float,
batch_size: Optional[int] = None, num_negs: Optional[int] = None,
mean: bool = True):
loss = self.__loss(n1, n2, node_tau, batch_size, num_negs, mean)
return loss
def group_level_loss(self, e1: Tensor, e2: Tensor, edge_tau: float,
batch_size: Optional[int] = None, num_negs: Optional[int] = None,
mean: bool = True):
loss = self.__loss(e1, e2, edge_tau, batch_size, num_negs, mean)
return loss