Keras masking zero before softmax

自作多情 提交于 2020-01-06 07:58:22

问题


Suppose that I have the following output from an LSTM layer

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

and I want to apply softmax on this output but I want to mask the 0's first.

When I used

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

It didnt work. Any ideas?

Update: The output from the LSTM hidden is (batch_size, 50, 4000)


回答1:


You can define custom activation to achieve it. This is equivalent to mask 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.        ]]


来源:https://stackoverflow.com/questions/56078515/keras-masking-zero-before-softmax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!