1. 测试通过的环境
名称 | 版本 |
Windows | win10_64位 |
IDE | Eclipse 2018-12 |
Tensorflow | 1.6.0 |
JDK | 1.8 (Eclipse 2018-12自带) |
2. JAVA版本的Tensorflow测试代码
测试代码项目文件百度网盘下载传送门
import org.tensorflow.Graph;
import org.tensorflow.Session;
import org.tensorflow.Tensor;
import org.tensorflow.TensorFlow;
public class test {
public static void main(String[] args) throws Exception {
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"));
}
}
}
}
/* 输出
Hello from 1.6.0
*/
3. 可能遇到的问题及解决方案
3.1 问题:
Exception in thread "main" java.lang.UnsatisfiedLinkError: Cannot find TensorFlow native library for OS: windows, architecture: x86. See https://github.com/tensorflow/tensorflow/tree/master/java/README.md for possible solutions (such as building the library from source).
at org.tensorflow.NativeLibrary.load(NativeLibrary.java:66)
at org.tensorflow.TensorFlow.init(TensorFlow.java:27)
at org.tensorflow.TensorFlow.<clinit>(TensorFlow.java:31)
at ai.advance.project.App.main(App.java:12)
3.2 解决办法:
- 确保所使用的JDK是1.7版本以上的64位(与电脑位数相一致)
tensorflow_jni.dll
要放在项目根目录下。其中tensorflow_jni.dll
可以通过解压libtensorflow_jni-1.6.0.jar
得到- 查看编译器compiler是否支持1.8以上的,我当时使用的MyEclipse2014的compiler最高仅支持1.7。查看compiler的方法如下图(window-preferences,然后直接搜索compiler)