?go語言有著很好的潛力,最近TensorFlow提供了go語言的API.這些API特別適合加載Python中創(chuàng)建的模型,并在Go應(yīng)用程序中執(zhí)行它們。不過這些API還沒有很穩(wěn)定,目前也只是支持Linux,Mac OSX平臺..
安裝
本文以MacOSX安裝為例
一 . Mac OS X上安裝TensorFlow
安裝TensorFlow有幾種方式可以選擇:
- virtualenv
- "native" pip
- Docker
- installing from sources
之前我是Docker安裝了,所以這里我選擇第一種virtualenv方式,更多方式請看官網(wǎng)
https://www.tensorflow.org/install/install_go
1 . 安裝pip
$ sudo easy_install pip
已經(jīng)安裝過了可以忽略.py2,和py3沖突解決方法請百度
2 . 安裝virtualenv
$ sudo pip install --upgrade virtualenv
3. 創(chuàng)建virtualenv環(huán)境
創(chuàng)建文件夾 :$ mkdir ~/tensorflow
如果你電腦裝了python2.7,執(zhí)行
$ virtualenv --system-site-packages ~/tensorflow
如果你電腦裝了python3.x,執(zhí)行
$ virtualenv --system-site-packages -p python3 ~/tensorflow
4 . 激活virtualenv環(huán)境
$ source ~/tensorflow/bin/activate
你會發(fā)現(xiàn)你的終端變成了這個樣子
(tensorflow)$
5 . 安裝TensorFlow 和所有激活TensorFlow所需要的包
如果你電腦裝了python2.7,執(zhí)行
(tensorflow)$ pip install --upgrade tensorflow
如果你電腦裝了python3.x,執(zhí)行
(tensorflow)$ pip3 install --upgrade tensorflow
附圖:下載比較慢
這里寫圖片描述
二 . 安裝TensorFlow for Go
前文說到的TensorFlow要安裝好.
1. 下載并解壓TensorFlow C庫文件 到/usr/local/lib
執(zhí)行以下命令:
$ TF_TYPE="cpu" # Change to "gpu" for GPU support
$ 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
第三條語句比較長..
2 . C庫安裝后,下載合適的包和依賴
執(zhí)行
$ go get github.com/tensorflow/tensorflow/tensorflow/go
3 . 確認TensorFlow forGO 已經(jīng)生效
$ go test github.com/tensorflow/tensorflow/tensorflow/go
示例
創(chuàng)建一個hello_tf.go文件,代碼如下
package main
import (
tf "github.com/tensorflow/tensorflow/tensorflow/go"
"github.com/tensorflow/tensorflow/tensorflow/go/op"
"fmt"
)
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())
}
運行 hello_tf.go
go run hello_tf.go
----------
運行結(jié)果:
Hello from TensorFlow version 1.3.0
同時運行結(jié)果中可能會產(chǎn)生一些警告,我們可以忽略.運行截圖
這里寫圖片描述