A Minimal rTorch Book
2020-11-19
Prerequisites
Last update: Sun Oct 25 12:05:18 2020 -0500 (79503f6ee)
You need couple of things to get rTorch working:
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.
Install R, Rtools and RStudio. I used two R versions R-3.6.3 and R-4.0.2.
Install the R package reticulate, which is the one that provides the connection between R and Python.
Install the stable version
rTorchfrom CRAN, or the latest version under development via GitHub.
Note. While it is not mandatory to have a previously created a
Pythonenvironment withAnaconda, wherePyTorchandTorchVisionhave already been installed, it is another option if for some reasonreticulaterefuses to communicate with the conda environment. Keep in mind that you could also get therTorchconda environment installed directly from theRconsole, in very similar fashion as in R-TensorFlow does. Use the functioninstall_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
- Create a
condaenvironment from the terminal with:
- Activate the new environment with
- Install the
PyTorchrelated 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:
rTorch:::install_conda(package="pytorch=1.4", envname="r-torch",
conda="auto", conda_python_version = "3.6", pip=FALSE,
channel="pytorch",
extra_packages=c("torchvision",
"cpuonly",
"matplotlib",
"pandas"))This is explained in more detailed in the rTorch package manual.
Note.
matplotlibandpandasare not really necessary forrTorchto work, but I was asked ifmatplotliborpandascould work withPyTorch. So, I decided to install them for testing and experimentation. They both work.