Inappropriate_measurement

I use the tf.unsorted_segment_sumTensorFlow method , and it works fine when the tensor that I give as data has only one row. For instance:

tf.unsorted_segment_sum(tf.constant([0.2, 0.1, 0.5, 0.7, 0.8]),
                        tf.constant([0, 0, 1, 2, 2]), 3)

It gives the correct result:

array([ 0.3,  0.5 , 1.5 ], dtype=float32)

Question: if I use a tensor with several lines, how can I get results for each line? For example, if I try the tensor with two lines:

tf.unsorted_segment_sum(tf.constant([[0.2, 0.1, 0.5, 0.7, 0.8],
                                     [0.2, 0.2, 0.5, 0.7, 0.8]]),
                        tf.constant([[0, 0, 1, 2, 2],
                                     [0, 0, 1, 2, 2]]), 3)

The result I would expect:

array([ [ 0.3,  0.5 , 1.5 ], [ 0.4, 0.5, 1.5 ] ], dtype=float32)

But I get:

array([ 0.7,  1. ,  3. ], dtype=float32)

I want to know if anyone knows how to get the result for each line without using a for loop?

Thanks in advance

+4
source share
1 answer

EDIT:

, , . , tf.unsorted_segment_sum , , . , :

import tensorflow as tf

with tf.Session() as sess:
    data = tf.constant([[0.2, 0.1, 0.5, 0.7, 0.8],
                        [0.2, 0.2, 0.5, 0.7, 0.8]])
    idx = tf.constant([0, 0, 1, 2, 2])
    result = tf.transpose(tf.unsorted_segment_sum(tf.transpose(data), idx, 3))
    print(sess.run(result))

:

[[ 0.30000001  0.5         1.5       ]
 [ 0.40000001  0.5         1.5       ]]

:

tf.unsorted_segment_sum . - , :

data = tf.constant([[0.2, 0.1, 0.5, 0.7, 0.8],
                    [0.2, 0.2, 0.5, 0.7, 0.8]])
segment_ids = tf.constant([[0, 0, 1, 2, 2],
                           [0, 0, 1, 2, 2]])
num_segments = 3
rows = []
for data_i, ids_i in zip(data, segment_ids):
    rows.append(tf.unsorted_segment_sum(data_i, ids_i))
result = tf.stack(rows, axis=0)

: 1) (.. ) 2) . tf.while_loop, , , , . , , .

. , segment_id num_segments * row_index, , :

num_rows = tf.shape(segment_ids)[0]
rows_idx = tf.range(num_rows)
segment_ids_per_row = segment_ids + num_segments * tf.expand_dims(rows_idx, axis=1)

, :

seg_sums = tf.unsorted_segment_sum(data, segment_ids_per_row,
                                   num_segments * num_rows)
result = tf.reshape(seg_sums, [-1, num_segments])

:

array([[ 0.3, 0.5, 1.5 ],
       [ 0.4, 0.5, 1.5 ]], dtype=float32)
+3

Source: https://habr.com/ru/post/1673999/


All Articles