forked from aimat-lab/gcnn_keras
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_make.py
231 lines (203 loc) · 10.6 KB
/
_make.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
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
import tensorflow as tf
from kgcnn.layers.casting import ChangeTensorType
from ._gin_conv import GIN, GINE
from kgcnn.layers.modules import Dense, OptionalInputEmbedding
from kgcnn.layers.mlp import GraphMLP, MLP
from kgcnn.layers.pooling import PoolingNodes
from kgcnn.model.utils import update_model_kwargs
ks = tf.keras
# Keep track of model version from commit date in literature.
# To be updated if model is changed in a significant way.
__model_version__ = "2022.11.25"
# Implementation of GIN in `tf.keras` from paper:
# How Powerful are Graph Neural Networks?
# Keyulu Xu, Weihua Hu, Jure Leskovec, Stefanie Jegelka
# https://arxiv.org/abs/1810.00826
model_default = {
"name": "GIN",
"inputs": [{"shape": (None,), "name": "node_attributes", "dtype": "float32", "ragged": True},
{"shape": (None, 2), "name": "edge_indices", "dtype": "int64", "ragged": True}],
"input_embedding": {"node": {"input_dim": 95, "output_dim": 64}},
"gin_mlp": {"units": [64, 64], "use_bias": True, "activation": ["relu", "linear"],
"use_normalization": True, "normalization_technique": "graph_batch"},
"gin_args": {},
"depth": 3, "dropout": 0.0, "verbose": 10,
"last_mlp": {"use_bias": [True, True, True], "units": [64, 64, 64],
"activation": ["relu", "relu", "linear"]},
"output_embedding": 'graph', "output_to_tensor": True,
"output_mlp": {"use_bias": True, "units": 1,
"activation": "softmax"}
}
@update_model_kwargs(model_default)
def make_model(inputs: list = None,
input_embedding: dict = None,
depth: int = None,
gin_args: dict = None,
gin_mlp: dict = None,
last_mlp: dict = None,
dropout: float = None,
name: str = None,
verbose: int = None,
output_embedding: str = None,
output_to_tensor: bool = None,
output_mlp: dict = None
):
r"""Make `GIN <https://arxiv.org/abs/1810.00826>`_ graph network via functional API.
Default parameters can be found in :obj:`kgcnn.literature.GIN.model_default`.
Inputs:
list: `[node_attributes, edge_indices]`
- node_attributes (tf.RaggedTensor): Node attributes of shape `(batch, None, F)` or `(batch, None)`
using an embedding layer.
- edge_indices (tf.RaggedTensor): Index list for edges of shape `(batch, None, 2)`.
Outputs:
tf.Tensor: Graph embeddings of shape `(batch, L)` if :obj:`output_embedding="graph"`.
Args:
inputs (list): List of dictionaries unpacked in :obj:`tf.keras.layers.Input`. Order must match model definition.
input_embedding (dict): Dictionary of embedding arguments for nodes etc. unpacked in :obj:`Embedding` layers.
depth (int): Number of graph embedding units or depth of the network.
gin_args (dict): Dictionary of layer arguments unpacked in :obj:`GIN` convolutional layer.
gin_mlp (dict): Dictionary of layer arguments unpacked in :obj:`MLP` for convolutional layer.
last_mlp (dict): Dictionary of layer arguments unpacked in last :obj:`MLP` layer before output or pooling.
dropout (float): Dropout to use.
name (str): Name of the model.
verbose (int): Level of print output.
output_embedding (str): Main embedding task for graph network. Either "node", "edge" or "graph".
output_to_tensor (bool): Whether to cast model output to :obj:`tf.Tensor`.
output_mlp (dict): Dictionary of layer arguments unpacked in the final classification :obj:`MLP` layer block.
Defines number of model outputs and activation.
Returns:
:obj:`tf.keras.models.Model`
"""
# Make input
assert len(inputs) == 2
node_input = ks.layers.Input(**inputs[0])
edge_index_input = ks.layers.Input(**inputs[1])
# Embedding, if no feature dimension
n = OptionalInputEmbedding(**input_embedding['node'],
use_embedding=len(inputs[0]['shape']) < 2)(node_input)
edi = edge_index_input
# Model
# Map to the required number of units.
n_units = gin_mlp["units"][-1] if isinstance(gin_mlp["units"], list) else int(gin_mlp["units"])
n = Dense(n_units, use_bias=True, activation='linear')(n)
list_embeddings = [n]
for i in range(0, depth):
n = GIN(**gin_args)([n, edi])
n = GraphMLP(**gin_mlp)(n)
list_embeddings.append(n)
# Output embedding choice
if output_embedding == "graph":
out = [PoolingNodes()(x) for x in list_embeddings] # will return tensor
out = [MLP(**last_mlp)(x) for x in out]
out = [ks.layers.Dropout(dropout)(x) for x in out]
out = ks.layers.Add()(out)
out = MLP(**output_mlp)(out)
elif output_embedding == "node": # Node labeling
out = n
out = GraphMLP(**last_mlp)(out)
out = GraphMLP(**output_mlp)(out)
if output_to_tensor: # For tf version < 2.8 cast to tensor below.
out = ChangeTensorType(input_tensor_type='ragged', output_tensor_type="tensor")(out)
else:
raise ValueError("Unsupported output embedding for mode `GIN`")
model = ks.models.Model(inputs=[node_input, edge_index_input], outputs=out)
model.__kgcnn_model_version__ = __model_version__
return model
model_default_edge = {
"name": "GIN",
"inputs": [{"shape": (None,), "name": "node_attributes", "dtype": "float32", "ragged": True},
{"shape": (None,), "name": "edge_attributes", "dtype": "float32", "ragged": True},
{"shape": (None, 2), "name": "edge_indices", "dtype": "int64", "ragged": True}],
"input_embedding": {"node": {"input_dim": 95, "output_dim": 64},
"edge": {"input_dim": 5, "output_dim": 64}},
"gin_mlp": {"units": [64, 64], "use_bias": True, "activation": ["relu", "linear"],
"use_normalization": True, "normalization_technique": "graph_batch"},
"gin_args": {"epsilon_learnable": False},
"depth": 3, "dropout": 0.0, "verbose": 10,
"last_mlp": {"use_bias": [True, True, True], "units": [64, 64, 64],
"activation": ["relu", "relu", "linear"]},
"output_embedding": 'graph', "output_to_tensor": True,
"output_mlp": {"use_bias": True, "units": 1,
"activation": "softmax"}
}
@update_model_kwargs(model_default_edge)
def make_model_edge(inputs: list = None,
input_embedding: dict = None,
depth: int = None,
gin_args: dict = None,
gin_mlp: dict = None,
last_mlp: dict = None,
dropout: float = None,
name: str = None,
verbose: int = None,
output_embedding: str = None,
output_to_tensor: bool = None,
output_mlp: dict = None
):
r"""Make `GINE <https://arxiv.org/abs/1905.12265>`_ graph network via functional API.
Default parameters can be found in :obj:`kgcnn.literature.GIN.model_default_edge`.
Inputs:
list: `[node_attributes, edge_attributes, edge_indices]`
- node_attributes (tf.RaggedTensor): Node attributes of shape `(batch, None, F)` or `(batch, None)`
using an embedding layer.
- edge_attributes (tf.RaggedTensor): Edge attributes of shape `(batch, None, F)` or `(batch, None)`
using an embedding layer.
- edge_indices (tf.RaggedTensor): Index list for edges of shape `(batch, None, 2)`.
Outputs:
tf.Tensor: Graph embeddings of shape `(batch, L)` if :obj:`output_embedding="graph"`.
Args:
inputs (list): List of dictionaries unpacked in :obj:`tf.keras.layers.Input`. Order must match model definition.
input_embedding (dict): Dictionary of embedding arguments for nodes etc. unpacked in :obj:`Embedding` layers.
depth (int): Number of graph embedding units or depth of the network.
gin_args (dict): Dictionary of layer arguments unpacked in :obj:`GIN` convolutional layer.
gin_mlp (dict): Dictionary of layer arguments unpacked in :obj:`MLP` for convolutional layer.
last_mlp (dict): Dictionary of layer arguments unpacked in last :obj:`MLP` layer before output or pooling.
dropout (float): Dropout to use.
name (str): Name of the model.
verbose (int): Level of print output.
output_embedding (str): Main embedding task for graph network. Either "node", "edge" or "graph".
output_to_tensor (bool): Whether to cast model output to :obj:`tf.Tensor`.
output_mlp (dict): Dictionary of layer arguments unpacked in the final classification :obj:`MLP` layer block.
Defines number of model outputs and activation.
Returns:
:obj:`tf.keras.models.Model`
"""
# Make input
assert len(inputs) == 3
node_input = ks.layers.Input(**inputs[0])
edge_input = ks.layers.Input(**inputs[1])
edge_index_input = ks.layers.Input(**inputs[2])
# Make input embedding, if no feature dimension
n = OptionalInputEmbedding(**input_embedding['node'],
use_embedding=len(inputs[0]['shape']) < 2)(node_input)
ed = OptionalInputEmbedding(**input_embedding['edge'],
use_embedding=len(inputs[1]['shape']) < 2)(edge_input)
edi = edge_index_input
# Model
# Map to the required number of units.
n_units = gin_mlp["units"][-1] if isinstance(gin_mlp["units"], list) else int(gin_mlp["units"])
n = Dense(n_units, use_bias=True, activation='linear')(n)
ed = Dense(n_units, use_bias=True, activation='linear')(ed)
list_embeddings = [n]
for i in range(0, depth):
n = GINE(**gin_args)([n, edi, ed])
n = GraphMLP(**gin_mlp)(n)
list_embeddings.append(n)
# Output embedding choice
if output_embedding == "graph":
out = [PoolingNodes()(x) for x in list_embeddings] # will return tensor
out = [MLP(**last_mlp)(x) for x in out]
out = [ks.layers.Dropout(dropout)(x) for x in out]
out = ks.layers.Add()(out)
out = MLP(**output_mlp)(out)
elif output_embedding == "node": # Node labeling
out = n
out = GraphMLP(**last_mlp)(out)
out = GraphMLP(**output_mlp)(out)
if output_to_tensor: # For tf version < 2.8 cast to tensor below.
out = ChangeTensorType(input_tensor_type='ragged', output_tensor_type="tensor")(out)
else:
raise ValueError("Unsupported output embedding for mode `GIN`")
model = ks.models.Model(inputs=[node_input, edge_input, edge_index_input], outputs=out)
model.__kgcnn_model_version__ = __model_version__
return model