Skip to content

Instantly share code, notes, and snippets.

@fooqri
Last active September 21, 2020 04:37
Show Gist options
  • Save fooqri/b59e2634b924072652df4991b9f83167 to your computer and use it in GitHub Desktop.
Save fooqri/b59e2634b924072652df4991b9f83167 to your computer and use it in GitHub Desktop.
Notes for adding tensorflow support to Emacs Org-mode code blocks on OS X

Getting TensorFlow working for Org-mode notes in Emacs

Prerequisites:

Steps:

  1. Activate tensorflow virtual env on command line
    source ~/tensorflow/bin/activate
    
  2. Create a kernel in the activated environment, this environment will be used by ipython so TensorFlow will be included when run from org-mode notes using this kernel name in the code block.
    python -m ipykernel install --user --name py3tf --display-name "Python 3 (with tensorflow)"
    
  3. Use iPython as the language and add a kernel parameter in org-mode code blocks, session parameter also required.

Show results in pop-up window

# use C-c C-c to execute code, results will show in popup window
#+BEGIN_SRC ipython :session mysession :exports both :kernel py3tf
import tensorflow as tf

a = tf.placeholder("float")
b = tf.placeholder("float")
y = tf.mul(a, b)
sess = tf.Session()
print("result: ", sess.run(y, feed_dict={a: 30, b: 7}))
#+END_SRC

Show results in the curent buffer under code block

# use C-c C-c to execute code, results will show in a generated result block, below code block
#+BEGIN_SRC ipython :session mysession :exports both :kernel py3tf :results output
import tensorflow as tf
sess = tf.Session()

identity_matrix = tf.diag([1.0, 1.0, 1.0])
A = tf.truncated_normal([2, 3])
B = tf.fill([2,3], 5.0)
C = tf.random_uniform([3,2])
D = tf.convert_to_tensor(np.array([[1., 2., 3.],[-3., -7., -1.],[0., 5., -2.]]))
print("I: ", sess.run(identity_matrix))
print("A: ", sess.run(A))
print("B: ", sess.run(B))
print("C: ", sess.run(C))
print("D: ", sess.run(D))
print("Transpose D: ", sess.run(tf.transpose(D)))
print("A + B: ", sess.run(A+B))
print("B - B: ", sess.run(B-B))
print("B * I: ", sess.run(tf.matmul(B, identity_matrix)))
#+END_SRC

#+RESULTS:
#+begin_example
I:  [[ 1.  0.  0.]
 [ 0.  1.  0.]
 [ 0.  0.  1.]]
A:  [[ 0.10231017  0.26816747 -0.51984078]
 [-0.2361702   0.48887771 -0.16014548]]
B:  [[ 5.  5.  5.]
 [ 5.  5.  5.]]
C:  [[ 0.96642244  0.34907722]
 [ 0.42412615  0.95863414]
 [ 0.36120582  0.23735201]]
D:  [[ 1.  2.  3.]
 [-3. -7. -1.]
 [ 0.  5. -2.]]
Transpose D:  [[ 1. -3.  0.]
 [ 2. -7.  5.]
 [ 3. -1. -2.]]
A + B:  [[ 5.25147152  4.23565722  4.04556942]
 [ 4.97981024  4.93410921  3.22310114]]
B - B:  [[ 0.  0.  0.]
 [ 0.  0.  0.]]
B * I:  [[ 5.  5.  5.]
 [ 5.  5.  5.]]
#+end_example
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment