删除或掩盖倾斜张量的第I个子元素? [英] Removing or masking the I'th sub-element of a tilted tensor?

查看:140
本文介绍了删除或掩盖倾斜张量的第I个子元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种使用Tensorflow提取除与张量索引相对应的子元素之外的所有子元素的方法.

I am searching for a way using Tensorflow to extract all of the sub-elements except for the one corresponding to the tensor's index.

(例如,如果查看索引1,则仅存在子元素0和2)

(eg. if looking at index 1 then only sub-elements 0 and 2 are present)

非常类似于使用Numpy的此方法.

Very similar to this approach using Numpy.

下面是创建平铺张量和布尔蒙版的一些示例代码:

Here's some example code to create a tiled tensor and a boolean mask:

import tensorflow as tf
import numpy as np

_coordinates = np.array([
    [1.0, 7.0, 0.0],
    [2.0, 7.0, 0.0],
    [3.0, 7.0, 0.0],
])

verts_coord = _coordinates
n = verts_coord.shape[0]

mat_loc = tf.Variable(verts_coord)

tile = tf.tile(mat_loc, [n, 1])
tile = tf.reshape(tile, [n, n, n])

mask = tf.constant(~np.eye(n, dtype=bool))

result = tf.somefunc(tile, mask) #somehow extract only the elements where mask == true

with tf.Session() as sess:
    sess.run(tf.initialize_all_variables())
    print(sess.run(tile))
    print(sess.run(mask))

输出张量示例:

>>> print(tile)
[[[ 1.  7.  0.]
  [ 2.  7.  0.]
  [ 3.  7.  0.]]

 [[ 1.  7.  0.]
  [ 2.  7.  0.]
  [ 3.  7.  0.]]

 [[ 1.  7.  0.]
  [ 2.  7.  0.]
  [ 3.  7.  0.]]]

>>> print(mask)
[[False  True  True]
 [ True False  True]
 [ True  True False]]

所需的输出:

>>> print(result)
[[[ 2.  7.  0.]
  [ 3.  7.  0.]]

 [[ 1.  7.  0.]
  [ 3.  7.  0.]]

 [[ 1.  7.  0.]
  [ 2.  7.  0.]]]

我也很好奇,是否有比创建一个大张量然后掩盖它更有效的方法?

I am also curious if there are more efficient methods for doing this as opposed to creating a large tensor and then masking it?

谢谢!

推荐答案

结果Tensorflow完全具有我正在寻找的内置对象:)

Turns out Tensorflow had exactly what I was looking for already built in :)

result = tf.boolean_mask(tile, mask)
result = tf.reshape(result,  [n, n-1, -1])

>>> print(result)
[[[ 2.  7.  0.]
  [ 3.  7.  0.]]

 [[ 1.  7.  0.]
  [ 3.  7.  0.]]

 [[ 1.  7.  0.]
  [ 2.  7.  0.]]]

这篇关于删除或掩盖倾斜张量的第I个子元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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