-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathnode.py
More file actions
277 lines (223 loc) · 8.17 KB
/
Copy pathnode.py
File metadata and controls
277 lines (223 loc) · 8.17 KB
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
"""This module provides the available node types to build a ``KSearchSpace``.
"""
import tensorflow as tf
import deephyper.core.exceptions
from deephyper.nas.operation import Operation
class Node:
"""Represents a node of a ``KSearchSpace``.
Args:
name (str): node name.
"""
# Number of 'Node' instances created
num = 0
def __init__(self, name="", *args, **kwargs):
Node.num += 1
self._num = Node.num
self._tensor = None
self.name = name
def __str__(self):
return f"{self.name}[id={self._num}]"
@property
def id(self):
return self._num
@property
def op(self):
raise NotImplementedError
def create_tensor(self, *args, **kwargs):
raise NotImplementedError
@staticmethod
def verify_operation(op):
if isinstance(op, Operation):
return op
elif isinstance(op, tf.keras.layers.Layer):
return Operation(op)
else:
raise RuntimeError(
f"Can't add this operation '{op.__name__}'. An operation should be either of type Operation or tf.keras.layers.Layer when is of type: {type(op)}"
)
class OperationNode(Node):
def __init__(self, name="", *args, **kwargs):
super().__init__(name=name, *args, **kwargs)
def create_tensor(self, inputs=None, train=True, seed=None, **kwargs):
if self._tensor is None:
if inputs is None:
try:
self._tensor = self.op(train=train, seed=None)
except TypeError:
raise RuntimeError(
f'Verify if node: "{self}" has incoming connexions!'
)
else:
self._tensor = self.op(inputs, train=train)
return self._tensor
class VariableNode(OperationNode):
"""This class represents a node of a graph where you have a set of possible operations. It means the agent will have to act to choose one of these operations.
>>> import tensorflow as tf
>>> from deephyper.nas.space.node import VariableNode
>>> vnode = VariableNode("VNode1")
>>> from deephyper.nas.space.op.op1d import Dense
>>> vnode.add_op(Dense(
... units=10,
... activation=tf.nn.relu))
>>> vnode.num_ops
1
>>> vnode.add_op(Dense(
... units=1000,
... activation=tf.nn.tanh))
>>> vnode.num_ops
2
>>> vnode.set_op(0)
>>> vnode.op.units
10
Args:
name (str): node name.
"""
def __init__(self, name=""):
super().__init__(name=name)
self._ops = list()
self._index = None
def __str__(self):
if self._index is not None:
return f"{super().__str__()}(Variable[{str(self.op)}])"
else:
return f"{super().__str__()}(Variable[?])"
def add_op(self, op):
self._ops.append(self.verify_operation(op))
@property
def num_ops(self):
return len(self._ops)
def set_op(self, index):
self.get_op(index).init(self)
def get_op(self, index):
assert "float" in str(type(index)) or "int" in str(
type(index)
), f"found type is : {type(index)}"
if "float" in str(type(index)):
self._index = self.denormalize(index)
else:
assert 0 <= index and index < len(
self._ops
), f"Number of possible operations is: {len(self._ops)}, but index given is: {index} (index starts from 0)!"
self._index = index
return self.op
def denormalize(self, index):
"""Denormalize a normalized index to get an absolute indexes. Useful when you want to compare the number of different search_spaces.
Args:
indexes (float|int): a normalized index.
Returns:
int: An absolute indexes corresponding to the operation choosen with the relative index of `index`.
"""
if type(index) is int:
return index
else:
assert 0.0 <= index and index <= 1.0
res = int(index * len(self._ops))
if index == 1.0:
res -= 1
return res
@property
def op(self):
if len(self._ops) == 0:
raise RuntimeError("This VariableNode doesn't have any operation yet.")
elif self._index is None:
raise RuntimeError(
'This VariableNode doesn\'t have any set operation, please use "set_op(index)" if you want to set one'
)
else:
return self._ops[self._index]
@property
def ops(self):
return self._ops
class ConstantNode(OperationNode):
"""A ConstantNode represents a node with a fixed operation. It means the agent will not make any new decision for this node. The common use case for this node is to add a tensor in the graph.
>>> import tensorflow as tf
>>> from deephyper.nas.space.node import ConstantNode
>>> from deephyper.nas.space.op.op1d import Dense
>>> cnode = ConstantNode(op=Dense(units=100, activation=tf.nn.relu), name='CNode1')
>>> cnode.op
Dense_100_relu
Args:
op (Operation, optional): operation to fix for this node. Defaults to None.
name (str, optional): node name. Defaults to ``''``.
"""
def __init__(self, op=None, name="", *args, **kwargs):
super().__init__(name=name)
if op is not None:
op = self.verify_operation(op)
op.init(self) # set operation
self._op = op
def set_op(self, op):
op = self.verify_operation(op)
op.init(self)
self._op = op
def __str__(self):
return f"{super().__str__()}(Constant[{str(self.op)}])"
@property
def op(self):
return self._op
class MirrorNode(OperationNode):
"""A MirrorNode is a node which reuse an other, it enable the reuse of tf.keras layers. This node will not add operations to choose.
Args:
node (Node): The targeted node to mirror.
>>> from deephyper.nas.space.node import VariableNode, MirrorNode
>>> from deephyper.nas.space.op.op1d import Dense
>>> vnode = VariableNode()
>>> vnode.add_op(Dense(10))
>>> vnode.add_op(Dense(20))
>>> mnode = MirrorNode(vnode)
>>> vnode.set_op(0)
>>> vnode.op
Dense_10
>>> mnode.op
Dense_10
"""
def __init__(self, node):
super().__init__(name=f"Mirror[{str(node)}]")
self._node = node
@property
def op(self):
return self._node.op
class MimeNode(OperationNode):
"""A MimeNode is a node which reuse an the choice made for an VariableNode, it enable the definition of a Cell based search_space. This node reuse the operation from the mimed VariableNode but only the choice made.
Args:
node (VariableNode): the VariableNode to mime.
>>> from deephyper.nas.space.node import VariableNode, MimeNode
>>> from deephyper.nas.space.op.op1d import Dense
>>> vnode = VariableNode()
>>> vnode.add_op(Dense(10))
>>> vnode.add_op(Dense(20))
>>> mnode = MimeNode(vnode)
>>> mnode.add_op(Dense(30))
>>> mnode.add_op(Dense(40))
>>> vnode.set_op(0)
>>> vnode.op
Dense_10
>>> mnode.op
Dense_30
"""
def __init__(self, node, name=""):
super().__init__(name=f"Mime[{name}][src={str(node)}]")
self.node = node
self._ops = list()
def add_op(self, op):
self._ops.append(self.verify_operation(op))
@property
def num_ops(self):
return len(self._ops)
def set_op(self):
if self.node._index is None:
raise deephyper.core.exceptions.DeephyperRuntimeError(
f"{str(self)} cannot be initialized because its source {str(self.node)} is not initialized!"
)
self._ops[self.node._index].init(self)
@property
def op(self):
if self.num_ops != self.node.num_ops:
raise deephyper.core.exceptions.DeephyperRuntimeError(
f"{str(self)} and {str(self.node)} should have the same number of opertions, when {str(self)} has {self.num_ops} and {str(self.node)} has {self.node.num_ops}!"
)
else:
return self._ops[self.node._index]
@property
def ops(self):
return self._ops