9
$\begingroup$

Consider:

input = {1, 2, 3};
mask = {1, 0, 1}

Classic Softmax:

SoftmaxLayer[]@input

{0.0900306, 0.244728, 0.665241}

Masked Softmax is something like this:

SoftmaxLayer[]@Pick[input, mask, 1]

{0.119203, 0.880797}

But zeros must be preserved:

{0.119203, 0., 0.880797}

$\endgroup$

1 Answer 1

9
$\begingroup$
MaskedSoftmax = NetGraph[
  {
   ElementwiseLayer[Exp],
   ThreadingLayer[Times],
   {SummationLayer[], ElementwiseLayer[Max[#, 10^-15] &], ReplicateLayer[Automatic]},
   ThreadingLayer[Divide]
   },
  {
   NetPort["Input"] -> 1 -> 2,
   NetPort["Mask"] -> 2,
   2 -> 3,
   {2, 3} -> 4
   }
  ]

enter image description here

MaskedSoftmax[<|"Input" -> {1, 2, 3}, "Mask" -> {1, 0, 1}|>]

{0.119203, 0., 0.880797}

MaskedSoftmax[<|"Input" -> {{1, 2, 3}, {1, 2, 3}}, "Mask" -> {{1, 0, 1}, {0, 1, 0}}|>]

{{0.119203, 0., 0.880797}, {0., 1., 0.}}

MaskedSoftmax[<|"Input" -> {{1, 2, 3}, {1, 2, 3}}, "Mask" -> {{1, 0, 1}, {0, 0, 0}}|>]

{{0.119203, 0., 0.880797}, {0., 0., 0.}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.