Skip to content

Instantly share code, notes, and snippets.

@daveliepmann
Last active April 16, 2018 13:52
Show Gist options
  • Save daveliepmann/2d884bbdcf42137d1d39af256eb16dba to your computer and use it in GitHub Desktop.
Save daveliepmann/2d884bbdcf42137d1d39af256eb16dba to your computer and use it in GitHub Desktop.
"Construction of a trivial graph to add two float tensors and then repeated invocation of the single graph using placeholders", from https://github.com/tensorflow/tensorflow/issues/6781#issuecomment-271888411 in Clojure based on the original Java
;; make sure your ns has `(:import [org.tensorflow DataType Graph Output Session Tensor])`
;; or if in REPL, evaluate `(import [org.tensorflow DataType Graph Output Session Tensor])` first
;; Construct a graph to add two float Tensors, using placeholders.
(let [g (Graph.)
s (Session. g)
x (-> (.opBuilder g "Placeholder" "x")
(.setAttr "dtype" DataType/FLOAT)
(.build)
(.output 0))
;; (`y` is identical except for name)
y (-> (.opBuilder g "Placeholder" "y")
(.setAttr "dtype" DataType/FLOAT)
(.build)
(.output 0))
z (-> (.opBuilder g "Add" "z")
(.addInput x)
(.addInput y)
(.build)
(.output 0))
big-x (mapv float [1 2 3])
big-y (mapv float [4 5 6])]
;; Execute the graph multiple times, each time with a different value of x and y
(for [i (range (count big-x))]
(let [tx (Tensor/create (nth big-x i))
ty (Tensor/create (nth big-y i))
tz (-> (.runner s)
(.feed "x" tx)
(.feed "y" ty)
(.fetch "z")
(.run)
(.get 0))]
(println (nth big-x i) " + " (nth big-y i) " = " (.floatValue tz)))))
;; result:
1.0 + 4.0 = 5.0
2.0 + 5.0 = 7.0
3.0 + 6.0 = 9.0
(nil nil nil)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment