So, how come we are able to use TensorFlow from R?

Which pc language is most intently related to TensorFlow? Whereas on the TensorFlow for R weblog, we’d in fact like the reply to be R, likelihood is it’s Python (although TensorFlow has official bindings for C++, Swift, Javascript, Java, and Go as properly).

So why is it you’ll be able to outline a Keras mannequin as

mannequin <- keras_model_sequential() %>%
  layer_dense(items = 32, activation = "relu") %>%
  layer_dense(items = 1)

(good with %>%s and all!) – then prepare and consider it, get predictions and plot them, all that with out ever leaving R?

The quick reply is, you might have keras, tensorflow and reticulate put in.
reticulate embeds a Python session inside the R course of. A single course of means a single handle house: The identical objects exist, and will be operated upon, no matter whether or not they’re seen by R or by Python. On that foundation, tensorflow and keras then wrap the respective Python libraries and allow you to write R code that, in truth, appears like R.

This submit first elaborates a bit on the quick reply. We then go deeper into what occurs within the background.

One observe on terminology earlier than we leap in: On the R facet, we’re making a transparent distinction between the packages keras and tensorflow. For Python we’re going to use TensorFlow and Keras interchangeably. Traditionally, these have been completely different, and TensorFlow was generally regarded as one potential backend to run Keras on, moreover the pioneering, now discontinued Theano, and CNTK. Standalone Keras does nonetheless exist, however current work has been, and is being, completed in tf.keras. In fact, this makes Python Keras a subset of Python TensorFlow, however all examples on this submit will use that subset so we are able to use each to confer with the identical factor.

So keras, tensorflow, reticulate, what are they for?

Firstly, nothing of this is able to be potential with out reticulate. reticulate is an R package deal designed to permit seemless interoperability between R and Python. If we completely needed, we may assemble a Keras mannequin like this:

<class 'tensorflow.python.keras.engine.sequential.Sequential'>

We may go on including layers …

m$add(tf$keras$layers$Dense(32, "relu"))


However who would wish to? If this had been the one approach, it’d be much less cumbersome to straight write Python as an alternative. Plus, as a person you’d should know the whole Python-side module construction (now the place do optimizers stay, at present: tf.keras.optimizers, tf.optimizers …?), and sustain with all path and title modifications within the Python API.

That is the place keras comes into play. keras is the place the TensorFlow-specific usability, re-usability, and comfort options stay.
Performance offered by keras spans the entire vary between boilerplate-avoidance over enabling elegant, R-like idioms to offering technique of superior characteristic utilization. For example for the primary two, contemplate layer_dense which, amongst others, converts its items argument to an integer, and takes arguments in an order that enable it to be “pipe-added” to a mannequin: As a substitute of

mannequin <- keras_model_sequential()
mannequin$add(layer_dense(items = 32L))

we are able to simply say

mannequin <- keras_model_sequential()
mannequin %>% layer_dense(items = 32)

Whereas these are good to have, there’s extra. Superior performance in (Python) Keras largely will depend on the power to subclass objects. One instance is customized callbacks. In case you had been utilizing Python, you’d should subclass tf.keras.callbacks.Callback. From R, you’ll be able to create an R6 class inheriting from KerasCallback, like so

CustomCallback <- R6::R6Class("CustomCallback",
    inherit = KerasCallback,
    public = list(
      on_train_begin = perform(logs) {
        # do one thing
      on_train_end = perform(logs) {
        # do one thing

It is because keras defines an precise Python class, RCallback, and maps your R6 class’ strategies to it.
One other instance is custom models, launched on this weblog about a year ago.
These fashions will be educated with customized coaching loops. In R, you utilize keras_model_custom to create one, for instance, like this:

m <- keras_model_custom(title = "mymodel", perform(self) {
  self$dense1 <- layer_dense(items = 32, activation = "relu")
  self$dense2 <- layer_dense(items = 10, activation = "softmax")
  perform(inputs, masks = NULL) {
    self$dense1(inputs) %>%

Right here, keras will make sure that an precise Python object is created which subclasses tf.keras.Mannequin and when known as, runs the above nameless perform().

In order that’s keras. What concerning the tensorflow package deal? As a person you solely want it when it’s a must to do superior stuff, like configure TensorFlow gadget utilization or (in TF 1.x) entry components of the Graph or the Session. Internally, it’s utilized by keras closely. Important inner performance consists of, e.g., implementations of S3 strategies, like print, [ or +, on Tensors, so you’ll be able to function on them like on R vectors.

Now that we all know what every of the packages is “for”, let’s dig deeper into what makes this potential.

Present me the magic: reticulate

As a substitute of exposing the subject top-down, we comply with a by-example method, increase complexity as we go. We’ll have three eventualities.

First, we assume we have already got a Python object (that has been constructed in no matter approach) and have to convert that to R. Then, we’ll examine how we are able to create a Python object, calling its constructor. Lastly, we go the opposite approach spherical: We ask how we are able to move an R perform to Python for later utilization.

State of affairs 1: R-to-Python conversion

Let’s assume now we have created a Python object within the world namespace, like this:

So: There’s a variable, known as x, with worth 1, residing in Python world. Now how can we convey this factor into R?

We all know the principle entry level to conversion is py_to_r, outlined as a generic in conversion.R:

py_to_r <- perform(x) {

… with the default implementation calling a perform named py_ref_to_r:

Rcpp : You simply write your C++ perform, and Rcpp takes care of compilation and offers the glue code essential to name this perform from R.

So py_ref_to_r actually is written in C++:

.Call(`_reticulate_py_ref_to_r`, x)

which lastly wraps the “actual” factor, the C++ perform py_ref_to_R we noticed above.

Through py_ref_to_r_with_convert in #1, a one-liner that extracts an object’s “convert” characteristic (see beneath)

Extending Python Guide.

In official phrases, what reticulate does it embed and lengthen Python.
Embed, as a result of it allows you to use Python from inside R. Prolong, as a result of to allow Python to name again into R it must wrap R capabilities in C, so Python can perceive them.

As a part of the previous, the specified Python is loaded (Py_Initialize()); as a part of the latter, two capabilities are outlined in a brand new module named rpycall, that might be loaded when Python itself is loaded.

Global Interpreter Lock, this isn’t robotically the case when different implementations are used, or C is used straight. So call_python_function_on_main_thread makes certain that except we are able to execute on the principle thread, we wait.

That’s it for our three “spotlights on reticulate”.


It goes with out saying that there’s so much about reticulate we didn’t cowl on this article, equivalent to reminiscence administration, initialization, or specifics of knowledge conversion. Nonetheless, we hope we had been in a position to shed a bit of sunshine on the magic concerned in calling TensorFlow from R.

R is a concise and stylish language, however to a excessive diploma its energy comes from its packages, together with those who can help you name into, and work together with, the surface world, equivalent to deep studying frameworks or distributed processing engines. On this submit, it was a particular pleasure to concentrate on a central constructing block that makes a lot of this potential: reticulate.

Thanks for studying!

BERT from R

Posit AI Weblog: Picture segmentation with U-Web