【发布时间】:2020-02-25 00:09:16
【问题描述】:
我正在尝试将两个张量混合在一起。 scatter_nd 非常适合这个场合,我编写了以下函数来完成我的任务。它基本上只是将 2 个 scatter_nds 广告放在一起。
def tf_munge(t, i, r, j, axis=0):
#insert tensor t at indices i and tensor r at indices j on axis `axis`.
#requires: i.shape[0] == t.shape[axis] && j.shape[0] == r.shape[axis] && t.shape[k] == r.shape[k] ∀k != axis
i = tf.expand_dims(i, -1)
j = tf.expand_dims(j, -1)
rank_indices = tf.range(tf.rank(t))
roller = tf.roll(rank_indices, -axis, 0)
rolled_t = tf.transpose(t, roller)
rolled_r = tf.transpose(r, roller)
scatter_shape = tf.concat((tf.shape(i)[0:1] + tf.shape(j)[0:1], tf.shape(rolled_t)[1:]), axis=0)
scattered = tf.scatter_nd(i, rolled_t, scatter_shape) + tf.scatter_nd(j, rolled_r, scatter_shape)
return tf.transpose(scattered, tf.roll(rank_indices, axis, 0))
它通常按预期工作。但是,只要 r 和 t 沿某个轴为空,它就会失败。我有两个代码“路径”,具体取决于一个布尔值,其中我拆分我的张量并根据该布尔值是真还是假执行不同的操作。有时,对于 0 行,该布尔值是错误的。在这种情况下,我最终会对一个空张量做一些事情。其中之一就是这种尝试的散射。该错误实际上引用了输出形状(上述代码中的scatter_shape)声称:
ValueError:为“ScatterNd_4”的空输出形状指定的索引和更新(操作:“ScatterNd”)
输入形状:[3,1]、[3,0,2]、[3],输入张量计算为部分形状:输入[2] = [5,0,2]。
请注意,空轴与我分散的轴不同。这是一个工作示例:
foo = tf.ones((3,1,2))
bar = tf.ones((2,1,2))*2
i = tf.constant([1,3,4])
j = tf.constant([0,2])
tf_munge(foo,i,bar,j,axis=0)
#Output: <tf.Tensor 'transpose_13:0' shape=(5, 1, 2) dtype=float32>
这是一个失败的例子:
foo = tf.ones((3,0,2))
bar = tf.ones((2,0,2))*2
tf_munge(foo,i,bar,j,axis=0)
#Output: The error above
这里的预期输出显然是一个形状为 (5,0,2) 的空张量。
我考虑过对输入的形状使用条件,但 tf.cond executes both pathways。当我有一个带有scatter_nd 的空张量时,我该如何处理这种情况?
【问题讨论】:
标签: python tensorflow