Last active
February 9, 2023 02:20
-
-
Save AmosLewis/c90c1148a96291db93408b3fa39f9ae2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import torch | |
t = torch.tensor([ | |
[1, 2, 3, 4, 5], | |
[6,7,8,9,10], | |
[11,12,13,14,15], | |
[16,17,18,19,20] | |
]) # 4*5 | |
i = torch.tensor([ | |
[1,2,3], | |
[3,2,1], | |
]) # 2*3 | |
o = t[i] | |
= torch.tensor([ | |
[[ 6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]], | |
[[16, 17, 18, 19, 20], [11, 12, 13, 14, 15], [ 6, 7, 8, 9, 10]] | |
]) # 2*3*5 | |
########## same function by tensorflow | |
import tensorflow as tf | |
t = tf.constant([ | |
[1, 2, 3, 4, 5], | |
[6,7,8,9,10], | |
[11,12,13,14,15], | |
[16,17,18,19,20] | |
]) # 4*5 | |
i = tf.constant([ | |
[1,2,3], | |
[3,2,1], | |
]) # 2*3 | |
i_expand = tf.expand_dims(i,axis=2) | |
<tf.Tensor: shape=(2, 3, 1), dtype=int32, numpy= | |
array([[[1], | |
[2], | |
[3]], | |
[[3], | |
[2], | |
[1]]], dtype=int32)> | |
io=tf.gather_nd(t,tf.expand_dims(i,axis=2)) | |
<tf.Tensor: shape=(2, 3, 5), dtype=int32, numpy= | |
array([[[ 6, 7, 8, 9, 10], | |
[11, 12, 13, 14, 15], | |
[16, 17, 18, 19, 20]], | |
[[16, 17, 18, 19, 20], | |
[11, 12, 13, 14, 15], | |
[ 6, 7, 8, 9, 10]]], dtype=int32)> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Multi Indexes with different shape