3.3 Accessing Parts of a Tensor (indexing and slicing)

Indexing in torch is 1-based. Very similar to functionality in R.

Example:

t <- torch_tensor(matrix(1:9, ncol = 3, byrow = TRUE))
t
## torch_tensor
##  1  2  3
##  4  5  6
##  7  8  9
## [ CPULongType{3,3} ]
t[1, ] # row 1. 
## torch_tensor
##  1
##  2
##  3
## [ CPULongType{3} ]
t[1, , drop = FALSE] # Same as above except that dimensionality is preserved
## torch_tensor
##  1  2  3
## [ CPULongType{1,3} ]

Slicing example:

t <- torch_rand(3, 3, 3)
t[1:2, 2:3, c(1, 3)]
## torch_tensor
## (1,.,.) = 
##   0.2937  0.4863
##   0.8151  0.8476
## 
## (2,.,.) = 
##   0.9466  0.6171
##   0.6888  0.2210
## [ CPUFloatType{2,2,2} ]

3.3.1 Beyond R

Access last element:

t <- torch_tensor(matrix(1:4, ncol = 2, byrow = TRUE))
t[-1, -1]
## torch_tensor
## 4
## [ CPULongType{} ]
t <- torch_tensor(1:4)
t[-1]
## torch_tensor
## 4
## [ CPULongType{} ]

Compare to R:

# matrix:
m <- matrix(1:4, ncol = 2, byrow = TRUE)
m[-1, -1]
## [1] 4
# vector:
m <- 1:4
m[-1]
## [1] 2 3 4

Step pattern:

t <- torch_tensor(matrix(1:20, ncol = 10, byrow = TRUE))
t
## torch_tensor
##   1   2   3   4   5   6   7   8   9  10
##  11  12  13  14  15  16  17  18  19  20
## [ CPULongType{2,10} ]
t[ , 1:8:2] # every other value in columns 1 through 8
## torch_tensor
##   1   3   5   7
##  11  13  15  17
## [ CPULongType{2,4} ]

Use .. to designate all dimensions not explicitly referenced.

t2 <- torch_randn(2, 2, 2)
t2
## torch_tensor
## (1,.,.) = 
##   0.5503  1.5899
##   0.3364 -1.3595
## 
## (2,.,.) = 
##   0.3992 -0.1357
##   0.0885  1.1671
## [ CPUFloatType{2,2,2} ]
t2[2, ..] # 2nd element of the 1st dimension
## torch_tensor
##  0.3992 -0.1357
##  0.0885  1.1671
## [ CPUFloatType{2,2} ]