Dynamically access the tensor index

(Alexey) #1

Hello guys, need help in indexing S4TF tensors.
I’m having a hard time with how to access some index in the tensor dynamically.
For example:
var x = Tensor<Float>(randomNormal: TensorShape([10, 2, 3]))
I can now do x[0,0,0],
but can’t find a way for something like this:
let a = [0, 0, 0]
x[a]

Or is there some multiindex in S4TF like numpy.nditer?
Appreciate any help.

0 Likes

(Stephen Johnson) #2

Here’s 3 ways to do it depending on what you’re trying to accomplish. Take your pick.

import TensorFlow
var x = Tensor<Float>(randomNormal: TensorShape([10, 2, 3]))

for a in 0..<10 {
  for b in 0..<2 {
    for c in 0..<3 {
      print(x[a,b,c])
    }
  }
}

print("\n\n----\n\n")

for i in x.array {
  for j in i {
    for k in j {
      print(k)
    }
  }
}

print("\n\n----\n\n")

for s in x.scalars {
  print(s)
}
0 Likes

(Alexey) #3

Thanks for the answer. I discuss it in s4tf google group as well (link). The relevant use case is to reassign values for tensor. The closest thing is numpy.nditer multiindex there one can iterate through this index and reassign values to each element. This use case is for numerical gradient checking. It seems like S4TF doesn’t have this functionality yet.

0 Likes