损失函数中的Tensorflow切片

问题描述 投票:1回答:1

我目前正在Tensorflow中实现一个函数,该函数会随机采样给定Tensor的128D向量。

所以我采样了n = 400个值:

x1 = tf.random.uniform((n,), minval=border, maxval=W-border)

然后复制张量的值,使我在张量中具有400 * Batch_size(B)值:

x1a = x1[None,:] #(1, 400)
x1b = tf.broadcast_to(x1a,(B,n)) #(4,400)
x1 = tf.reshape(x1b, [-1]) # (1600)

并且我对y坐标重复该步骤,然后将类似的函数应用于Batch_size:

b1 = tf.range(B)
b1 = b1[:,None]
b1 = tf.broadcast_to(b1,(B,n))
b1 = tf.reshape(b1, [-1])

最后我将张量转换为int32:

b1 = tf.cast(b1, tf.int32)
x1 = tf.cast(x1, tf.int32)
y1 = tf.cast(y1, tf.int32)

现在,我要从我的损失函数中从网络输出((无,512,512,128))中提取这些“随机” 128D:

feat1 = feat1[b1, x1, y1, :]

但是,这会向我抛出以下错误消息:

TypeError: Only integers, slices (`:`), ellipsis (`...`), tf.newaxis (`None`) and scalar tf.int32/tf.int64 tensors are valid indices, got <tf.Tensor 'loss_30/ap_loss_concat_loss/Reshape_10:0' shape=(1600,) dtype=int32>

AFAIK,这种张量切片可以在numpy中使用,但我不确定Tensorflow中是否也可以使用,我的搜索显示tf.gather_nd可以用于此类操作。

有人可以告诉我如何正确执行此操作吗?

python tensorflow
1个回答
0
投票

您几乎正确,只需要这样做:

feat1 = tf.gather_nd(feat1, tf.stack([b1, x1, y1], axis=-1))

如果要获得具有[B, 400, 128]形状的张量的结果,可以在之后对其进行重塑,但也可以对indicestf.gather_nd参数进行塑形:

tf.gather_nd

作为附带说明,请注意,您可以将idx = tf.reshape(tf.stack([b1, x1, y1], axis=-1), [B, n, 3]) feat1 = tf.gather_nd(feat1, idx) 传递给dtype=tf.int32以直接生成整数随机值。

© www.soinside.com 2019 - 2024. All rights reserved.