Keras在softmax之前掩盖零

时间:2019-05-10 13:16:46

标签: python keras softmax

假设我从LSTM层获得以下输出

[0.         0.         0.         0.         0.01843184 0.01929785 0.         0.         0.         0.         0.         0. ]

我想在此输出上应用softmax,但我想先屏蔽0。

当我使用

mask = Masking(mask_value=0.0)(lstm_hidden)
combined = Activation('softmax')(mask)

它没有用。有什么想法吗?

更新:隐藏的LSTM输出为(batch_size, 50, 4000)

1 个答案:

答案 0 :(得分:0)

您可以定义自定义激活来实现。这等效于掩码0

from keras.layers import Activation,Input
import keras.backend as K
from keras.utils.generic_utils import get_custom_objects
import numpy as np
import tensorflow as tf

def custom_activation(x):
    x = K.switch(tf.is_nan(x), K.zeros_like(x), x) # prevent nan values
    x = K.switch(K.equal(K.exp(x),1),K.zeros_like(x),K.exp(x))
    return x/K.sum(x,axis=-1,keepdims=True)

lstm_hidden = Input(shape=(12,))
get_custom_objects().update({'custom_activation': Activation(custom_activation)})
combined = Activation(custom_activation)(lstm_hidden)

x = np.array([[0.,0.,0.,0.,0.01843184,0.01929785,0.,0.,0.,0.,0.,0. ]])
with K.get_session()as sess:
    print(combined.eval(feed_dict={lstm_hidden:x}))

[[0.         0.         0.         0.         0.49978352 0.50021654
  0.         0.         0.         0.         0.         0.        ]]