tensorflow保存變量的本質

前面博客已經說過,tf.Variable的本質就是C++變量或者數組,所以在聲明變量時,最好自己給定變量一個名字,如下代碼:
import tensorflow as tf
import numpy as np
w = tf.Variable([[11,12,13],[22,23,25]],dtype=tf.float32,name=“w”)
save = tf.train.Saver()
with tf.Session() as sess:
sess.run(init)
save_path = save.save(sess,“my_net/save_net.ckpt”)
print(“保存路徑:”,save_path)
執行sess.run(init後,相當於執行c++代碼:float w[2][3]={{11,12,13},{22,23,25}}
tensorflow保存變量實際 上是保存的C++ 浮點二維數組w
如果聲明tf.Variable時,不給名字,tensorflow會給一個名字,以後提取變量時,不能根據變量名字提取變量值,太依賴變量聲明的順序

看代碼:
import tensorflow as tf
import numpy as np

data1=tf.Variable([1,2,3],dtype=tf.int32)
data2=tf.Variable([1,2,3],dtype=tf.int32,name=“data2”)
data3=tf.Variable([1,2,3],dtype=tf.int32)
data4=tf.Variable([1,2,3],dtype=tf.int32)

init = tf.global_variables_initializer()

with tf.Session() as sess:
sess.run(init)
print(data1)
print(data2)
print(data3)
print(data4)
輸出爲:
<tf.Variable ‘Variable:0’ shape=(3,) dtype=int32_ref>
<tf.Variable ‘data2:0’ shape=(3,) dtype=int32_ref>
<tf.Variable ‘Variable_1:0’ shape=(3,) dtype=int32_ref>
<tf.Variable ‘Variable_2:0’ shape=(3,) dtype=int32_ref>
變量data1,data3,data4的名字爲系統給定的,data2的名字爲自己給定的,系統的給定的名字格式爲:Variable_n:0,其中n與變量聲明的順序有關

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章