GO + Tensorflow - 安裝

Ref: https://www.tensorflow.org/install/lang_go

1. 安裝 tensorflow C library

    (1) 下載: 可以參考上述網址, 用 wget 指令下載適合的檔案
     ( Linux 有 CPU 和 GPU 版本 )

    (2) 解壓縮

          安裝到 /usr/local
sudo tar -C /usr/local -xzf (downloaded file)

   (3) Linker

sudo ldconfig


    (4) 測試

    - 造一個 hello_tf.c

#include <stdio.h>
#include <tensorflow/c/c_api.h>
int main() {
  printf("Hello from TensorFlow C library version %s\n", TF_Version());
  return 0;
}

   - 編譯執行

gcc hello_tf.c -ltensorflow -o hello_tf
./hello_tf

  結果:

      Hello from TensorFlow C library version 1.14.0

   表示 ok

2. 下載 Tensorflow GO package

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

    測試

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

  ok        github.com/tensorflow/tensorflow/tensorflow/go        2.068s

3. 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 from TensorFlow version 1.14.0






留言

熱門文章