What are tensors?

From the book:

“… tensors are ‘just’ multi-dimensional arrays optimized for fast computation - not on the CPU only but also on specialized devices such as GPUs and TPUs.

Load libraries:

library(torch)
library(dplyr)
library(ggplot2)

Create a tensor:

t1 <- torch_tensor(2)
t1$shape
## [1] 1

Parameters of torch_tensor() (see help file for this function):

  • data
  • dtype
  • device
  • requires_grad
  • pin_memory

Look at the attributes of the tensor:

t1$dtype
## torch_Float
t1$device
## torch_device(type='cpu')
t1$shape
## [1] 1
summary(t1)
##       Length       Class1       Class2         Mode 
##            1 torch_tensor           R7  externalptr

Change attributes:

# to integer:
t2 <- t1$to(dtype = torch_int())
t2$dtype
## torch_Int
# utilize GPU:
t2 <- t1$to(device = "cuda")
t2$device