Skip to content

Instantly share code, notes, and snippets.

@rasmusab
Last active April 25, 2018 02:35
Show Gist options
  • Save rasmusab/a8de31f8d6b09d20fcc4 to your computer and use it in GitHub Desktop.
Save rasmusab/a8de31f8d6b09d20fcc4 to your computer and use it in GitHub Desktop.
An example of building a TensorFlow model from R using rPython
### An example of building a TensorFlow model from R using rPython ###
# For this script you need to
# 1. Have python 2.7 installed.
# 2. Install the rPython package in R.
# 3. Install Google's TensorFlow library as per these instructions:
# http://www.tensorflow.org/get_started/os_setup.md#binary_installation
### Here is how to setup and run a trivial TensorFlow model ###
# Load TensorFlow (I couldn't get this to work without setting sys.argv... )
library(rPython)
python.exec("
import sys
sys.argv = ['']
import tensorflow as tf
")
# Define a "hello world" TensorFlow model adding two numbers
python.exec("
a = tf.constant(10)
b = tf.constant(32)
sum = a + b
")
#Instantiate a TensorFlow session, and get the result into R.
# (we need the .tolist() to convert from the result into something
# that can be serialized by JSON and imported into R)
python.exec("
sess = tf.Session()
result = sess.run(sum)
")
result = python.get("result.tolist()")
# Tada! :)
print(result)
## [1] 42
@billyvreeland
Copy link

This is nice example. I have been trying to do something similar but am running into a "cannot import name pywrap_tensorflow" error when trying to import tensorflow. I know this is typically a circular reference error, but I haven't been able to figure out what is causing it. I was just curious if you ran into it when getting things set up.

Thanks!

@dennisthemenace2
Copy link

i get a problem when i have huger data sets. it breaks execution
Fehler in python.exec("\n for i in range(10):\n sess.run(train_step, feed_dict={x: trainX, y_: trainY})\n ") :
����

@prakashjayy
Copy link

No module named tensorflow.

I get this error when I run tensorflow from R. However from the python console it is running fine. What can be the reason?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment