theano 中的蒙面 softmax

masked softmax in theano

我想知道是否可以在表演前敷面膜theano.tensor.nnet.softmax?

这是我正在寻找的行为:

>>>a = np.array([[1,2,3,4]])
>>>m = np.array([[1,0,1,0]]) # ignore index 1 and 3
>>>theano.tensor.nnet.softmax(a,m)
array([[ 0.11920292,  0. ,  0.88079708,  0.  ]])

请注意 am 是矩阵,所以我希望 softmax 对整个矩阵进行处理并执行逐行掩码 softmax。

此外,输出应与 a 的形状相同,因此解决方案无法进行高级索引,例如theano.tensor.softmax(a[0,[0,2]])

theano.tensor.switch 是一种方法。

在计算图中,您可以执行以下操作:

a_mask = theano.tensor.switch(m, a, np.NINF)
sm = theano.tensor.softmax(a_mask)

希望对其他人有所帮助。

def masked_softmax(a, m, axis):
    e_a = T.exp(a)
    masked_e = e_a * m
    sum_masked_e = T.sum(masked_e, axis, keepdims=True)
    return masked_e / sum_masked_e