tf.keras.ops.sparsemax

Sparsemax activation function.

For each batch i, and class j, sparsemax activation function is defined as:

sparsemax(x)[i, j] = max(x[i, j] - τ(x[i, :]), 0).

x Input tensor.
axis int, axis along which the sparsemax operation is applied.

A tensor, output of sparsemax transformation. Has the same type and shape as x.

Example:

x = np.array([-1., 0., 1.])
x_sparsemax = keras.ops.sparsemax(x)
print(x_sparsemax)
array([0., 0., 1.], shape=(3,), dtype=float64)