File: test_gnn.py

package info (click to toggle)
python-pot 0.9.5%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,884 kB
  • sloc: python: 56,498; cpp: 2,310; makefile: 265; sh: 19
file content (299 lines) | stat: -rw-r--r-- 8,765 bytes parent folder | download
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
"""Tests for module gnn"""

# Author: Sonia Mazelet <sonia.mazelet@ens-paris-saclay.fr>
#         Rémi Flamary <remi.flamary@unice.fr>
#
# License: MIT License

import pytest

try:  # test if pytorch_geometric is installed
    import torch_geometric
    import torch
    from torch_geometric.nn import Linear
    from torch_geometric.data import Data as GraphData
    from torch_geometric.loader import DataLoader
    import torch.nn as nn
    from ot.gnn import TFGWPooling, TWPooling

except ImportError:
    torch_geometric = False


@pytest.mark.skipif(not torch_geometric, reason="pytorch_geometric not installed")
def test_TFGW_optim():
    # Test the TFGW layer by passing two graphs through the layer and doing backpropagation.

    class pooling_TFGW(nn.Module):
        """
        Pooling architecture using the TFGW layer.
        """

        def __init__(self, n_features, n_templates, n_template_nodes):
            """
            Pooling architecture using the TFGW layer.
            """
            super().__init__()

            self.n_features = n_features
            self.n_templates = n_templates
            self.n_template_nodes = n_template_nodes

            self.TFGW = TFGWPooling(
                self.n_templates, self.n_template_nodes, self.n_features
            )

            self.linear = Linear(self.n_templates, 1)

        def forward(self, x, edge_index):
            x = self.TFGW(x, edge_index)

            x = self.linear(x)

            return x

    torch.manual_seed(0)

    n_templates = 3
    n_template_nodes = 3
    n_nodes = 10
    n_features = 3
    n_epochs = 3

    C1 = torch.randint(0, 2, size=(n_nodes, n_nodes))
    C2 = torch.randint(0, 2, size=(n_nodes, n_nodes))

    edge_index1 = torch.stack(torch.where(C1 == 1))
    edge_index2 = torch.stack(torch.where(C2 == 1))

    x1 = torch.rand(n_nodes, n_features)
    x2 = torch.rand(n_nodes, n_features)

    graph1 = GraphData(x=x1, edge_index=edge_index1, y=torch.tensor([0.0]))
    graph2 = GraphData(x=x2, edge_index=edge_index2, y=torch.tensor([1.0]))

    dataset = DataLoader([graph1, graph2], batch_size=1)

    model_FGW = pooling_TFGW(n_features, n_templates, n_template_nodes)

    optimizer = torch.optim.Adam(model_FGW.parameters(), lr=0.01)
    criterion = torch.nn.CrossEntropyLoss()

    model_FGW.train()

    for i in range(n_epochs):
        for data in dataset:
            out = model_FGW(data.x, data.edge_index)
            loss = criterion(out, data.y)
            loss.backward()
            optimizer.step()
            optimizer.zero_grad()


@pytest.mark.skipif(not torch_geometric, reason="pytorch_geometric not installed")
def test_TFGW_variants():
    # Test the TFGW layer by passing two graphs through the layer and doing backpropagation.

    class GNN_pooling(nn.Module):
        """
        Pooling architecture using the TW layer.
        """

        def __init__(self, n_features, n_templates, n_template_nodes, pooling_layer):
            """
            Pooling architecture using the TW layer.
            """
            super().__init__()

            self.n_features = n_features
            self.n_templates = n_templates
            self.n_template_nodes = n_template_nodes

            self.TFGW = pooling_layer

            self.linear = Linear(self.n_templates, 1)

        def forward(self, x, edge_index, batch=None):
            x = self.TFGW(x, edge_index, batch=batch)

            x = self.linear(x)

            return x

    n_templates = 3
    n_template_nodes = 3
    n_nodes = 10
    n_features = 3

    torch.manual_seed(0)

    C1 = torch.randint(0, 2, size=(n_nodes, n_nodes))
    edge_index1 = torch.stack(torch.where(C1 == 1))
    x1 = torch.rand(n_nodes, n_features)
    graph1 = GraphData(x=x1, edge_index=edge_index1, y=torch.tensor([0.0]))
    batch1 = torch.tensor([1] * n_nodes)
    batch1[: n_nodes // 2] = 0

    criterion = torch.nn.CrossEntropyLoss()

    for train_node_weights in [True, False]:
        for alpha in [None, 0, 0.5]:
            for multi_alpha in [True, False]:
                model = GNN_pooling(
                    n_features,
                    n_templates,
                    n_template_nodes,
                    pooling_layer=TFGWPooling(
                        n_templates,
                        n_template_nodes,
                        n_features,
                        alpha=alpha,
                        multi_alpha=multi_alpha,
                        train_node_weights=train_node_weights,
                    ),
                )

                # predict
                out1 = model(graph1.x, graph1.edge_index)
                loss = criterion(out1, graph1.y)
                loss.backward()

                # predict on batch
                out1 = model(graph1.x, graph1.edge_index, batch1)


@pytest.mark.skipif(not torch_geometric, reason="pytorch_geometric not installed")
def test_TW_variants():
    # Test the TFGW layer by passing two graphs through the layer and doing backpropagation.

    class GNN_pooling(nn.Module):
        """
        Pooling architecture using the TW layer.
        """

        def __init__(self, n_features, n_templates, n_template_nodes, pooling_layer):
            """
            Pooling architecture using the TW layer.
            """
            super().__init__()

            self.n_features = n_features
            self.n_templates = n_templates
            self.n_template_nodes = n_template_nodes

            self.TFGW = pooling_layer

            self.linear = Linear(self.n_templates, 1)

        def forward(self, x, edge_index, batch=None):
            x = self.TFGW(x, edge_index, batch=batch)

            x = self.linear(x)

            return x

    n_templates = 3
    n_template_nodes = 3
    n_nodes = 10
    n_features = 3

    torch.manual_seed(0)

    C1 = torch.randint(0, 2, size=(n_nodes, n_nodes))
    edge_index1 = torch.stack(torch.where(C1 == 1))
    x1 = torch.rand(n_nodes, n_features)
    graph1 = GraphData(x=x1, edge_index=edge_index1, y=torch.tensor([0.0]))
    batch1 = torch.tensor([1] * n_nodes)
    batch1[: n_nodes // 2] = 0

    criterion = torch.nn.CrossEntropyLoss()

    for train_node_weights in [True, False]:
        model = GNN_pooling(
            n_features,
            n_templates,
            n_template_nodes,
            pooling_layer=TWPooling(
                n_templates,
                n_template_nodes,
                n_features,
                train_node_weights=train_node_weights,
            ),
        )

        out1 = model(graph1.x, graph1.edge_index)
        loss = criterion(out1, graph1.y)
        loss.backward()

        # predict on batch
        out1 = model(graph1.x, graph1.edge_index, batch1)


@pytest.mark.skipif(not torch_geometric, reason="pytorch_geometric not installed")
def test_TW():
    # Test the TW layer by passing two graphs through the layer and doing backpropagation.

    class pooling_TW(nn.Module):
        """
        Pooling architecture using the TW layer.
        """

        def __init__(self, n_features, n_templates, n_template_nodes):
            """
            Pooling architecture using the TW layer.
            """
            super().__init__()

            self.n_features = n_features
            self.n_templates = n_templates
            self.n_template_nodes = n_template_nodes

            self.TFGW = TWPooling(
                self.n_templates, self.n_template_nodes, self.n_features
            )

            self.linear = Linear(self.n_templates, 1)

        def forward(self, x, edge_index):
            x = self.TFGW(x, edge_index)

            x = self.linear(x)

            return x

    torch.manual_seed(0)

    n_templates = 3
    n_template_nodes = 3
    n_nodes = 10
    n_features = 3
    n_epochs = 3

    C1 = torch.randint(0, 2, size=(n_nodes, n_nodes))
    C2 = torch.randint(0, 2, size=(n_nodes, n_nodes))

    edge_index1 = torch.stack(torch.where(C1 == 1))
    edge_index2 = torch.stack(torch.where(C2 == 1))

    x1 = torch.rand(n_nodes, n_features)
    x2 = torch.rand(n_nodes, n_features)

    graph1 = GraphData(x=x1, edge_index=edge_index1, y=torch.tensor([0.0]))
    graph2 = GraphData(x=x2, edge_index=edge_index2, y=torch.tensor([1.0]))

    dataset = DataLoader([graph1, graph2], batch_size=1)

    model_W = pooling_TW(n_features, n_templates, n_template_nodes)

    optimizer = torch.optim.Adam(model_W.parameters(), lr=0.01)
    criterion = torch.nn.CrossEntropyLoss()

    model_W.train()

    for i in range(n_epochs):
        for data in dataset:
            out = model_W(data.x, data.edge_index)
            loss = criterion(out, data.y)
            loss.backward()
            optimizer.step()
            optimizer.zero_grad()