Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the order of elements in first axis tensorflow

I have an n dimensional tensor . I want to change the order of elements based on first axis and a given order. For example (1, 0, 2, 4, 3, 5) should give me this result for this matrix:

[1, 0, 0, 0, 0]        [0, 1, 0, 0, 0]     
[0, 1, 0, 0, 0]        [1, 0, 0, 0, 0]
[0, 0, 1, 0, 0]   ==>  [0, 0, 1, 0, 0]
[0, 0, 0, 1, 0]        [0, 0, 0, 0, 1]
[0, 0, 0, 0, 1]        [0, 0, 0, 1, 0]
[0, 0, 0, 0, 1]        [0, 0, 0, 0, 1]

The order is important for me because I have some tensors and I want all of them to be reordered with the same order. How can I achieve this?

like image 976
Siavash Avatar asked Oct 30 '25 18:10

Siavash


1 Answers

You should use tf.gather:

with tf.Session() as sess:
    data = [[1, 0, 0, 0, 0],
            [0, 1, 0, 0, 0],
            [0, 0, 1, 0, 0],
            [0, 0, 0, 1, 0],
            [0, 0, 0, 0, 1],
            [0, 0, 0, 0, 1]]
    idx = [1, 0, 2, 4, 3, 5]
    result = tf.gather(data, idx)
    print(sess.run(result))

Output:

[[0 1 0 0 0]
 [1 0 0 0 0]
 [0 0 1 0 0]
 [0 0 0 0 1]
 [0 0 0 1 0]
 [0 0 0 0 1]]
like image 77
jdehesa Avatar answered Nov 01 '25 08:11

jdehesa