Tensorflow lesson 3---變量Variable

Tensorflow中的變量就是一個放在內存中的tensor結構,用於在計算過程中保存數據,變量的數值可以保存到文件中,也可以從文件中讀取

1.變量的初始化

import tensorflow as tf

Weights=tf.Variable(tf.random_normal([3,2],stddev=0.35),name="weights")#聲明一個Weights的變量

print(Weights)#打印Weights變量結構
init=tf.global_variables_initializer()#初始化變量

with tf.Session() as sess:#執行session任務
    sess.run(init)#初始化認爲
    print(sess.run(Weights))#打印Weights的值

tensorflow中的變量必須被初始化,否則其內容是空的,以上代碼執行完後會打印出一個3行2列的矩陣,值隨機的,執行的輸出結果如下

<tf.Variable 'weights:0' shape=(3, 2) dtype=float32_ref>
[[ 0.01990979 -0.26959115]
 [ 0.32198292 -0.09266231]
 [-0.32708889  0.3107968 ]]

2.變量保存到文件

import tensorflow as tf

Weights=tf.Variable(tf.random_normal([3,2],stddev=0.35),name="weights")

print(Weights)

saver = tf.train.Saver()#聲明Saver
init=tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    print(sess.run(Weights))
    save_path = saver.save(sess, "/Users/william/tmp/model.ckpt")#保存到文件
    print("Model saved in file: %s" % save_path)#打印保存的路徑

tensorflow是可以將變量保存到文件的,要用到的是tf.train.Saver,以上這段代碼執行完成後,就會在tmp文件夾下身材變量保存的文件
這裏寫圖片描述

3.變量的讀取
可以保存到文件,就可以從文件中把變量讀取出來

import tensorflow as tf

Weights=tf.Variable(tf.random_normal([3,2],stddev=0.35),name="weights")

print(Weights)

saver = tf.train.Saver()

with tf.Session() as sess:
    saver.restore(sess, "/Users/william/tmp/model.ckpt")
    print("the restore variable Weights= %s" % sess.run(Weights))

以上代碼把變量讀取出來,並打印出來,其輸出如下:

<tf.Variable 'weights:0' shape=(3, 2) dtype=float32_ref>
the restore variable Weights= [[ 0.01990979 -0.26959115]
 [ 0.32198292 -0.09266231]
 [-0.32708889  0.3107968 ]]

如果變量是從文件中讀取出來,就不需要初始化,只需要聲明就可以了

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