【问题标题】:TensorFlow: How to combine rows of tensor with summing the 2nd element of tensor which has the same 1st element?TensorFlow:如何将张量的行与具有相同第一个元素的张量的第二个元素相加?
【发布时间】:2019-09-16 14:46:38
【问题描述】:

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

  • 发件人:
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)

【问题讨论】:

    标签: python numpy tensorflow


    【解决方案1】:

    numpy 解决方案:

    x = np.array([
        [1., 0.9],
        [2., 0.7],
        [1., 0.7],
        [3., 0.4],
        [4., 0.8]])
    
    ans = np.array([[i,np.sum(x[np.where(x[:,0]==i), 1])] for i in set(x[:,0])])
    

    给了

    array([[1. , 1.6],
           [2. , 0.7],
           [3. , 0.4],
           [4. , 0.8]])
    

    您将无法对 'tf.constant()' 执行此操作,因为它是一个 constant 变量并且不支持更改其值。如果要更改 tensorflow 数据结构中的值,最好将值传递给 tf.placeholder 或使用 tf.Variable。但是,这些需要预定义的尺寸,并且不能根据您的问题更改其尺寸。

    【讨论】:

    • 感谢基于 numpy 的解决方案,但事实证明,您可以使用 tf.unique_with_counts() 和 tf.segment_sum() 来做到这一点。您可以在下面查看我的答案。
    【解决方案2】:

    感谢 FinleyGibson 提供 Numpy 解决方案和一些有用的 TensorFlow 指针!这是我在 TF 中使用tf.unique_with_counts()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]]
    
    

    【讨论】:

      猜你喜欢
      • 2012-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多