I have this Custom Keras Layer that chooses between elements of a list, like a Dense layer, and I want it to return the element of the list it predicted directly.
The list is a list of Keras.layers.Layer
.
I have this piece of code:
def call(self, inputs, context):
pred = tf.argmax(tf.matmul(context, self.kernel))
return self.layers[pred](inputs)
It throws an error: TypeError: list indices must be integers or slices, not Tensor
, which is understandable, but I can't find a way of making it work. The "pred" Tensor doesn't have a .numpy
property, though I'm running the program eagerly, since this happens when the layer is being built.
I understand there may be no solutions, if so, submit ideas on how I could code this layer in another way.
There is a bigger problem.
This layer will not work, because you cannot get derivatives of argmax
, the kernel
will be impossible to train. And you will get an error message like "An operation has None for gradient"
As a workaround, I'd suggest you to:
tf.stack([listf_of_outputs],axis=1)
softmax
of the result of matmul
softmax
to the same number of dimensions of the stacked result above: shape (-1, number_of_layers, _other_dims_if_exist, 1)
*
) the stacked results by the reshaped softmax and sum the axis 1.