如何使用`散播`多维张量

2024-04-19 19:56:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个新的张量(output),其中另一个张量(updates)的值根据idx张量放置。output的形状应该是[batch_size, 1, 4, 4](类似于2x2像素和一个通道的图像),并且update具有形状[batch_size, 3]。你知道吗

我已经阅读了Tensorflow文档(我正在使用gpu版本1.13.1),发现tf.scatter_nd应该可以解决我的问题。问题是我无法让它工作,我想我在理解如何安排idx时遇到了问题。你知道吗

让我们考虑一下batch_size = 2,所以我要做的是:

updates = tf.constant([[1, 2, 3], [4, 5, 6]])  # shape [2, 3]
output_shape = tf.constant([2, 1, 4, 4])
idx = tf.constant([[[1, 0], [1, 1], [1, 0]], [[0, 0], [0, 1], [0, 2]]])  # shape [2, 3, 2]
idx_expanded = tf.expand_dims(idx, 1)  # so I have shape [2, 1, 3, 2]
output = tf.scatter_nd(idx_expanded, updates, output_shape)

我希望它能工作,但它没有,它给了我一个错误:

ValueError: The outer 3 dimensions of indices.shape=[2,1,3,2] must match the outer 3 dimensions of updates.shape=[2,3]: Shapes must be equal rank, but are 3 and 2 for 'ScatterNd_7' (op: 'ScatterNd') with input shapes: [2,1,3,2], [2,3], [4]

我不明白为什么它期望updates有维度3。我认为idx必须对output_shape(这就是为什么我使用expand_dims)和updates(指定三个点的两个索引)有意义,但很明显我在这里遗漏了一些东西。你知道吗

任何帮助都将不胜感激。你知道吗


Tags: outputsizetfbatchexpand形状outershape
1条回答
网友
1楼 · 发布于 2024-04-19 19:56:12

我一直在玩弄这个函数,我发现了我的错误。如果有人面临这个问题,我就是这么解决的:

考虑batch_size=23点,idx张量必须具有[2, 3, 4]形状,其中第一维度对应于我们从中获取update值的批次,第二个维度必须等于第二个维度updates(每个批次的点数),第三个维度是4,因为我们需要4索引:[批次号,通道,行,列]。按照问题中的例子:

updates = tf.constant([[1., 2., 3.], [4., 5., 6.]])  # [2, 3]
idx = tf.constant([[[0, 0, 0, 1], [0, 0, 0, 0], [0, 0, 1, 0]], [[1, 0, 1, 1], [1, 0, 0, 0], [1, 0, 1, 0]]])  # [2, 3, 4]
output = tf.scatter_nd(idx, updates, [2, 1, 4, 4])

sess = tf.Session()
print(sess.run(output))

[[[[2. 1. 0. 0.]
   [3. 0. 0. 0.]
   [0. 0. 0. 0.]
   [0. 0. 0. 0.]]]


 [[[5. 0. 0. 0.]
   [6. 4. 0. 0.]
   [0. 0. 0. 0.]
   [0. 0. 0. 0.]]]]

这样就可以在一个新的张量中放置特定的数字。你知道吗

相关问题 更多 >