I am want to build a custom Keras layer keeping the k top activation values. I am currently doing this (and its working fine) :
def max_topk_pool(x,k):
import tensorflow as tf
k_max = tf.nn.top_k(x,k=k,sorted=True,name=None)
return k_max
def KMax(k):
return Lambda(max_topk_pool,
arguments={'k':k},
output_shape=lambda x: (None, k))
Do you know if there is a way to build a custom Layer class "KMax" in the way shown by Keras in https://keras.io/layers/writing-your-own-keras-layers/
from keras import backend as K
from keras.layers import Layer
class MyLayer(Layer):
def __init__(self, output_dim, **kwargs):
self.output_dim = output_dim
super(MyLayer, self).__init__(**kwargs)
def build(self, input_shape):
# Create a trainable weight variable for this layer.
self.kernel = self.add_weight(name='kernel',
shape=(input_shape[1], self.output_dim),
initializer='uniform',
trainable=True)
super(MyLayer, self).build(input_shape) # Be sure to call this at the end
def call(self, x):
return K.dot(x, self.kernel)
def compute_output_shape(self, input_shape):
return (input_shape[0], self.output_dim)
I would like something like this :
from keras import backend as K
from keras.layers import Layer
class KMax(Layer):
def __init__(self, output_dim, **kwargs):
self.K = K
super(MyLayer, self).__init__(**kwargs)
def build(self, input_shape):
<... Lambda here ?>
def compute_output_shape(self, input_shape):
return (input_shape[0], self.K)
Thank you very much !