gpt4 book ai didi

python - Tensorflow - 根据批处理位置进行索引

转载 作者:行者123 更新时间:2023-11-30 22:12:35 25 4
gpt4 key购买 nike

我正在研究屏蔽 r-cnn,但在根据标签索引屏蔽时遇到问题。

这就是我想要实现的目标:我有一个张量 (?,28,28,c),其中 ? 是未知的batch_size,“28x28”是二维坐标并且 c 代表不同的标签,然后我有一个 int32 的索引列表(基本上是我的标签预测)(?,)。现在我想根据批处理索引提取给定标签的掩码 -> 使其成为 (?,28,28,1) 张量。

我尝试了self.masks_sigmoid = tf.gather(self.final_conv, self.label_predictions, axis=3),但形状保持不变。

我还在这里查看了tf.gather_nd http://www.riptutorial.com/tensorflow/example/29069/how-to-use-tf-gather-nd ,我想这是正确的路径,但我不知道如何根据批量索引合并我想要的索引(在 numpy (b_i,:,:,c_i) 中)

我也感觉我的问题有点类似于Batched 4D tensor Tensorflow indexing ,尽管我的问题似乎不那么复杂。然而,就 tensorflow 的快速发展而言,这个问题已经很老了,所以我要求一个可能更好、更清晰的解决方案。编辑:即使是一个肮脏的解决方案也可能是有益的,因为我没有在链接的SO中得到问题(已经写了一条评论要求澄清问题),因此我没有从唯一的答案中得到太多。这也可能对社区有利,因为这个问题更简单,这意味着它会更清楚地展示解决方案。

最佳答案

解决方案 1:更通用

你可以看一下答案here,基本上和你的问题是一样的,只是维度不同。

那里描述的解决方案是创建一个[?, 28, 28, 4]形张量indices,其中indices[i, x, y, :] = [i, x, y, self.label_predictions[i]],然后使用tf.gather_nd:

self.masks_sigmoids = tf.gather_nd(self.final_conv, indices=indices)

构建索引并不是很优雅,如 this answer 所示(为您提供了多一个维度),但其本身很简单。

解决方案 2:更优雅并适合您的问题

此解决方案与第一个解决方案非常相似,但避免创建索引[x, y]部分。这个想法是使用gather_nd的切片功能来避免在每个(i, x, y)indices中写入[x, y] ,通过在收集数据之前转置数据。我将把整个代码放在这里,包括如何创建索引以及如何测试:

import numpy as np
import tensorflow as tf

N_CHANNELS = 5
pl=tf.placeholder(dtype=tf.int32, shape=(None, 28, 28, N_CHANNELS))

# Indices we'll use. batch_size = 4 here.
label_predictions = tf.constant([0, 2, 0, 3])

# Indices of shape [?, 2], with indices[i] = [i, self.label_predictions[i]],
# which is easy to do with tf.range() and tf.stack()
indices = tf.stack([tf.range(tf.size(label_predictions)), label_predictions], axis=-1)
# [[0, 0], [1, 2], [2, 0], [3, 3]]

transposed = tf.transpose(pl, perm=[0, 3, 1, 2])
gathered = tf.gather_nd(transposed, indices) # Should be of shape (4, 2, 3)
result = tf.expand_dims(gathered, -1)

initial_value = np.arange(4*28*28*N_CHANNELS).reshape((4, 28, 28, N_CHANNELS))
sess = tf.InteractiveSession()
res = sess.run(result, feed_dict={pl: initial_value})
# print(res)

print("checking validity")
for i in range(4):
for x in range(28):
print(x)
for y in range(28):
assert res[i, x, y, 0] == initial_value[i, x, y, indices[i, 1].eval()]
print("All assertions passed")

关于python - Tensorflow - 根据批处理位置进行索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51052203/

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