Google is committed to advancing racial equity for Black communities. See how.

安裝 TensorFlow for Go

TensorFlow 提供了 Go API,特別適合用於載入以 Python 建立的模型,並且在 Go 應用程式中執行這些模型。

支援的平台

下列系統支援 TensorFlow for Go:

  • Linux 64 位元 x86
  • macOS X 10.12.6 (Sierra) 或較新版本

設定

TensorFlow C 程式庫

請安裝 TensorFlow Go 套件所需的 TensorFlow C 程式庫

下載

請下載並安裝 TensorFlow Go 套件及其依附元件:

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

然後,請驗證安裝項目:

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

建構

範例程式

安裝 TensorFlow Go 套件後,請使用下列原始碼 (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())
}

執行

執行範例程式:

go run hello_tf.go

指令輸出:Hello from TensorFlow version number

程式可能會產生下列警告訊息,你可以忽略這些訊息:

W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library
wasn't compiled to use *Type* instructions, but these are available on your
machine and could speed up CPU computations.

從原始碼開始建構

TensorFlow 為開放原始碼。請閱讀指示,瞭解如何從原始碼開始建構 TensorFlow for Go。