Tensorflow = Tensor(張量) + flow(數據流圖)
1、張量
張量可不是“麻辣燙”!張量是一個很抽象的概念,直觀的來說,張量在tensorflow中就像一個杯子,起到保存數據的作用,我們也可以把張量看成一個不同維度的數組。
0階的張量是一個標量,就是一個數值;
1階的張量是一個向量;
2階的張量是一個矩陣;
3階的張量是一個三維矩陣。
以此類推...
#定義0階張量 a = tf.constant(2.,name="a") #定義1階張量 b = tf.constant([3],name="b") #定義2階張量 c = tf.constant([[4,5]],name="c") print(a) print(b) print(c)
輸出結果:
Tensor("a:0", shape=(), dtype=float32) Tensor("b:0", shape=(1,), dtype=int32) Tensor("c:0", shape=(1, 2), dtype=int32)
a、b、c三個張量分別是0階、1階、2階,可以看出來Tensor有類型、形狀兩個屬性。
2、數據流圖
如果大家看過官方的教程,那么對上圖肯定很熟悉。所謂Tensorflow,簡單的說,就是tensor(張量)數據在圖中flow(流動)計算的過程。
import tensorflow as tf tf.reset_default_graph() with tf.variable_scope("a"): a = tf.constant(1,name="a") with tf.variable_scope("b"): b = tf.constant(2,name="b") with tf.variable_scope("c"): c = tf.constant(3,name="c") output1 = tf.add(a,b,name="out1") output2 = tf.add(c,output1,name="out2") write = tf.summary.FileWriter("E://logs",tf.get_default_graph()) write.close()
我這里使用tensorboard來查看數據流圖,將數據流圖存儲在e://logs目錄下,然后終端執行:
tensorboard --logdir=e://logs//
打開tensorboard可以看到如圖結果:
這個數據流圖就為我們很好的演示了“tensor(張量)數據在圖中flow(流動)計算的過程”。我們定義三個張量a,b,c,其中out1=a+b,out2=out1+c,得到最終結果。