带有选定索引的tensorflow掩码框 [英] tensorflow mask boxes with selected indices

查看:119
本文介绍了带有选定索引的tensorflow掩码框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个2级张量 A [[1,1,1,1], [2,2,2,2],[3,3,3,3], [4, 4, 4, 4], ...],并且有一个选定的索引 B (来自tf.equal()或其他地方),例如.我想使 B 中任何 i A [i] 都为零,以便 A 最终变成类似[1,1,1,1], [0,0,0,0],[3,3,3,3], [0,0,0,0], ...].怎么做或有可能吗?

Suppose I have a rank-2 tensor A [[1,1,1,1], [2,2,2,2],[3,3,3,3], [4, 4, 4, 4], ...], and I have a selected indices B (from tf.equal() or somewhere else) such as [1, 3, 4] . I want to make A[i] all zero for any i in B so that A eventually becomes something like [1,1,1,1], [0,0,0,0],[3,3,3,3], [0,0,0,0], ...]. How to do that or is that possible?

推荐答案

有多种方法可以做到这一点.这是带有 tf.one_hot() (经过测试的代码)的代码:

There are multiple ways to do that. Here's one with tf.one_hot() (tested code):

import tensorflow as tf

a = tf.constant( [[1,1,1,1], [2,2,2,2],[3,3,3,3], [4, 4, 4, 4]] )
b = tf.constant( [ 1, 3, 4 ] )

one_hot = tf.one_hot( b, a.get_shape()[ 0 ].value, dtype = a.dtype )
mask = 1 - tf.reduce_sum( one_hot, axis = 0 )
res = a * mask[ ..., None ]

with tf.Session() as sess:
    print( sess.run( res ) )

或带有 tf.scatter_nd() (经测试的代码)的代码:

or this one with tf.scatter_nd() (tested code):

import tensorflow as tf

a = tf.constant( [[1,1,1,1], [2,2,2,2], [3,3,3,3], [4, 4, 4, 4]] )
b = tf.constant( [ 1, 3 ] )

mask = 1 - tf.scatter_nd( b[ ..., None ], tf.ones_like( b ), shape = [ a.get_shape()[ 0 ].value ] )
res = a * mask[ ..., None ]

with tf.Session() as sess:
    print( sess.run( res ) )

都将输出:

[[1 1 1 1]
[0 0 0 0]
[3 3 3 3]
[0 0 0 0]]

[[1 1 1 1]
[0 0 0 0]
[3 3 3 3]
[0 0 0 0]]

根据需要.

这篇关于带有选定索引的tensorflow掩码框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆