Advertisement
Guest User

Untitled

a guest
Jun 24th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. c = tf.ragged.constant([[1, 2, 3], [4, 5]])
  2. v = tf.ragged.constant([[10., 20., 30.], [40., 50.]])
  3.  
  4. r = tf.random.uniform([1, 1], maxval=2, dtype=tf.int32)
  5.  
  6. with tf.Session() as sess:
  7. print(sess.run([tf.gather_nd(c, r), tf.gather_nd(v, r)]))
  8.  
  9. import tensorflow as tf
  10. tf.enable_eager_execution() # you can use a normal Session, but this to show intermediate output
  11.  
  12. c = tf.ragged.constant([[1, 2, 3], [4, 5]])
  13. v = tf.ragged.constant([[10., 20., 30.], [40., 50.]])
  14.  
  15. r = tf.random.uniform([1, 1], maxval=2, dtype=tf.int32)
  16.  
  17. a = tf.gather_nd(c, r)
  18. b = tf.gather_nd(v, r)
  19. print(a)
  20. print(b)
  21.  
  22. # Output example
  23. #<tf.RaggedTensor [[1, 2, 3]]>
  24. #<tf.RaggedTensor [[10.0, 20.0, 30.0]]>
  25.  
  26. # Lengths
  27. l_a = tf.squeeze(a.row_lengths())
  28. l_b = tf.squeeze(b.row_lengths())
  29. print(l_a)
  30. print(l_b)
  31.  
  32. #Output example
  33. #tf.Tensor(3, shape=(), dtype=int64)
  34. #tf.Tensor(3, shape=(), dtype=int64)
  35.  
  36. #Random index between 0 and length
  37. rand_idx_a = tf.random.uniform([1],minval=0,maxval=l_a,dtype=tf.int64)
  38. rand_idx_b = tf.random.uniform([1],minval=0,maxval=l_b,dtype=tf.int64)
  39. print(rand_idx_a)
  40. print(rand_idx_b)
  41.  
  42. #Output example
  43. #tf.Tensor([0], shape=(1,), dtype=int64)
  44. #tf.Tensor([2], shape=(1,), dtype=int64)
  45.  
  46. #Convert ragged tensor to tensor of shape [1,n]
  47. t_a = a.to_tensor()
  48. t_b = b.to_tensor()
  49. print(t_a)
  50. print(t_b)
  51.  
  52. #Read from extracted tensor using random index
  53. rand_a = tf.gather_nd(tf.squeeze(t_a),rand_idx_a) #removes dimension of 1
  54. rand_b = tf.gather_nd(tf.squeeze(t_b),rand_idx_b)
  55. print(rand_a)
  56. print(rand_b)
  57.  
  58. #Output example
  59. #tf.Tensor([[1 2 3]], shape=(1, 3), dtype=int32)
  60. #tf.Tensor([[10. 20. 30.]], shape=(1, 3), dtype=float32)
  61. #tf.Tensor(1, shape=(), dtype=int32)
  62. #tf.Tensor(30.0, shape=(), dtype=float32)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement