knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
library(rTorch)

Creating a tensor

If you are in a hurry to test rTorch, here some examples:

Example 1

library(rTorch)

a <- torch$tensor(c(1, 2, 3, 4, 5))
a

Notice that this is a float tensor (see the comma ,). By default, rTorch will choose a 32-bit float for you.

class(a)
a$dtype

Example 2

b <- torch$tensor(seq(1,10))
b

These are all integers.

class(b)
b$dtype

Example 3

c <- torch$arange(1, 10)
c
torch$ones(c(2L, 3L))

Example 4

torch$rand(5L, 4L)

Example 5

torch$linspace(1L, 10L, steps = 100L)

Example 6

torch$eye(5L)

Example 7

arr <- array(seq(1, 60), dim = c(5, 4, 3))
torch$as_tensor(arr)

Example 8

mat <- matrix(seq(1, 20), nrow = 5)
torch$as_tensor(mat)

Example 9

m <- torch$Tensor(list(list(1, 2), 
                  list(3, 4),
                  list(5, 6)
                  )
             )
m
(shp <- m$shape)
m$size()
dim(m)
length(m)
# tensor shape components
shp[[1]]
shp[[2]]

Example 10

# a tensor representing a 28x20 pixels image in 3 channels
(img <- torch$rand(3L, 28L, 28L))
# plot the image three channels
image((img[1L,,]$numpy()), main = "channel 1")
image((img[2L,,]$numpy()), main = "channel 2")
image((img[3L,,]$numpy()), main = "channel 3")


f0nzie/rTorch documentation built on Oct. 28, 2021, 5:40 a.m.