Binary mask from tf.nn.top_k indices for a four-dimensional tensor in Tensorflow?

I have a 4-D form tensor (10, 32, 32, 128). I want to create a binary mask for all elements of top N.

arr = tf.random_normal(shape=(10, 32, 32, 128))
values, indices = tf.nn.top_k(arr, N=64)

My question is how to get a binary mask of the same form as arrusing indicesreturnedtf.nn.top_k

+4
source share
1 answer

If someone is looking for an answer: here it is.

K = 64
arr = tf.random_normal(shape=(10, 32, 32, 128))
values, indices = tf.nn.top_k(arr, k=K, sorted=False)

temp_indices = tf.meshgrid(*[tf.range(d) for d in (tf.unstack(
       tf.shape(arr)[:(arr.get_shape().ndims - 1)]) + [K])], indexing='ij')
temp_indices = tf.stack(temp_indices[:-1] + [indices], axis=-1)
full_indices = tf.reshape(temp_indices, [-1, arr.get_shape().ndims])
values = tf.reshape(values, [-1])

mask_st = tf.SparseTensor(indices=tf.cast(
      full_indices, dtype=tf.int64), values=tf.ones_like(values), dense_shape=arr.shape)
mask = tf.sparse_tensor_to_dense(tf.sparse_reorder(mask_st))
0
source

Source: https://habr.com/ru/post/1674370/


All Articles