I want to write a custom layer that applies a dense layer and then some specified functions to the output of that computation. I want to specify the functions that are applied to the individual outputs in a list, such that I can easily change them.
I'm trying to apply the functions inside a tf.while_loop, but I don't know how to access and write to the individual elements of dense_output_nodes.
dense_output_nodes[i] = ... doesn't work as it tells me that
TypeError: 'Tensor' object does not support item assignment
So I tried to tf.unstack before, which is the code below, but now when creating the layer with hidden_1 = ArithmeticLayer(unit_types=['id', 'sin', 'cos'])(inputs), I get the error that
TypeError: list indices must be integers or slices, not Tensor
because apparently TensorFlow converts i from tf.constant to tf.Tensor.
By now, I'm really struggling to see ways I can fix this. Is there some way I can get this to work?
Or should I build the whole ArithmeticLayer as a combination of a Dense layer and a Lambda layer applying the custom functions?
class ArithmeticLayer(layers.Layer):
# u = number of units
def __init__(self, name=None, regularizer=None, unit_types=['id', 'sin', 'cos']):
self.regularizer=regularizer
super().__init__(name=name)
self.u = len(unit_types)
self.u_types = unit_types
def build(self, input_shape):
self.w = self.add_weight(shape=(input_shape[-1], self.u),
initializer='random_normal',
regularizer=self.regularizer,
trainable=True)
self.b = self.add_weight(shape=(self.u,),
initializer='random_normal',
regularizer=self.regularizer,
trainable=True)
def call(self, inputs):
# get the output nodes of the dense layer as a list
dense_output_nodes = tf.matmul(inputs, self.w) + self.b
dense_output_list = tf.unstack(dense_output_nodes, axis=1)
# apply the function units
i = tf.constant(0)
def c(i):
return tf.less(i, self.u)
def b(i):
dense_output_list[i] = tf.cond(self.u_types[i] == 'sin',
lambda: tf.math.sin(dense_output_list[i]),
lambda: dense_output_list[i]
)
dense_output_list[i] = tf.cond(self.u_types[i] == 'cos',
lambda: tf.math.cos(dense_output_list[i]),
lambda: dense_output_list[i]
)
return (tf.add(i, 1), )
[i] = tf.while_loop(c, b, [i])
final_output_nodes = tf.stack(dense_output_list, axis=1)
return final_output_nodes
Thanks for any suggestions!