Understanding Tensorflow using Go
原文: https://pgaleone.eu/tensorflow/go/2017/05/29/understanding-tensorflow-using-go/
Tensorflow is not a Machine Learning specific library, instead, is a general purpose computation library that represents computations with graphs. Its core is implemented in C++ and there are also bindings for different languages. The bindings for the Go programming language, differently from the Python ones, are a useful tool not only for using Tensorflow in Go but also for understanding how Tensorflow is implemented under the hood.
The bindings
Officially, the Tensorflow’s developers released:
- The C++ source code: the real Tensorflow core where the high & low level operations are concretely implemented.
- The Python bindings & the Python library: the bindings are automatically generated from the C++ implementation, in this way we can use Python to invoke C++ functions: that’s how, for instance, the core of numpy is implemented. The library, moreover, combines calls to the bindings in order to define the higher level API that everyone’s using Tensorflow knows well.
- The Java bindings
- The Go binding
Being a Gopher and not a Java lover, I started looking at the Go bindings in order to understand what kind of tasks they were created for.
The Go bindings

The Gopher (created by Takuya Ueda (@tenntenn). Licensed under the Creative Commons 3.0 Attributions license)
overlapping the Tensorflow Logo.
The first thing to note is that the Go API, for admission of the maintainers itself, lacks the Variable support: this API is designed to use trained models and not for trainingmodels from scratch. This is clearly stated in the Installing Tensorflow for Go:
TensorFlow provides APIs for use in Go programs. These APIs are particularly well-suited to loading models created in Python and executing them within a Go application.
If we’re not interested in training ML models: hooray! If, instead, you’re interested in training models here’s an advice:
Be a real gopher, keep it simple! Use Python to define & train models; you can always load trained models and using them with Go later!
In short: the go bindings can be used to import and define constants graphs; where constant, in this context, means that there’s no training process involved and thus no trainable variables.
Let’s now start diving into Tensorflow using Go: let’s create our first application.
In the following, I suppose that the reader has its Go environment ready and the Tensorflow bindings compiled and installed as explained in the README.
Understand Tensorflow structure
Let’s repeat what Tensorflow is (kept from the Tensorflow website, the emphasis is mine):
TensorFlow™ is an open source software library for numerical computation using data flow graphs. Nodes in the graph represent mathematical operations, while the graph edges represent the multidimensional data arrays (tensors) communicated between them.
We can think of Tensorflow as a descriptive language, a bit like SQL, in which you describe what you want and let the underlying engine (the database) parse your query, check for syntactic and semantic errors, convert it to its private representation, optimize it and compute the results: all this to give you the correct results.
Therefore, what we really do when we use any of the available APIs is to describe a graph: the evaluation of the graph starts when we place it into a Session and explicitly decide to Run the graph within the Session.
Knowing this, let’s try to define a computational graph and evaluate it within a Session. The API documentation gives us a pretty clear list of the available methods within the packages tensorflow (shorthanded tf) & op.
As we can see, these two packages contains everything we need to define and evaluate a graph.
The former contains the functions to construct the basic “empty” structures like the Graph itself, the latter is the most important package that contains the bindings automatically generated from the C++ implementation.
However, suppose that we want to compute the matrix multiplication between AA and xx where
I suppose that the reader is already familiar with the tensorflow graph definition idea and knows what placeholders are and how they work. The code below is the first attempt that a Tensorflow Python bindings user would make. Let’s call this file attempt1.go
package main
import (
"fmt"
tf "github.com/tensorflow/tensorflow/tensorflow/go"
"github.com/tensorflow/tensorflow/tensorflow/go/op"
)
func main() {
// Let's describe what we want: create the graph
// We want to define two placeholder to fill at runtime
// the first placeholder A will be a [2, 2] tensor of integers
// the second placeholder x will be a [2, 1] tensor of intergers
// Then we want to compute Y = Ax
// Create the first node of the graph: an empty node, the root of our graph
root := op.NewScope()
// Define the 2 placeholders
A := op.Placeholder(root, tf.Int64, op.PlaceholderShape(tf.MakeShape(2, 2)))
x := op.Placeholder(root, tf.Int64, op.PlaceholderShape(tf.MakeShape(2, 1)))
// Define the operation node that accepts A & x as inputs
product := op.MatMul(root, A, x)
// Every time we passed a `Scope` to an operation, we placed that
// operation **under** that scope.
// As you can see, we have an empty scope (created with NewScope): the empty scope
// is the root of our graph and thus we denote it with "/".
// Now we ask tensorflow to build the graph from our definition.
// The concrete graph is created from the "abstract" graph we defined
// using the combination of scope and op.
graph, err := root.Finalize()
if err != nil {
// It's useless trying to handle this error in any way:
// if we defined the graph wrongly we have to manually fix the definition.
// It's like a SQL query: if the query is not syntactically valid
// we have to rewrite it
panic(err.Error())
}
// If here: our graph is syntatically valid.
// We can now place it within a Session and execute it.
var sess *tf.Session
sess, err = tf.NewSession(graph, &tf.SessionOptions{})
if err != nil {
panic(err.Error())
}
// In order to use placeholders, we have to create the Tensors
// containing the values to feed into the network
var matrix, column *tf.Tensor
// A = [ [1, 2], [-1, -2] ]
if matrix, err = tf.NewTensor([2][2]int64{ {1, 2}, {-1, -2} }); err != nil {
panic(err.Error())
}
// x = [ [10], [100] ]
if column, err = tf.NewTensor([2][1]int64{ {10}, {100} }); err != nil {
panic(err.Error())
}
var results []*tf.Tensor
if results, err = sess.Run(map[tf.Output]*tf.Tensor{
A: matrix,
x: column,
}, []tf.Output{product}, nil); err != nil {
panic(err.Error())
}
for _, result := range results {
fmt.Println(result.Value().([][]int64))
}
}
The code is completely commented and I invite the reader to read every single comment.
Now, the Tensorflow-Python user expects that this code compiles and works fine. Let’s see if he’s right:
go run attempt1.go
Here’s what he got:
panic: failed to add operation "Placeholder": Duplicate node name in graph: 'Placeholder'
wait: what’s going on here? Apparently, there are 2 operations “Placeholder” with the same name “Placeholder”.
Understanding Tensorflow using Go的更多相关文章
- TensorFlow Playground
A Neural Network Playground Understanding neural networks with TensorFlow Playground 机器之心翻译
- (转)The Road to TensorFlow
Stephen Smith's Blog All things Sage 300… The Road to TensorFlow – Part 7: Finally Some Code leave a ...
- (转) Written Memories: Understanding, Deriving and Extending the LSTM
R2RT Written Memories: Understanding, Deriving and Extending the LSTM Tue 26 July 2016 When I was ...
- TensorFlow 中文资源全集,官方网站,安装教程,入门教程,实战项目,学习路径。
Awesome-TensorFlow-Chinese TensorFlow 中文资源全集,学习路径推荐: 官方网站,初步了解. 安装教程,安装之后跑起来. 入门教程,简单的模型学习和运行. 实战项目, ...
- 在 TensorFlow 中实现文本分类的卷积神经网络
在TensorFlow中实现文本分类的卷积神经网络 Github提供了完整的代码: https://github.com/dennybritz/cnn-text-classification-tf 在 ...
- 那些令人惊艳的TensorFlow扩展包和社区贡献模型
随着TensorFlow发布的,还有一个models库(仓库地址:https://github.com/tensorflow/models),里面包含官方及社群所发布的一些基于TensorFlow实现 ...
- 5个最好的TensorFlow网络课程
1. Introduction to TensorFlow for Artificial Intelligence, Machine Learning and Deep Learning This c ...
- [转] Implementing a CNN for Text Classification in TensorFlow
Github上的一个开源项目,文档讲得极清晰 Github - https://github.com/dennybritz/cnn-text-classification-tf 原文- http:// ...
- Tensorflow实例:利用LSTM预测股票每日最高价(一)
RNN与LSTM 这一部分主要涉及循环神经网络的理论,讲的可能会比较简略. 什么是RNN RNN全称循环神经网络(Recurrent Neural Networks),是用来处理序列数据的.在传统的神 ...
随机推荐
- hbase 批量插入api
1.数据格式a.txt: 1363157985066 13726230503 00-FD-07-A4-72-B8:CMCC 120.196.100.82 i02.c.aliimg.com 24 27 ...
- Office 365 离线安装
原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://yueque.blog.51cto.com/4580340/1707479 有个O ...
- Verilog语言:还真的是人格分裂的语言
人气腹语术师天愿在现场披露了被人偶搭档夺取灵魂的腹语术师将妻子杀害的表演节目.天愿真的陷入了多重人格,命令自己杀害妻子和子的人偶的人格出现了.为了不(让自己)杀害和弟子登川有外遇的妻子,天愿提出委托想 ...
- Haskell示例
i :: Int i = --add, sub :: Int -> Int -> Int add, sub :: (Num a) => a -> a -> a add a ...
- Android实现微信自己主动抢红包的程序
简单实现了微信自己主动抢红包的服务,原理就是依据keyword找到对应的View, 然后自己主动点击.主要是用到AccessibilityService这个辅助服务,基本能够满足自己主动抢红包的功能, ...
- linux 从百度网盘下载文件的方法
linux 从百度网盘下载文件的方法 发表于2015 年 月 日由shenwang 方法1.wget wget是在Linux下开发的开放源代码的软件,作者是Hrvoje Niksic,后来被移植到包括 ...
- shell script 在if 的判断条件正则表达式=~中引号问题
今天在脚本里运行if判断的时候,总是进不了对应的分支,检查正则表达式也没有错误.单独拿到shell里面执行还是显示没有匹配.比较奇怪,就搜了下,才发现是在=~ 后面的正则表达式上不能加上引号,而且以点 ...
- (译)Getting Started——1.2.1 Defining the Concept(确定理念)
每个出色的应用都是由理念开始的.在开发应用时,你不需要把理念完善和完成后再进行开发.但是你确实需要确定你要做什么,做完后的效果如何. 为了定义理念,问自己以下的问题: 应用的受众是哪些人?应用的内容和 ...
- MapReduce实战(四)倒排索引的实现
需求: 以上三个文件,用MapReduce进行处理,最终输出以下格式: hello c.txt-->2 b.txt-->2 a.txt-->3jerry c.txt-->1 b ...
- zend studio 10.6.2 设置默认编码为UTF-8
如果汉化的:窗体-->常规-->工作空间 然后再选择编码格式 如果未汉化:Window->Preferences->General->wookspace 然后再选 ...