Prerequisites

Last update: Sun Oct 25 12:05:18 2020 -0500 (79503f6ee)

You need couple of things to get rTorch working:

  1. Install Python Anaconda. Preferably, for 64-bits, and above Python 3.6+. I have successfully tested Anaconda under four different operating systems: Windows (Win10 and Windows Server 2008); macOS (Sierra, Mojave and Catalina); Linux (Debian, Fedora and Ubuntu); and lastly, Solaris 10. All these tests are required by CRAN.

  2. Install R, Rtools and RStudio. I used two R versions R-3.6.3 and R-4.0.2.

  3. Install the R package reticulate, which is the one that provides the connection between R and Python.

  4. Install the stable version rTorch from CRAN, or the latest version under development via GitHub.

Note. While it is not mandatory to have a previously created a Python environment with Anaconda, where PyTorch and TorchVision have already been installed, it is another option if for some reason reticulate refuses to communicate with the conda environment. Keep in mind that you could also get the rTorch conda environment installed directly from the R console, in very similar fashion as in R-TensorFlow does. Use the function install_pytorch() to install a conda environment for PyTorch.

Installation

The rTorch package can be installed from CRAN or Github.

From CRAN:

From GitHub, install rTorch with:

which will install rTorch from the main or master branch.

If you want to play with the latest rTorch version, then install it from the develop branch, like this:

or clone with Git from the terminal with:

This will allow you to build rTorch from source.

Python Anaconda

If your preference is installing an Anaconda environment first, these are the steps:

Example

  1. Create a conda environment from the terminal with:
  1. Activate the new environment with
  1. Install the PyTorch related packages with:

The last part -c pytorch specifies the stable conda channel to download the PyTorch packages. Your conda installation may not work if you don’t indicate the channel.

Now, you can load rTorch in R or RStudio with:

Automatic installation

I used the idea for automatic installation in the tensorflow package for R, to create the function rTorch::install_pytorch(). This function will allow you to install a conda environment complete with all PyTorch requirements plus the packages you specify. Example:

This is explained in more detailed in the rTorch package manual.

Note. matplotlib and pandas are not really necessary for rTorch to work, but I was asked if matplotlib or pandas could work with PyTorch. So, I decided to install them for testing and experimentation. They both work.