Lua Torch7 array index notation

2019-07-10 21:03发布

问题:

I have an array named xTain of size nDatax1

I initialize it as

xTrain = torch.linspace(-1,1,nData)

To access the array, the author uses xTrain[{{i}}]

can you please explain this notation? Why not simply xTrain[i] ?

Please refer the author's code here on Pg No 21- https://www.cs.ox.ac.uk/people/nando.defreitas/machinelearning/lecture4.pdf

As an additional note-

xTrain=torch.linespace(-1,1,10)

when I do

th> print(xTrain[1])    
-1

th> print(xTrain[{1}])
-1

th> print(xTrain[{{1}}])
-1
[torch.DoubleTensor of size 1]

Why does it also print [torch.DoubleTensor of size 1] in 3rd case. My guess is in first 2 case its returning a scalar value at that location and in 3rd case a DoubleTensor

回答1:

Good place to start is the Lua manual, it's syntax and explessions. You can see, what is meaning of {...} in Lua:

 {...}              -- creates a list with all vararg parameters

So in short your {1} creates a list with single value 1. Repeating it once more you got a list containing list containing single number 1.

If the xTrain would be simple table, it would probably fail, because it is hard to index using lists, but Lua supports metatables so the actual value is not used for indexing the table, but passed to some function which takes care of the lists.

Also reading further about the Tensor class, which is returned from the torch.linespace() function is a good place to see. The indexing using "array access" is explained in the section [Tensor] [{ dim1,dim2,... }] or [{ {dim1s,dim1e}, {dim2s,dim2e} }]