Title: | R Interface to 'TensorFlow' |
---|---|
Description: | Interface to 'TensorFlow' <https://www.tensorflow.org/>, an open source software library for numerical computation using data flow graphs. Nodes in the graph represent mathematical operations, while the graph edges represent the multidimensional data arrays (tensors) communicated between them. The flexible architecture allows you to deploy computation to one or more 'CPUs' or 'GPUs' in a desktop, server, or mobile device with a single 'API'. 'TensorFlow' was originally developed by researchers and engineers working on the Google Brain Team within Google's Machine Intelligence research organization for the purposes of conducting machine learning and deep neural networks research, but the system is general enough to be applicable in a wide variety of other domains as well. |
Authors: | JJ Allaire [aut, cph], Tomasz Kalinowski [ctb, cph, cre], Daniel Falbel [ctb, cph], Dirk Eddelbuettel [ctb, cph], Yuan Tang [aut, cph] , Nick Golding [ctb, cph], Google Inc. [ctb, cph] (Examples and Tutorials), Posit, PBC [cph, fnd] |
Maintainer: | Tomasz Kalinowski <[email protected]> |
License: | Apache License 2.0 |
Version: | 2.16.0.9000 |
Built: | 2024-10-30 19:20:06 UTC |
Source: | https://github.com/rstudio/tensorflow |
[
Subset tensors with [
## S3 method for class 'tensorflow.tensor' x[ ..., drop = TRUE, style = getOption("tensorflow.extract.style"), options = tf_extract_opts(style) ]
## S3 method for class 'tensorflow.tensor' x[ ..., drop = TRUE, style = getOption("tensorflow.extract.style"), options = tf_extract_opts(style) ]
x |
Tensorflow tensor |
... |
slicing specs. See examples and details. |
drop |
whether to drop scalar dimensions |
style |
One of |
options |
An object returned by |
## Not run: x <- as_tensor(array(1:15, dim = c(3, 5))) x # by default, numerics supplied to [...] are interpreted R style x[,1] # first column x[1:2,] # first two rows x[,1, drop = FALSE] # 1 column matrix # strided steps can be specified in R syntax or python syntax x[, seq(1, 5, by = 2)] x[, 1:5:2] # if you are unfamiliar with python-style strided steps, see: # https://numpy.org/doc/stable/reference/arrays.indexing.html#basic-slicing-and-indexing # missing arguments for python syntax are valid, but they must by backticked # or supplied as NULL x[, `::2`] x[, NULL:NULL:2] x[, `2:`] # all_dims() expands to the shape of the tensor # (equivalent to a python ellipsis `...`) # (not to be confused with R dots `...`) y <- as_tensor(array(1:(3^5), dim = c(3,3,3,3,3))) all.equal(y[all_dims(), 1], y[, , , , 1]) # tf$newaxis are valid (equivalent to a NULL) x[,, tf$newaxis] x[,, NULL] # negative numbers are always interpreted python style # The first time a negative number is supplied to `[`, a warning is issued # about the non-standard behavior. x[-1,] # last row, with a warning x[-1,] # the warning is only issued once # specifying `style = 'python'` changes the following: # + zero-based indexing is used # + slice sequences in the form of `start:stop` do not include `stop` # in the returned value # + out-of-bounds indices in a slice are valid # The style argument can be supplied to individual calls of `[` or set # as a global option # example of zero based indexing x[0, , style = 'python'] # first row x[1, , style = 'python'] # second row # example of slices with exclusive stop options(tensorflow.extract.style = 'python') x[, 0:1] # just the first column x[, 0:2] # first and second column # example of out-of-bounds index x[, 0:10] options(tensorflow.extract.style = NULL) # slicing with tensors is valid too, but note, tensors are never # translated and are always interpreted python-style. # A warning is issued the first time a tensor is passed to `[` x[, tf$constant(0L):tf$constant(2L)] # just as in python, only scalar tensors are valid # https://www.tensorflow.org/api_docs/python/tf/Tensor#__getitem__ # To silence the warnings about tensors being passed as-is and negative numbers # being interpreted python-style, set options(tensorflow.extract.style = 'R') # clean up from examples options(tensorflow.extract.style = NULL) ## End(Not run)
## Not run: x <- as_tensor(array(1:15, dim = c(3, 5))) x # by default, numerics supplied to [...] are interpreted R style x[,1] # first column x[1:2,] # first two rows x[,1, drop = FALSE] # 1 column matrix # strided steps can be specified in R syntax or python syntax x[, seq(1, 5, by = 2)] x[, 1:5:2] # if you are unfamiliar with python-style strided steps, see: # https://numpy.org/doc/stable/reference/arrays.indexing.html#basic-slicing-and-indexing # missing arguments for python syntax are valid, but they must by backticked # or supplied as NULL x[, `::2`] x[, NULL:NULL:2] x[, `2:`] # all_dims() expands to the shape of the tensor # (equivalent to a python ellipsis `...`) # (not to be confused with R dots `...`) y <- as_tensor(array(1:(3^5), dim = c(3,3,3,3,3))) all.equal(y[all_dims(), 1], y[, , , , 1]) # tf$newaxis are valid (equivalent to a NULL) x[,, tf$newaxis] x[,, NULL] # negative numbers are always interpreted python style # The first time a negative number is supplied to `[`, a warning is issued # about the non-standard behavior. x[-1,] # last row, with a warning x[-1,] # the warning is only issued once # specifying `style = 'python'` changes the following: # + zero-based indexing is used # + slice sequences in the form of `start:stop` do not include `stop` # in the returned value # + out-of-bounds indices in a slice are valid # The style argument can be supplied to individual calls of `[` or set # as a global option # example of zero based indexing x[0, , style = 'python'] # first row x[1, , style = 'python'] # second row # example of slices with exclusive stop options(tensorflow.extract.style = 'python') x[, 0:1] # just the first column x[, 0:2] # first and second column # example of out-of-bounds index x[, 0:10] options(tensorflow.extract.style = NULL) # slicing with tensors is valid too, but note, tensors are never # translated and are always interpreted python-style. # A warning is issued the first time a tensor is passed to `[` x[, tf$constant(0L):tf$constant(2L)] # just as in python, only scalar tensors are valid # https://www.tensorflow.org/api_docs/python/tf/Tensor#__getitem__ # To silence the warnings about tensors being passed as-is and negative numbers # being interpreted python-style, set options(tensorflow.extract.style = 'R') # clean up from examples options(tensorflow.extract.style = NULL) ## End(Not run)
This function returns an object that can be used when subsetting tensors with
[
. If you are familiar with python,, this is equivalent to the python Ellipsis
...
, (not to be confused with ...
in R
).
all_dims()
all_dims()
## Not run: # in python, if x is a numpy array or tensorflow tensor x[..., i] # the ellipsis means "expand to match number of dimension of x". # to translate the above python expression to R, write: x[all_dims(), i] ## End(Not run)
## Not run: # in python, if x is a numpy array or tensorflow tensor x[..., i] # the ellipsis means "expand to match number of dimension of x". # to translate the above python expression to R, write: x[all_dims(), i] ## End(Not run)
Coerce objects to tensorflow tensors (potentially of a specific dtype or shape). The
provided default methods will call
tf$convert_to_tensor
. Depending on arguments supplied it may also call some combination of
as_tensor(x, dtype = NULL, ..., name = NULL) ## Default S3 method: as_tensor(x, dtype = NULL, ..., shape = NULL, name = NULL) ## S3 method for class 'double' as_tensor(x, dtype = NULL, ..., name = NULL)
as_tensor(x, dtype = NULL, ..., name = NULL) ## Default S3 method: as_tensor(x, dtype = NULL, ..., shape = NULL, name = NULL) ## S3 method for class 'double' as_tensor(x, dtype = NULL, ..., name = NULL)
x |
object to convert |
dtype |
|
... |
ignored |
name |
|
shape |
an integer vector, tensor, or |
a tensorflow tensor
## Not run: as_tensor(42, "int32") as_tensor(as_tensor(42)) ## End(Not run)
## Not run: as_tensor(42, "int32") as_tensor(as_tensor(42)) ## End(Not run)
Evaluate a model object. See implementations in the keras3 package.
evaluate(object, ...)
evaluate(object, ...)
object |
An evaluatable R object. |
... |
Optional arguments passed on to implementing methods. |
install_tensorflow()
installs just the tensorflow python package and it's
direct dependencies. For a more complete installation that includes
additional optional dependencies, use keras3::install_keras()
.
install_tensorflow( method = c("auto", "virtualenv", "conda"), conda = "auto", version = "default", envname = "r-tensorflow", extra_packages = NULL, restart_session = TRUE, conda_python_version = NULL, ..., cuda = NULL, metal = FALSE, pip_ignore_installed = FALSE, new_env = identical(envname, "r-tensorflow"), python_version = NULL )
install_tensorflow( method = c("auto", "virtualenv", "conda"), conda = "auto", version = "default", envname = "r-tensorflow", extra_packages = NULL, restart_session = TRUE, conda_python_version = NULL, ..., cuda = NULL, metal = FALSE, pip_ignore_installed = FALSE, new_env = identical(envname, "r-tensorflow"), python_version = NULL )
method |
Installation method. By default, "auto" automatically finds a method that will work in the local environment. Change the default to force a specific installation method. Note that the "virtualenv" method is not available on Windows. |
conda |
The path to a |
version |
TensorFlow version to install. Valid values include:
|
envname |
The name, or full path, of the environment in which Python
packages are to be installed. When |
extra_packages |
Additional Python packages to install along with TensorFlow. |
restart_session |
Restart R session after installing (note this will only occur within RStudio). |
conda_python_version |
Passed to conda (only applicable if |
... |
other arguments passed to |
cuda |
logical |
metal |
Whether to install |
pip_ignore_installed |
Whether pip should ignore installed python packages and reinstall all already installed python packages. |
new_env |
If |
python_version |
Select the Python that will be used to create the
virtualenv. Pass a string with version constraints like |
You may be prompted to download and install miniconda if reticulate did not find a non-system installation of python. Miniconda is the recommended installation method for most users, as it ensures that the R python installation is isolated from other python installations. All python packages will by default be installed into a self-contained conda or venv environment named "r-reticulate". Note that "conda" is the only supported method on M1 Mac.
If you initially declined the miniconda installation prompt, you can later
manually install miniconda by running reticulate::install_miniconda()
.
install_tensorflow()
or
keras3::install_keras()
isn't required to use tensorflow with the
package. If you manually configure a python environment with the required
dependencies, you can tell R to use it by pointing reticulate at it,
commonly by setting an environment variable:
Sys.setenv("RETICULATE_PYTHON" = "~/path/to/python-env/bin/python")
Beginning with Tensorflow version 2.13, the default tensorflow package now works on Apple Silicon. See https://developer.apple.com/metal/tensorflow-plugin/ for instructions on how to install older versions of Tensorflow on macOS. Please note that not all operations are supported on Arm Mac GPUs. You can work around the missing operations by pinning operations to CPU. For example:
x <- array(runif(64*64), c(1, 64, 64)) keras3::layer_random_rotation(x, .5) # Error: # No registered 'RngReadAndSkip' OpKernel for 'GPU' devices # Pin the operation to the CPU to avoid the error with(tf$device("CPU"), keras3::layer_random_rotation(x, .5) ) # No Error
If you wish to add additional PyPI packages to your Keras / TensorFlow
environment you can either specify the packages in the extra_packages
argument of install_tensorflow()
or install_keras()
, or alternatively
install them into an existing environment using the
reticulate::py_install()
function. Note that install_keras()
includes a
set of additional python packages by default, see ?keras3::install_keras
for details.
Parse command line arguments of the form --key=value
and
--key value
. The values are assumed to be valid yaml
and
will be converted using yaml.load()
.
parse_arguments(arguments = NULL)
parse_arguments(arguments = NULL)
arguments |
A vector of command line arguments. When
|
Parse configuration flags for a TensorFlow application. Use
this to parse and unify the configuration(s) specified through
a flags.yml
configuration file, alongside other arguments
set through the command line.
parse_flags( config = Sys.getenv("R_CONFIG_ACTIVE", unset = "default"), file = "flags.yml", arguments = commandArgs(TRUE) )
parse_flags( config = Sys.getenv("R_CONFIG_ACTIVE", unset = "default"), file = "flags.yml", arguments = commandArgs(TRUE) )
config |
The configuration to use. Defaults to the
active configuration for the current environment (as
specified by the |
file |
The configuration file to read. |
arguments |
The command line arguments (as a character vector) to be parsed. |
A named R list, mapping configuration keys to values.
## Not run: # examine an example configuration file provided by tensorflow file <- system.file("examples/config/flags.yml", package = "tensorflow") cat(readLines(file), sep = "\n") # read the default configuration FLAGS <- tensorflow::parse_flags("default", file = file) str(FLAGS) # read the alternate configuration: note that # the default configuration is inherited, but # we override the 'string' configuration here FLAGS <- tensorflow::parse_flags("alternate", file = file) str(FLAGS) # override configuration values using command # line arguments (normally, these would be # passed in through the command line invocation # used to start the process) FLAGS <- tensorflow::parse_flags( "alternate", file = file, arguments = c("--foo=1") ) str(FLAGS) ## End(Not run)
## Not run: # examine an example configuration file provided by tensorflow file <- system.file("examples/config/flags.yml", package = "tensorflow") cat(readLines(file), sep = "\n") # read the default configuration FLAGS <- tensorflow::parse_flags("default", file = file) str(FLAGS) # read the alternate configuration: note that # the default configuration is inherited, but # we override the 'string' configuration here FLAGS <- tensorflow::parse_flags("alternate", file = file) str(FLAGS) # override configuration values using command # line arguments (normally, these would be # passed in through the command line invocation # used to start the process) FLAGS <- tensorflow::parse_flags( "alternate", file = file, arguments = c("--foo=1") ) str(FLAGS) ## End(Not run)
Sets all random seeds needed to make TensorFlow code reproducible.
set_random_seed(seed, disable_gpu = TRUE)
set_random_seed(seed, disable_gpu = TRUE)
seed |
A single value, interpreted as an integer |
disable_gpu |
|
This function should be used instead of use_session_with_seed()
if
you are using TensorFlow >= 2.0, as the concept of session
doesn't
really make sense anymore.
This functions sets:
The R random seed with set.seed()
.
The python and Numpy seeds via (reticulate::py_set_seed()
).
The TensorFlow seed with (tf$random$set_seed()
)
It also optionally disables the GPU execution as this is a potential source of non-reproducibility.
tf.TensorShape
objectCreate a tf.TensorShape
object
shape(..., dims = list(...))
shape(..., dims = list(...))
... |
Tensor dimensions as integers or |
dims |
Tensor dimensions as a vector. |
https://www.tensorflow.org/api_docs/python/tf/TensorShape
## Not run: # --- construct --- shape() # tf.TensorShape() # scalar shape(NULL) # tf.TensorShape([None]) # 1-D array of unknown length shape(NA) # tf.TensorShape([None]) # 1-D array of unknown length, NA is a synonym for NULL shape(dims = NULL) # TensorShape(None) # Unknown rank, unknown size shape(3, 4) # TensorShape([3, 4]) # 2-D array (matrix) with 3 rows, 4 columns shape(NA, 4) # TensorShape([None, 4]) # 2-D array (matrix) with unknown rows, 4 columns shape(dims = c(NA, 4)) # TensorShape([None, 4]) # same as above; bypass ... and pass dims directly # --- inspect --- length(shape(dims = NULL)) # NA_integer_ length(shape(1,2,3,NA)) # 4L # ---convert --- x <- shape(dims = list(3L, 5L)) as.list(x) # list(3L, 5L) as.integer(x) # c(3L, 5L) as.numeric(x) # c(3, 5) as.double(x) # c(3, 5) # alias for as.numeric as_tensor(x) # tf.Tensor([3 5], shape=(2,), dtype=int32) # convert partially undefined shapes x <- shape(NA, 3) as.list(x) # list(NULL, 3L) as.integer(x) # c(NA, 3L) as_tensor(x) # tf.Tensor([-1 3], shape=(2,), dtype=int32) # unspecified dims default is -1 # as_tensor() converts undefined dimensions to -1, which is useful for # tf functions that only accept tensors for shapes, e.g, tf$reshape(tf$zeros(shape(8)), as_tensor(shape(NA, 4))) # tf.Tensor([[0. 0. 0. 0.] # [0. 0. 0. 0.]], shape=(2, 4), dtype=float32) # converting fully unknown shapes raises an error try(as.list(shape(dims = NULL))) # ValueError: as_list() is not defined on an unknown TensorShape. # test for rank first if this a concern: as.list_or_null <- function(x) if(is.na(length(x))) NULL else as.list(x) as.list_or_null(shape(dims = NULL)) # --- compare --- # Fully known shapes return TRUE if and only if each element is equal shape(3, 4) == shape(3, 4) # TRUE shape(3, 4) == shape(4, 4) # FALSE # two unknown dimensions are treated as equal shape(NA, 4) == shape(NA, 4) # TRUE shape(NA, 4) == shape(3, 4) # FALSE # Two unknown shapes, return TRUE shape(dims = NULL) == shape(dims = NULL) # TRUE # Comparing an unknown shape to a partially or fully defined shape returns FALSE shape(dims = NULL) == shape(NULL) # FALSE shape(dims = NULL) == shape(4) # FALSE values of length greater than one supplied to `...` are automatically flattened shape(1, c(2, 3), 4) # shape(1, 2, 3, 4) shape(1, shape(2, 3), 4) # shape(1, 2, 3, 4) shape(1, as_tensor(2, 3), 4) # shape(1, 2, 3, 4) # --- extract or replace --- # regular R-list semantics for `[`, `[[`, `[<-`, `[[<-` x <- shape(1, 2, 3) x[1] # TensorShape([1]) x[[1]] # 1L x[2:3] # TensorShape([2, 3]) x[-1] # TensorShape([2, 3]) x[1] <- 11 ; x # TensorShape([11, 2, 3]) x[1] <- shape(11) ; x # TensorShape([11, 2, 3]) x[1] <- list(11) ; x # TensorShape([11, 2, 3]) x[[1]] <- 22 ; x # TensorShape([22, 2, 3]) x[1:2] <- c(NA, 99) ; x # TensorShape([None, 99, 3]) x[1:2] <- shape(33, 44) ; x # TensorShape([33, 44, 3]) # --- concatenate --- c(shape(1), shape(2, 3), shape(4, NA)) # TensorShape([1, 2, 3, 4, None]) # --- merge --- merge(shape(NA, 2), shape(1 , 2)) # TensorShape([1, 2]) try(merge(shape(2, 2), shape(1, 2))) # ValueError: Shapes (2, 2) and (1, 2) are not compatible rm(x) # cleanup ## End(Not run)
## Not run: # --- construct --- shape() # tf.TensorShape() # scalar shape(NULL) # tf.TensorShape([None]) # 1-D array of unknown length shape(NA) # tf.TensorShape([None]) # 1-D array of unknown length, NA is a synonym for NULL shape(dims = NULL) # TensorShape(None) # Unknown rank, unknown size shape(3, 4) # TensorShape([3, 4]) # 2-D array (matrix) with 3 rows, 4 columns shape(NA, 4) # TensorShape([None, 4]) # 2-D array (matrix) with unknown rows, 4 columns shape(dims = c(NA, 4)) # TensorShape([None, 4]) # same as above; bypass ... and pass dims directly # --- inspect --- length(shape(dims = NULL)) # NA_integer_ length(shape(1,2,3,NA)) # 4L # ---convert --- x <- shape(dims = list(3L, 5L)) as.list(x) # list(3L, 5L) as.integer(x) # c(3L, 5L) as.numeric(x) # c(3, 5) as.double(x) # c(3, 5) # alias for as.numeric as_tensor(x) # tf.Tensor([3 5], shape=(2,), dtype=int32) # convert partially undefined shapes x <- shape(NA, 3) as.list(x) # list(NULL, 3L) as.integer(x) # c(NA, 3L) as_tensor(x) # tf.Tensor([-1 3], shape=(2,), dtype=int32) # unspecified dims default is -1 # as_tensor() converts undefined dimensions to -1, which is useful for # tf functions that only accept tensors for shapes, e.g, tf$reshape(tf$zeros(shape(8)), as_tensor(shape(NA, 4))) # tf.Tensor([[0. 0. 0. 0.] # [0. 0. 0. 0.]], shape=(2, 4), dtype=float32) # converting fully unknown shapes raises an error try(as.list(shape(dims = NULL))) # ValueError: as_list() is not defined on an unknown TensorShape. # test for rank first if this a concern: as.list_or_null <- function(x) if(is.na(length(x))) NULL else as.list(x) as.list_or_null(shape(dims = NULL)) # --- compare --- # Fully known shapes return TRUE if and only if each element is equal shape(3, 4) == shape(3, 4) # TRUE shape(3, 4) == shape(4, 4) # FALSE # two unknown dimensions are treated as equal shape(NA, 4) == shape(NA, 4) # TRUE shape(NA, 4) == shape(3, 4) # FALSE # Two unknown shapes, return TRUE shape(dims = NULL) == shape(dims = NULL) # TRUE # Comparing an unknown shape to a partially or fully defined shape returns FALSE shape(dims = NULL) == shape(NULL) # FALSE shape(dims = NULL) == shape(4) # FALSE values of length greater than one supplied to `...` are automatically flattened shape(1, c(2, 3), 4) # shape(1, 2, 3, 4) shape(1, shape(2, 3), 4) # shape(1, 2, 3, 4) shape(1, as_tensor(2, 3), 4) # shape(1, 2, 3, 4) # --- extract or replace --- # regular R-list semantics for `[`, `[[`, `[<-`, `[[<-` x <- shape(1, 2, 3) x[1] # TensorShape([1]) x[[1]] # 1L x[2:3] # TensorShape([2, 3]) x[-1] # TensorShape([2, 3]) x[1] <- 11 ; x # TensorShape([11, 2, 3]) x[1] <- shape(11) ; x # TensorShape([11, 2, 3]) x[1] <- list(11) ; x # TensorShape([11, 2, 3]) x[[1]] <- 22 ; x # TensorShape([22, 2, 3]) x[1:2] <- c(NA, 99) ; x # TensorShape([None, 99, 3]) x[1:2] <- shape(33, 44) ; x # TensorShape([33, 44, 3]) # --- concatenate --- c(shape(1), shape(2, 3), shape(4, NA)) # TensorShape([1, 2, 3, 4, None]) # --- merge --- merge(shape(NA, 2), shape(1 , 2)) # TensorShape([1, 2]) try(merge(shape(2, 2), shape(1, 2))) # ValueError: Shapes (2, 2) and (1, 2) are not compatible rm(x) # cleanup ## End(Not run)
TensorBoard is a tool inspecting and understanding your TensorFlow runs and graphs.
tensorboard( log_dir, action = c("start", "stop"), host = "127.0.0.1", port = "auto", launch_browser = getOption("tensorflow.tensorboard.browser", interactive()), reload_interval = 5, purge_orphaned_data = TRUE )
tensorboard( log_dir, action = c("start", "stop"), host = "127.0.0.1", port = "auto", launch_browser = getOption("tensorflow.tensorboard.browser", interactive()), reload_interval = 5, purge_orphaned_data = TRUE )
log_dir |
Directories to scan for training logs. If this is a named character vector then the specified names will be used as aliases within TensorBoard. |
action |
Specify whether to start or stop TensorBoard (TensorBoard will be stopped automatically when the R session from which it is launched is terminated). |
host |
Host for serving TensorBoard |
port |
Port for serving TensorBoard. If "auto" is specified (the default) then an unused port will be chosen automatically. |
launch_browser |
Open a web browser for TensorBoard after launching.
Defaults to |
reload_interval |
How often the backend should load more data. |
purge_orphaned_data |
Whether to purge data that may have been orphaned due to TensorBoard restarts. Disabling purge_orphaned_data can be used to debug data disappearance. |
When TensorBoard is passed a logdir at startup, it recursively walks the directory tree rooted at logdir looking for subdirectories that contain tfevents data. Every time it encounters such a subdirectory, it loads it as a new run, and the frontend will organize the data accordingly.
The TensorBoard process will be automatically destroyed when the R session
in which it is launched exits. You can pass action = "stop"
to manually
terminate TensorBoard.
URL for browsing TensorBoard (invisibly).
TensorFlow is an open source software library for numerical computation using data flow graphs. Nodes in the graph represent mathematical operations, while the graph edges represent the multidimensional data arrays (tensors) communicated between them. The flexible architecture allows you to deploy computation to one or more CPUs or GPUs in a desktop, server, or mobile device with a single API.
The TensorFlow API is composed of a set of Python modules that enable constructing and executing TensorFlow graphs. The tensorflow package provides access to the complete TensorFlow API from within R.
For additional documentation on the tensorflow package see https://tensorflow.rstudio.com
Maintainer: Tomasz Kalinowski [email protected] [contributor, copyright holder]
Authors:
JJ Allaire [copyright holder]
Yuan Tang [email protected] (ORCID) [copyright holder]
Other contributors:
Daniel Falbel [email protected] [contributor, copyright holder]
Dirk Eddelbuettel [email protected] [contributor, copyright holder]
Nick Golding [email protected] [contributor, copyright holder]
Google Inc. (Examples and Tutorials) [contributor, copyright holder]
Posit, PBC [copyright holder, funder]
Useful links:
Interface to main TensorFlow module. Provides access to top level classes
and functions as well as sub-modules (e.g. tf$nn
,
tf$contrib$learn
, etc.).
tf
tf
TensorFlow module
## Not run: library(tensorflow) hello <- tf$constant('Hello, TensorFlow!') zeros <- tf$Variable(tf$zeros(shape(1L))) tf$print(hello) tf$print(zeros) ## End(Not run)
## Not run: library(tensorflow) hello <- tf$constant('Hello, TensorFlow!') zeros <- tf$Variable(tf$zeros(shape(1L))) tf$print(hello) tf$print(zeros) ## End(Not run)
Tensor extract options
tf_extract_opts( style = getOption("tensorflow.extract.style"), ..., one_based = getOption("tensorflow.extract.one_based", TRUE), inclusive_stop = getOption("tensorflow.extract.inclusive_stop", TRUE), disallow_out_of_bounds = getOption("tensorflow.extract.dissallow_out_of_bounds", TRUE), warn_tensors_passed_asis = getOption("tensorflow.extract.warn_tensors_passed_asis", TRUE), warn_negatives_pythonic = getOption("tensorflow.extract.warn_negatives_pythonic", TRUE) )
tf_extract_opts( style = getOption("tensorflow.extract.style"), ..., one_based = getOption("tensorflow.extract.one_based", TRUE), inclusive_stop = getOption("tensorflow.extract.inclusive_stop", TRUE), disallow_out_of_bounds = getOption("tensorflow.extract.dissallow_out_of_bounds", TRUE), warn_tensors_passed_asis = getOption("tensorflow.extract.warn_tensors_passed_asis", TRUE), warn_negatives_pythonic = getOption("tensorflow.extract.warn_negatives_pythonic", TRUE) )
style |
one of |
... |
ignored |
one_based |
TRUE or FALSE, if one-based indexing should be used |
inclusive_stop |
TRUE or FALSE, if slices like |
disallow_out_of_bounds |
TRUE or FALSE, whether checks are performed on the slicing index to ensure it is within bounds. |
warn_tensors_passed_asis |
TRUE or FALSE, whether to emit a warning the
first time a tensor is supplied to |
warn_negatives_pythonic |
TRUE or FALSE, whether to emit
a warning the first time a negative number is supplied to |
an object with class "tf_extract_opts", suitable for passing to
[.tensorflow.tensor()
## Not run: x <- tf$constant(1:10) opts <- tf_extract_opts("R") x[1, options = opts] # or for more fine-grained control opts <- tf_extract_opts( one_based = FALSE, warn_tensors_passed_asis = FALSE, warn_negatives_pythonic = FALSE ) x[0:2, options = opts] ## End(Not run)
## Not run: x <- tf$constant(1:10) opts <- tf_extract_opts("R") x[1, options = opts] # or for more fine-grained control opts <- tf_extract_opts( one_based = FALSE, warn_tensors_passed_asis = FALSE, warn_negatives_pythonic = FALSE ) x[0:2, options = opts] ## End(Not run)
tf_function
constructs a callable that executes a TensorFlow graph created
by tracing the TensorFlow operations in f
. This allows the TensorFlow
runtime to apply optimizations and exploit parallelism in the computation
defined by f
.
tf_function(f, input_signature = NULL, autograph = TRUE, ...)
tf_function(f, input_signature = NULL, autograph = TRUE, ...)
f |
the function to be compiled |
input_signature |
A possibly nested sequence of |
autograph |
TRUE or FALSE. If TRUE (the default), you can use tensors in
R control flow expressions |
... |
additional arguments passed on to |
A guide to getting started with
tf.function
can
be found here.
TensorFlow Probability Module
tf_probability()
tf_probability()
Reference to TensorFlow Probability functions and classes
## Not run: library(tensorflow) ## one time setup: # reticulate::py_install("tensorflow_probability") tfp <- tf_probability() tfp$distributions$Normal(loc = 0, scale = 1) ## End(Not run)
## Not run: library(tensorflow) ## one time setup: # reticulate::py_install("tensorflow_probability") tfp <- tf_probability() tfp$distributions$Normal(loc = 0, scale = 1) ## End(Not run)
Enables TensorFlow to run under a different API version for compatibility with previous versions. For instance, this is useful to run TensorFlow 1.x code when using TensorFlow 2.x.
use_compat(version = c("v1", "v2"))
use_compat(version = c("v1", "v2"))
version |
The version to activate. Must be |
## Not run: library(tensorflow) use_compat("v1") ## End(Not run)
## Not run: library(tensorflow) use_compat("v1") ## End(Not run)
Set various random seeds required to ensure reproducible results. The
provided seed
value will establish a new random seed for R, Python, NumPy,
and TensorFlow. GPU computations and CPU parallelism will also be disabled by
default.
use_session_with_seed( seed, disable_gpu = TRUE, disable_parallel_cpu = TRUE, quiet = FALSE )
use_session_with_seed( seed, disable_gpu = TRUE, disable_parallel_cpu = TRUE, quiet = FALSE )
seed |
A single value, interpreted as an integer |
disable_gpu |
|
disable_parallel_cpu |
|
quiet |
|
This function must be called at the very top of your script (i.e.
immediately after library(tensorflow)
, library(keras)
, etc.). Any
existing TensorFlow session is torn down via tf$reset_default_graph()
.
This function takes all measures known to promote reproducible results from TensorFlow sessions, however it's possible that various individual TensorFlow features or dependent libraries escape its effects. If you encounter non-reproducible results please investigate the possible sources of the problem, contributions via pull request are very welcome!
Packages which need to be notified before and after the seed is set
can register for the "tensorflow.on_before_use_session" and
"tensorflow.on_use_session" hooks (see setHook()
) for additional
details on hooks).
TensorFlow session object, invisibly
By default the use_session_with_seed()
function
disables GPU and CPU parallelism, since both can result in
non-deterministic execution patterns (see
https://stackoverflow.com/questions/42022950/). You can optionally enable
GPU or CPU parallelism by setting the disable_gpu
and/or
disable_parallel_cpu
parameters to FALSE
.
## Not run: library(tensorflow) use_session_with_seed(42) ## End(Not run)
## Not run: library(tensorflow) use_session_with_seed(42) ## End(Not run)
View a serialized model from disk.
view_savedmodel(model_dir)
view_savedmodel(model_dir)
model_dir |
The path to the exported model, as a string. |
URL for browsing TensorBoard (invisibly).