我想构建一个自定义Keras层,保留k个顶部激活值。我目前正在这样做(并且工作正常):
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))
您是否知道是否可以按照Keras在https://keras.io/layers/writing-your-own-keras-layers/中展示的方式来构建自定义Layer类“ KMax”
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)
我想要这样的东西:
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)
非常感谢您!
答案 0 :(得分:3)
这里是您所需要的(基于https://github.com/keras-team/keras/issues/373):
g2: 8 pointer size
g2: 280 10 * 7 * int size