首页 > 解决方案 > TensorFlow 收集索引并展开

问题描述

我有一个[batch, num_objs, vals]or (16, 4, 10)tensor y,其中y[:,:,:2](row, col) 索引进入 a [batch, rows, cols, num_objs, vals]or [16, 40, 60, 2, 10]tensor y'。现在每个y[i,:,:2]可能都有完全相同的(行,列)索引,或者它们可能都是唯一的。我想y根据y'来自y[:,:,:2]. num_objs如果超过 2 个映射到同一个网格单元,我会将维度从 4 减少到 2 并丢弃 1 或 2 个向量。

感谢这个答案https://stackoverflow.com/a/61056074/3614578我有一个基于y[:,:,:2]. 这是我所拥有的

true_grid_coords = y[:,:,:2] // params.grid_stride
true_grid_vals = tf.concat([true_grid_coords, y[:,:,2:]], axis=2)
s1 = tf.shape(true_grid_coords, out_type=true_grid_coords.dtype)
b = tf.range(s1[0])
# Repeat batch index for each object
b = tf.repeat(b, s1[1]) # (64) 16 times num_obj
# Concatenate with row and column indices - (64, 1) concat (64, 2) = (64, 3), b is first col, true coords second, third col
# vals in first col(each batch index 0-15) repeated 4 times from repeat function
idx = tf.concat([tf.expand_dims(b, 1), tf.reshape(true_grid_coords, [-1, s1[2]])], axis=1)
s2 = tf.shape(y\')
# I want to index into first 3 dims of s2 and expand by adding (4, 10) tensor from indexing into y[:,:,:2]
true_grid_vals = tf.scatter_nd(idx, y, s2[:3])

我需要在从中提取整个长度为 10 个向量时使用idx索引到行和列中[batch, rows, cols, num_objs, vals]以及行列中。向量的数量可以并且将在 0 到 4 之间。 可以截断或扩展为 2 ( ),如果没有匹配项或 1 个匹配项,则其他向量可以全为零。然后将该张量附加到适当(行,列)处的张量。我怎么能这样做?这有意义吗?y[:,:,:2]ymatchMatchnum_objs(num_objs, 10)[batch, rows, cols, num_objs, vals]y'

例如,i批次中的一个样本y[i]是 [4, 10] 形张量

[1, 5, ....]
[30, 20, ....]
[37, 51, ....]
[37, 51, ....]

每行中的前 2 个数字可以用作形状张量的第一维和第二维的索引,[16, 40, 60, 2, 10]称为y'. 我想根据上面行[16, 40, 60, 2, 10]中的前 2 个数字和适当的批处理索引将上面的每一行映射到张量中i。在上面的批处理示例中i,2 个向量将映射到[i, 37, 51,:,:],一个向量映射到 ,一个映射[i, 30, 20,0,:][i, 1, 5,0,:]。中的每个其他值y'[i,:,:,:,:]都是 0。如果上面有 3 行带有坐标[37, 51, ...],则其中一个将被丢弃。

标签: pythontensorflow

解决方案


推荐阅读