【环境配置】JAVA调用Tensorflow模型

本文详细介绍了在Windows环境下使用Eclipse IDE搭建TensorFlow Java开发环境的过程,并提供了测试代码示例,确保环境配置正确。同时,针对可能出现的错误,如无法找到TensorFlow本地库等问题,给出了具体解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 测试通过的环境
名称版本
Windowswin10_64位
IDEEclipse 2018-12
Tensorflow1.6.0
JDK1.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 解决办法:
  1. 确保所使用的JDK是1.7版本以上的64位(与电脑位数相一致)
  2. tensorflow_jni.dll要放在项目根目录下。其中tensorflow_jni.dll可以通过解压libtensorflow_jni-1.6.0.jar得到
    在这里插入图片描述
  3. 查看编译器compiler是否支持1.8以上的,我当时使用的MyEclipse2014的compiler最高仅支持1.7。查看compiler的方法如下图(window-preferences,然后直接搜索compiler)
    在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值