【问题标题】:Adding consecutive elements across dimension in tensorflow (np.add.reduceat)在张量流中跨维度添加连续元素(np.add.reduceat)
【发布时间】:2019-11-10 04:28:59
【问题描述】:

是否有任何 tensorflow 功能或优雅的执行以下任务

考虑我有维度说 $3 \times 10$ 的二维张量。现在我想沿维度 $1$(或行)添加连续元素,其中要添加的连续元素的数量由张量决定。如果它说 $[ 2,2,4,2]$ 输出张量的大小应为 $ 3 \times 4$。因为 $ [ a_1 + a_2 , a_3+a_4 , a_5+a_6+a_7+a_8 , a_9+a_10]$ 会在每一行张量

例如:

$\begin{bmatrix}
1 & 2 & 3 & 4 & 5 & 6 & 1 & 2 & 3 &4\\ 
7 & 8 & 9 & 10 &11  &12 & 7 & 8 & 9 & 10\\ 
13 &14  &15  &16  &17  &18 & 13 &14 &15 &16
\end{bmatrix}$

输出应该跟在后面

$\begin{bmatrix}
3 & 7 & 14 & 7\\ 
15 & 19 &38 &19\\ 
27  &31 & 62 &31
\end{bmatrix}$

编辑:在 numpy np.add.reduceat 中似乎有这个功能

【问题讨论】:

  • 也有人可以正确格式化问题或告诉我该怎么做吗?
  • 不幸的是,stackoverflow 上没有乳胶支持。一种解决方法是使用codecogs.com/latex/eqneditor.php 并使用图片来回答问题。
  • 输出的最后一行应该是:27 & 31 & 62 & 31

标签: tensorflow


【解决方案1】:

tensorflow中没有这个功能。但是你可以通过拆分数组来构造它:

def tf_reduceat(data, at_array, axis=-1):
    split_data = tf.split(data, at_array, axis=axis)
    return tf.stack([tf.reduce_sum(i, axis=axis) for i in split_data], axis=axis)


a = tf.constant([[1, 2, 3, 4, 5, 6, 1, 2, 3, 4], 
                 [7, 8, 9, 10, 11, 12, 7, 8, 9, 10], 
                 [13, 14, 15, 16, 17, 18, 13, 14, 15, 16]])
result = tf_reduceat(a, [2, 2, 4, 2])

运行结果产量:

array([[ 3,  7, 14,  7],                                                                                                       
       [15, 19, 38, 19],                                                                                                       
       [27, 31, 62, 31]], dtype=int32)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-20
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多