Last Updated: July 16, 2017
·
990
· ahmad_ragab

HelloTF in Clojure: Using the Tensorflow Java API

Tensorflow for Java is a still experimental, but fleshed out API for using TF on the JVM, that means we can use it Clojure, Yay!

There are some light-wrappers for TF in Clojure in order to make the inter-op more idiomatic, but you may be hesitant to try and work through two-layers of indirection (especially as the Java API is not fully stable). This is a wrapper-less implementation of the HelloTF example located on TensorFlow site.

Installing TensorFlow

While we don't have Maven, leiningen does allow us to include the java jar straightaway and you shouldn't have to worry about performing any special installation steps (for CPU only). If you use lein new app tf-demo to create a basic clojure app, you should just need to add

[org.tensorflow/tensorflow "1.2.1"] ;; or whatever is latest version at the time of reading

to your project.clj

Implementing the HelloTF example

(ns tf-demo.core
  (:gen-class)
  (:import (org.tensorflow Tensor
                           TensorFlow
                           Graph
                           Session)))

(defn -main
  "Execute basic HelloTF Example"
  [& args]
  (try (let [graph (let [g (Graph.)
                         value (str "Hello from " (TensorFlow/version))
                         t (Tensor/create (.getBytes value))]

                     (-> (.opBuilder g "Const" "MyConst")
                         (.setAttr "dtype" (.dataType t))
                         (.setAttr "value" t)
                         (.build))
                     g)]
         (try (let [output (-> (Session. graph)
                               (.runner)
                               (.fetch "MyConst")
                               (.run)
                               (.get 0))]
                (println (String. (.bytesValue output) "UTF-8")))))))

Running the code

lein run => "Hello from <version number>"