Python softmax之前的Keras掩蔽零点
假设我有来自LSTM层的以下输出Python softmax之前的Keras掩蔽零点,python,keras,softmax,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
[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 hidden的输出为批量大小504000,您可以定义自定义激活来实现它。这相当于掩码0
你说我想先屏蔽0是什么意思?是否仅对值应用softmax=0?@Vlad,是的,这就是我想做的。@Vlad:我在使用kerasGreat,你对此有答案。如果我的lstm_隐藏的大小为批次大小504000,该怎么办?我试过了,但由于自定义_激活中的形状兼容性,出现了一个错误function@Daisy我把它加到了答案上,它没有给出预期的结果。我试图用我拥有的形状更新示例,但我无法。我更新示例如下:lstm_hidden=Inputshape=3,4。。。x=np.数组[[1,0,0,1],[0,0.19,0,0,0.78],[0,0,0.01843184,0.01929785]]和Get-ValueError:无法为张量'input_1:0'输入形状3,4'的值,该张量具有形状'?,3,4'@Daisy。您可以使用tf.is__nan来防止nan值。我已经更新了我的代码。此外,输出中的nan值总是一个非常糟糕的信号。您需要重新检查数据处理或模型代码。
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. ]]