In this article we describe various ways of creating
torch tensors in R.
You can create tensors from R objects using the
torch_tensor function. The
function takes an R vector, matrix or array and creates an equivalent
You can see a few examples below:
By default, we will create tensors in the
converting their R datatype to the corresponding torch
Note currently, only numeric and boolean types are supported.
You can always modify
converting an R object to a torch tensor. For example:
Other options available when creating a tensor are:
requires_grad: boolean indicating if you want
autograd to record operations on them for automatic
pin_memory: – If set, the tensor returned would be
allocated in pinned memory. Works only for CPU tensors.
These options are available for all functions that can be used to create new tensors, including the factory functions listed in the next section.
You can also use the
torch_* functions listed below to
create torch tensors using some algorithm.
For example, the
torch_randn function will create
tensors using the normal distribution with mean 0 and standard deviation
1. You can use the
... argument to pass the size of the
dimensions. For example, the code below will create a normally
distributed tensor with shape 5x3.
Another example is
torch_ones, which creates a tensor
filled with ones.
Here is the full list of functions that can be used to bulk-create tensors in torch:
torch_arange: Returns a tensor with a sequence of
torch_empty: Returns a tensor with uninitialized
torch_eye: Returns an identity matrix,
torch_full: Returns a tensor filled with a single
torch_linspace: Returns a tensor with values linearly
spaced in some interval,
torch_logspace: Returns a tensor with values
logarithmically spaced in some interval,
torch_ones: Returns a tensor filled with all ones,
torch_rand: Returns a tensor filled with values drawn
from a uniform distribution on [0, 1).
torch_randint: Returns a tensor with integers randomly
drawn from an interval,
torch_randn: Returns a tensor filled with values drawn
from a unit normal distribution,
torch_randperm: Returns a tensor filled with a random
permutation of integers in some interval,
torch_zeros: Returns a tensor filled with all