我有一个4-D张量的形状(10,32,32,128).我想为所有前N个元素生成二进制掩码.
arr = tf.random_normal(shape=(10, 32, 32, 128))
values, indices = tf.nn.top_k(arr, N=64)
Run Code Online (Sandbox Code Playgroud)
我的问题是如何获得与arr使用indices返回的相同形状的二进制掩码tf.nn.top_k
如果有人正在寻找答案:就在这里。
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))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
868 次 |
| 最近记录: |