在张量流中的单个轴上使用指定的切片进行局部归约



我正在尝试在 2D 数组的单个轴上使用指定的切片执行局部归约。

我使用 numpy 的numpy.ufunc.reduceatnumpy.add.reduceat实现了这一目标,但我想在 tensorflow 中做同样的事情,因为此 reduce 操作的输入是 tensorflow 卷积的输出。

我遇到了tf.math.reduce_sum但我不确定如何在我的情况下使用它。

如果我能在 tensorflow 中执行reduceat操作,那就太好了,因为我可以利用 GPU。

您可以使用tf.math.segment_sum执行几乎相同的操作:

import tensorflow as tf
import numpy as np
def add_reduceat_tf(a, indices, axis=0):
a = tf.convert_to_tensor(a)
indices = tf.convert_to_tensor(indices)
# Transpose if necessary
transpose = not (isinstance(axis, int) and axis == 0)
if transpose:
axis = tf.convert_to_tensor(axis)
ndims = tf.cast(tf.rank(a), axis.dtype)
a = tf.transpose(a, tf.concat([[axis], tf.range(axis),
tf.range(axis + 1, ndims)], axis=0))
# Make segment ids
r = tf.range(tf.shape(a, out_type=indices.dtype)[0])
segments = tf.searchsorted(indices, r, side='right')
# Compute segmented sum and discard first unused segment
out = tf.math.segment_sum(a, segments)[1:]
# Transpose back if necessary
if transpose:
out = tf.transpose(out, tf.concat([tf.range(1, axis + 1), [0],
tf.range(axis + 1, ndims)], axis=0))
return out
# Test
np.random.seed(0)
a = np.random.rand(5, 10).astype(np.float32)
indices = [2, 4, 7]
axis = 1
# NumPy computation
out_np = np.add.reduceat(a, indices, axis=axis)
# TF computation
with tf.Graph().as_default(), tf.Session() as sess:
out = add_reduceat_tf(a, indices, axis=axis)
out_tf = sess.run(out)
# Check result
print(np.allclose(out_np, out_tf))
# True

您可以将上面的tf.math.segment_sum替换为您要使用的缩减功能。这与实际np.ufunc.reduceat之间的唯一区别是特殊情况,其中indices[i] >= indices[i + 1].发布函数需要对indices进行排序,如果存在indices[i] == indices[i + 1]输出中相应的i位置将为零,而不是a[indices[i]].

最新更新