以十为单位在单轴上使用指定切片进行局部缩减

2024-09-27 07:32:43 发布

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

我尝试在二维数组的单轴上使用指定的切片执行局部reduce。你知道吗

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

我遇到了tf.math.reduce_sum,但我不确定如何在我的案例中使用它。你知道吗

如果我能像利用GPU一样在tensorflow中执行reduceat操作,那就太好了。你知道吗


Tags: numpyaddreducetftensorflow切片局部math
1条回答
网友
1楼 · 发布于 2024-09-27 07:32:43

您可以使用^{}执行几乎相同的操作:

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

您可以用要使用的归约函数替换上面的^{}。这和实际的^{}之间的唯一区别是indices[i] >= indices[i + 1]的特殊情况。posted函数要求对indices进行排序,如果存在indices[i] == indices[i + 1]的情况,则输出中相应的i位置将为零,而不是a[indices[i]]。你知道吗

相关问题 更多 >

    热门问题