python - 仅使用矢量化操作突出显示多个零矩阵上的特定坐标

标签 python tensorflow matrix

假设有 2 5x5 稀疏矩阵相互堆叠(或 tf.zeros(2, 5, 5))。

然后假设还有一个坐标数组[[0, 2, 4, 4], [2, 0, 3, 3]],分别表示起始宽度位置,起始高度坐标的位置、结束宽度位置和结束高度位置(即每个坐标的[starting_w, starting_h, ending_w, ending_h])。

我想根据上面提到的坐标“突出显示”(2, 5, 5)稀疏形状,这样在形状的每个稀疏矩阵上,每个坐标分别被“投影”和这些坐标上有 1,其他地方有 0

例子

如前所述,我们有一个 (2, 5, 5) 稀疏形状:

[[[0. 0. 0. 0. 0.]
  [0. 0. 0. 0. 0.]
  [0. 0. 0. 0. 0.]
  [0. 0. 0. 0. 0.]
  [0. 0. 0. 0. 0.]]

 [[0. 0. 0. 0. 0.]
  [0. 0. 0. 0. 0.]
  [0. 0. 0. 0. 0.]
  [0. 0. 0. 0. 0.]
  [0. 0. 0. 0. 0.]]]

现在我们将 [[0, 2, 4, 4], [2, 0, 3, 3]] 中的每个坐标“投影”到每个稀疏矩阵上:

[[[1. 1. 1. 1. 1.]  # [0, 2, 4, 4]
  [0. 0. 0. 0. 0.]
  [1. 0. 0. 0. 0.]
  [1. 0. 0. 0. 0.]
  [1. 0. 0. 0. 0.]]

 [[1. 0. 1. 1. 0.]  # [2, 0, 3, 3]
  [1. 0. 0. 0. 0.]
  [1. 0. 0. 0. 0.]
  [1. 0. 0. 0. 0.]
  [0. 0. 0. 0. 0.]]]

注意:

上面看到的例子使用了n = 2坐标,因此生成了2矩阵,但是一般来说n必须被当作一个符号可以有任何值的张量。

问题

在高度声明性的 Tensorflow 的纯矢量化操作上可以做这样的事情吗? (不使用任何操作,如 tf.map_fntf.while 等)。

我尝试了什么:

我最初尝试过 tf.gather_nd , 但它没有明确支持切片(虽然有 some "hacks" 由于缺乏符号支持而无法工作)。我知道tf.slice旨在精确地做到这一点,但它没有明确支持上面演示的示例。

我还考虑过使用 tf.where,它可能很容易在具有单个坐标的单个数组上工作 - 但我不知道它是否支持多个坐标,如上所示。

谢谢!

最佳答案

你可以这样得到结果:

import tensorflow as tf

def make_highlights(idx, width, height, dtype=tf.bool):
    n = tf.shape(idx)[0]
    # Add two dimensions for broadcasting later
    idx = idx[:, :, np.newaxis, np.newaxis]
    # Extract coordinates
    start_w, start_h, end_w, end_h = idx[:, 0], idx[:, 1], idx[:, 2], idx[:, 3]
    # Make index arrays
    xx = tf.range(width)
    yy = tf.expand_dims(tf.range(height), 1)
    # Make first row highlighting
    h_x = tf.equal(yy, 0) & (xx > start_w) & (xx <= end_w)
    # Make first column highlighting
    h_y = tf.equal(xx, 0) & (yy >= start_h) & (yy <= end_h)
    # Make result
    return tf.cast(h_x | h_y, dtype)

with tf.Graph().as_default(), tf.Session() as sess:
    idx = tf.placeholder(tf.int32, [None, 4])
    width = tf.placeholder(tf.int32, [])
    height = tf.placeholder(tf.int32, [])
    result = make_highlights(idx, width, height, tf.float32)
    out = sess.run(result, feed_dict={idx: [[0, 2, 4, 4], [2, 0, 3, 3]],
                                      width: 5, height: 5})
    print(out)
    # [[[1. 1. 1. 1. 1.]
    #   [0. 0. 0. 0. 0.]
    #   [1. 0. 0. 0. 0.]
    #   [1. 0. 0. 0. 0.]
    #   [1. 0. 0. 0. 0.]]
    # 
    #  [[1. 0. 1. 1. 0.]
    #   [1. 0. 0. 0. 0.]
    #   [1. 0. 0. 0. 0.]
    #   [1. 0. 0. 0. 0.]
    #   [0. 0. 0. 0. 0.]]]

关于python - 仅使用矢量化操作突出显示多个零矩阵上的特定坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57480903/

相关文章:

python - 更改 django-haystack 中的默认 View

python - 如何通过 setuptools 安装支持 SSL 的 MySQL-python?

tensorflow - 将共享 GPU 内存与 TensorFlow 一起使用?

python - 如何计算神经网络模型的准确性

algorithm - 存储和读取 n 维稀疏矩阵

python - 如何为 tastypie 设置授权 header ?

python - 将字典列表转换为唯一的字典

python - 无法在 Ubuntu 中使用 setup.py 中的 Github Actions 安装 Tensorflow 2.2.0rc0

algorithm - 方阵中的最小矩形曲面 - 算法

javascript - 矩阵旋转后如何得到正确的x,y位置?