您现在的位置是:首页 > 文章详情

安装适用于 Java 的 TensorFlow

日期:2018-06-05点击:321

安装适用于 Java 的 TensorFlow

TensorFlow 可提供在 Java 程序中使用的 API。这些 API 特别适合用于加载以 Python 语言创建的模型并在 Java 应用中运行这些模型。本指南将介绍如何安装适用于 Java 的 TensorFlow 并在 Java 应用中使用 TensorFlow。

警告:TensorFlow Java API 不在 TensorFlow API 稳定性保障的涵盖范围内。

支持的平台

本指南介绍如何安装适用于 Java 的 TensorFlow。虽然这些说明可能也适用于其他配置,但我们只在满足以下要求的计算机上验证过这些说明(而且我们只支持在此类计算机上按这些说明操作):

  • Ubuntu 16.04 或更高版本;64 位、x86
  • macOS X 10.11 (El Capitan) 或更高版本
  • Windows 7 或更高版本;64 位、x86

针对 Android 的安装说明位于单独的 Android TensorFlow 支持页面中。安装完成后,请查看这个适用于 Android 的完整 TensorFlow 示例

在 Maven 项目中使用 TensorFlow

如果您的项目使用 Apache Maven,请将以下内容添加到项目的 pom.xml 以使用 TensorFlow Java API:

<dependency> <groupId>org.tensorflow</groupId> <artifactId>tensorflow</artifactId> <version>1.6.0</version> </dependency> 

就这么简单。

示例

举个例子,以下步骤可以创建一个使用 TensorFlow 的 Maven 项目:

  1. 创建项目的 pom.xml
 <project> <modelVersion>4.0.0</modelVersion> <groupId>org.myorg</groupId> <artifactId>hellotf</artifactId> <version>1.0-SNAPSHOT</version> <properties> <exec.mainClass>HelloTF</exec.mainClass> <!-- The sample code requires at least JDK 1.7. --> <!-- The maven compiler plugin defaults to a lower version --> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.tensorflow</groupId> <artifactId>tensorflow</artifactId> <version>1.6.0</version> </dependency> </dependencies> </project> 
  1. 创建源文件 (src/main/java/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 { 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")); } } } } 
  1. 编译并执行:
# Use -q to hide logging from the mvn tool mvn -q compile exec:java 

上述命令应该会输出Hello from 版本 。如果是这样,则说明您已成功设置适用于 Java 的 TensorFlow,随时可以在 Maven 项目中使用此 API。如果不是,请访问 Stack Overflow 查找可行的解决方案。您可以跳过本文档的其余部分。

https://www.tensorflow.org/install/install_java

原文链接:https://yq.aliyun.com/articles/626888
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章