2017年10月14日 星期六

Tensorflow for JAVA



 微軟的線上 jupyter notebook
https://notebooks.azure.com/


Tensorflow for Python
深度學習的好網站
https://ithelp.ithome.com.tw/articles/10187648
該作者的github
https://github.com/c1mone/Tensorflow-101/blob/master/notebooks/3_MNIST_CNN_Layer_Visualization.ipynb

Tensorflow for JAVA on Windows
https://www.tensorflow.org/install/install_java

下載下面兩個檔案
https://storage.googleapis.com/tensorflow/libtensorflow/libtensorflow-1.3.0.jar
https://storage.googleapis.com/tensorflow/libtensorflow/libtensorflow_jni-cpu-windows-x86_64-1.3.0.zip

HelloTF.java的原始碼如下,紅色是我加的,其他都跟官網一樣。
import org.tensorflow.Graph;
import org.tensorflow.Session;
import org.tensorflow.Tensor;
import org.tensorflow.TensorFlow;

public class HelloTF {
  public static void main(String[] args) throws Exception {
System.loadLibrary("tensorflow_jni");
    try (Graph g = new Graph()) {
      final String value = "Hello from " + TensorFlow.version();

      // Construct the computation graph with a single operation, a constant
      // named "MyConst" with a value "value".
      try (Tensor t = Tensor.create(value.getBytes("UTF-8"))) {
        // The Java API doesn't yet include convenience functions for adding operations.
        g.opBuilder("Const", "MyConst").setAttr("dtype", t.dataType()).setAttr("value", t).build();
      }

      // Execute the "MyConst" operation in a Session.
      try (Session s = new Session(g);
           Tensor output = s.runner().fetch("MyConst").run().get(0)) {
        System.out.println(new String(output.bytesValue(), "UTF-8"));
      }
    }
  }
}


編譯
javac -cp libtensorflow-1.3.0.jar HelloTF.java
執行
java -cp libtensorflow-1.3.0.jar;. -Djava.library.path=jni HelloTF

執行
java -cp libtensorflow-1.3.0.jar;. -Djava.library.path="存放tensorflow_jni.dll檔案的資料夾" HelloTF

結果
2017-10-15 12:33:30.150485: W tensorflow/core/platform/cpu_feature_guard.cc:45]
The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2017-10-15 12:33:30.150485: W tensorflow/core/platform/cpu_feature_guard.cc:45]
The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
Hello from 1.3.0

另一個範例程式
https://github.com/tensorflow/tensorflow/blob/r1.3/tensorflow/java/src/main/java/org/tensorflow/examples/LabelImage.java

需要搭配下面的參考檔案
https://storage.googleapis.com/download.tensorflow.org/models/inception5h.zip

執行的方式
java -cp libtensorflow-1.3.0.jar;. -Djava.library.path="存放tensorflow_jni的資料夾" -jar LabelImage.jar "放tensorflow_inception_graph.pb的資料夾"  "測試的圖片.jpg"

結果
2017-10-19 09:41:56.723777: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructio
ns, but these are available on your machine and could speed up CPU computations.
BEST MATCH: bolo tie (26.88% likely)