【问题标题】:Keras masking zero before softmaxKeras 在 softmax 之前屏蔽零
【发布时间】:2019-05-10 13:16:46
【问题描述】:

假设我有来自 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)

【问题讨论】:

  • I want to mask 0's first 是什么意思?是否仅对值 !=0 应用 softmax
  • @Vlad,是的,这就是我想要做的。
  • @Vlad:我正在使用 keras
  • 太好了,你有答案了。

标签: python keras softmax


【解决方案1】:

您可以定义自定义激活来实现它。这相当于掩码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.        ]]

【讨论】:

  • 如果我的 lstm_hidden 大小为 (batch_size,50,4000) 怎么办?我试过了,但由于 custom_activation 函数中的形状兼容性而出现错误
  • @Daisy 我将其添加到答案中。
  • 它没有给出预期的结果。我试图用我拥有的形状更新示例,但我做不到。
  • 我将示例更新如下:lstm_hidden = Input(shape=(3,4)) ... x =np.array([[1, 0, 0,1],[0,0.19, 0, 0.78],[0,0,0.01843184,0.01929785]]) 并得到了ValueError: Cannot feed value of shape (3, 4) for Tensor 'input_1:0', which has shape '(?, 3, 4)'
  • @Daisy 您可以使用tf.is_nan 来阻止nan 值。我已经更新了我的代码。此外,输出中的nan 值始终是一个非常糟糕的信号。您需要重新检查您的数据处理或模型代码。
猜你喜欢
  • 1970-01-01
  • 2019-10-13
  • 2021-03-03
  • 2018-08-15
  • 2020-08-31
  • 1970-01-01
  • 2021-09-18
  • 1970-01-01
  • 2016-10-15
相关资源
最近更新 更多