TensorFlow:如何将张量行与具有相同第一个元素的张量的第二个元素相加? [英] TensorFlow: How to combine rows of tensor with summing the 2nd element of tensor which has the same 1st element?

查看:28
本文介绍了TensorFlow:如何将张量行与具有相同第一个元素的张量的第二个元素相加?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我想add这个张量的第二个元素,其中第一个元素是相同的.也欢迎任何基于 Numpy 的解决方案!

For example, I want to add the 2nd element of this tensor where the 1st element is same. Any Numpy based solution is also welcomed!

  • 来自:
x = tf.constant([
    [1., 0.9],
    [2., 0.7],
    [1., 0.7],
    [3., 0.4],
    [4., 0.8]
], dtype=tf.float32)

  • 致:
  • x = tf.constant([
        [1., 1.6],
        [2., 0.7],
        [3., 0.4],
        [4., 0.8]
    ], dtype=tf.float32)
    

    推荐答案

    感谢 FinleyGibson 的 Numpy 解决方案和一些有用的TensorFlow 指针!这是我在 TF 中使用 tf.unique_with_counts()tf.segment_sum() 的解决方案:

    Thanks FinleyGibson for the Numpy solution and some useful TensorFlow pointers! This is my solution in TF with using tf.unique_with_counts() and tf.segment_sum():

    <打击>

    x = tf.constant([
        [1., 0.9],
        [2., 0.7],
        [1., 0.7],
        [3., 0.4],
        [4., 0.8]
    ], dtype=tf.float32)
    
    with tf.Session() as sess:
        y, idx, y_counts = tf.unique_with_counts(x[:, 0])
        idx_sorted = tf.sort(idx, axis=-1, direction='ASCENDING')
        score_sum = tf.segment_sum(x[:, 1], idx_sorted)
        result = tf.stack((y, score_sum), axis=1)
        print(sess.run(result))
    
    [[1.       1.5999999]
    [2.        0.7      ]
    [3.        0.4      ]
    [4.        0.8      ]]
    

    • 似乎上述解决方案没有正确排序行/列对.这是固定版本.
    with tf.Session() as sess:
        x = tf.constant([
            [2., 0.7],
            [1., 0.1],
            [3., 0.4],
            [4., 0.8],
            [1., 0.9]], dtype=tf.float32)
    
        def matrix_sort(a, col):
            return tf.gather(a, tf.nn.top_k(-a[:, col], k=a.get_shape()[0].value).indices)
    
        sorted_x = matrix_sort(matrix_sort(x, 1), 0)
        labels = sorted_x[:, 0]
        scores = sorted_x[:, 1]
        y, idx, y_counts = tf.unique_with_counts(labels)
        score_sum = tf.segment_sum(scores, idx)    
        result = tf.stack((y, score_sum), axis=1) 
        print(sess.run(result))
    
    [[1.  1. ]
     [2.  0.7]
     [3.  0.4]
     [4.  0.8]]
    
    

    这篇关于TensorFlow:如何将张量行与具有相同第一个元素的张量的第二个元素相加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆