TensorFlow (3) TensorFlow Basics

1. TensorFlow 計算流程:

  1. 建立算圖
  2. 執行算圖

2. 何謂算圖:

算圖由兩種東西組成,分別是 node 和 edge 。

  • node: node 是一種 operation (運算),例如加法。
  • edge: edge 是一種 tensor (張量),數字和矩陣都算張量的一種只是維度不同。

3. 一個簡單的例子:

import tensorflow as tf

# 建立算圖
a = tf.constant(1)
b = tf.constant(2)
c = a + b

# 執行算圖
with tf.Session() as sess:
    res = sess.run(c)

print(res)


4. 算圖和 default 算圖:

宣告運算時若未宣告使用的算圖,系統會產生新的 default 算圖。

import tensorflow as tf

print(tf.get_default_graph())
a = tf.constant(1)
print(a.graph) # 使用的是系統建置的算圖

g1 = tf.Graph()
with g1.as_default():
    print(tf.get_default_graph())
    b = tf.constant(1)
    print(b.graph) # 使用的是 g1,現在 g1 是 scope 的預設。
    



Reference

[1] Tom Hope, Yehezkel S. Resheff, and Itay Lieder, Learning TensorFlow A Guide to Building Deep Learning Systems , O'Reilly Media (2017)

留言

熱門文章