TensorFlow——Graph的基本操做

1.建立圖函數

在tensorflow中,一個程序默認是創建一個圖的,除了系統自動創建圖之外,咱們還能夠手動創建圖,並作一些其餘的操做。測試

下面咱們使用tf.Graph函數創建圖,使用tf.get_default_graph函數來獲取圖,使用reset_default_graph對圖進行重置。spa

import tensorflow as tf
import numpy as np


c = tf.constant(1.5)
g = tf.Graph()

with g.as_default():

    c1 = tf.constant(2.0)
    print(c1.graph)
    print(g)
    print(c.graph)

g2 = tf.get_default_graph()
print(g2)

tf.reset_default_graph()
g3 = tf.get_default_graph()
print(g3)

上述的代碼運行結果以下所示:code

根據上述的運行結果,c是在剛開始的默認圖中創建的,因此打印的結果就是13376A1FE10,和g2獲取的默認圖的值是同樣的,而後使用tf.Graph創建了一個新的圖,並添加了變量c1,最後又對圖進行了重置,替代了原來的默認圖。對象

在使用reset_default_graph()函數的時候,要保證當前圖中資源都已經所有進行了釋放,不然將會報錯。blog

2.獲取張量ip

咱們能夠在圖中經過名字獲得其對應的元素,好比獲取圖中的變量和OP等元素。element

import tensorflow as tf
import numpy as np

g = tf.Graph()

with g.as_default():
    c1 = tf.constant(2.5, name='c1_constant')
    c2 = tf.Variable(1.5, dtype=tf.float32, name='c2_constant')
    add = tf.multiply(c1, c2, name='op_add')

    c_1 = g.get_tensor_by_name(name='c1_constant:0')
    c_2 = g.get_tensor_by_name(name='c2_constant:0')
    c_3 = g.get_tensor_by_name(name='op_add:0')


    print(c_1)
    print(c_2)
    print(c_3)
    

在進行測試時,咱們爲元素添加了變量名,在設置變量名的時候,設置好的名字會自動添加後面的:0字符。通常咱們能夠將名字打印出來,在將打印好的名字進行回填。資源

3.獲取節點操做get

獲取節點操做OP的方法和獲取張量的方法很是相似,使用get_operation_by_name.下面是運行實例:

import tensorflow as tf
import numpy as np

a = tf.constant([[1.0, 2.0]])
b = tf.constant([[1.0], [3.0]])

tensor_1 = tf.matmul(a, b, name='matmul_1')

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    t1 = tf.get_default_graph().get_operation_by_name(name='matmul_1')
    t2 = tf.get_default_graph().get_tensor_by_name(name='matmul_1:0')
    print(t1)
    print('t1: ', sess.run(t1))
    print('t2: ', sess.run(t2))

在上述的代碼中,定義了一個OP操做,命名爲matmul_1,在運行時咱們將op打印出來,在使用名字後面加上:0咱們就能獲得OP運算的結果的tensor,注意這二者的區別。

咱們還能夠經過get_opreations函數獲取圖中的全部信息。此外,咱們還可使用tf.Grapg.as_graph_element函數將傳入的對象返回爲張量或者op。該函數具備驗證和轉換功能。

相關文章
相關標籤/搜索