WUYUANS
Just for Sharing

TensorFlow笔记1

2017年08月21日 分类:学习笔记GolangTensorFlow

最近一段时间都在用Golang写东西,发现TensorFLow也有Golang的API,可以在Golang代码里嵌入TensorFlow模块。开始挖TensorFlow的坑,边记边学,看看能坚持到什么时候,:)

0. 环境

  • 操作系统:macOS Sierra
  • TensorFlow版本:1.3.0
  • 安装方式:pip
  • Golang版本:go1.7.3 darwin/amd64

1. 安装TensorFlow

首先我们要安装TensorFlow,有4种方法,virtualenv、pip、docker、source。pip的安装方式比较简单,一条命令就能搞定。

pip install tensorflow # Python 2.7; CPU support
pip3 install tensorflow # Python 3.n; CPU support

参考文档 https://www.tensorflow.org/install/install_mac

注意:TensorFlow从1.2.0开始不再支持mac环境下的GPU。

1.1 测试TensorFlow

# Python
import tensorflow as tf
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(hello))

出现Hello,TensorFlow就说明安装成功了。

2. 安装C扩展库

TF_TYPE="cpu"
TARGET_DIRECTORY='/usr/local'
curl -L "https://storage.googleapis.com/tensorflow/libtensorflow/libtensorflow-${TF_TYPE}-$(go env GOOS)-x86_64-1.3.0.tar.gz" | sudo tar -C $TARGET_DIRECTORY -xz

TF_TYPE 指定TensorFlow运行类型,可以选择 cpu、gpu。TARGET_DIRECTORY 执行库文件的安装位置。

3. 安装Golang依赖包

使用go get命令安装,可能需要梯子。

go get github.com/tensorflow/tensorflow/tensorflow/go
go test github.com/tensorflow/tensorflow/tensorflow/go

4. Hello World

还是使用官方的例子,新建文件hello_tf.go。

package main

import (
 "fmt"
 tf "github.com/tensorflow/tensorflow/tensorflow/go"
 "github.com/tensorflow/tensorflow/tensorflow/go/op"
)

func main() {
 // Construct a graph with an operation that produces a string constant.
 s := op.NewScope()
 c := op.Const(s, "Hello from TensorFlow version "+tf.Version())
 graph, err := s.Finalize()
 if err != nil {
  panic(err)
 }

 // Execute the graph in a session.
 sess, err := tf.NewSession(graph, nil)
 if err != nil {
  panic(err)
 }
 output, err := sess.Run(nil, []tf.Output{c}, nil)
 if err != nil {
  panic(err)
 }
 fmt.Println(output[0].Value())
}

执行 go run hello_tf.go

输出 Hello from TensorFlow version 1.3.0

安装成功!

5. 总结

按照官方的教程,没出现什么大问题,但是最新的发行版在mac下不支持gpu,还是有点遗憾的。本机主要拿来学习的话cpu也够用了,将来可以考虑在Ubuntu下装一个用来运行代码。

还有一点是每次执行代码的时候会出现几个warning,设置环境变量或者重新编译就行了,没什么影响,以后再解决吧。

参考文档:https://www.tensorflow.org/install/install_go

作者:wuyuan 本文来自Wuyuan's Blog 转载请注明,谢谢! 文章地址: https://www.wuyuans.com/blog/detail/132