gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:53:24 24 4
gpt4 key购买 nike

假设有 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com