【问题标题】:Removing or masking the I'th sub-element of a tilted tensor?删除或掩盖倾斜张量的第 i 个子元素?
【发布时间】:2017-06-10 12:19:19
【问题描述】:

我正在寻找一种使用 Tensorflow 提取所有子元素的方法,除了对应于张量索引的子元素。

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

与使用 Numpy 的 this approach 非常相似。

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

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.]]]

我也很好奇是否有更有效的方法来做到这一点,而不是创建一个大张量然后屏蔽它?

谢谢!

【问题讨论】:

    标签: python tensorflow tiling


    【解决方案1】:

    事实证明 Tensorflow 已经内置了我正在寻找的东西 :)

    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.]]]
    

    【讨论】:

      猜你喜欢
      • 2019-04-16
      • 1970-01-01
      • 1970-01-01
      • 2014-11-04
      • 1970-01-01
      • 2021-10-17
      • 2017-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多