Hike News
Hike News

深度學習-tensorflow基礎-變量(Variable)

Introduction

變量(Variable)也是一種op,是一種特殊的張量,能夠進行存儲持久化(權重、係數等),它的值就是張量可被修改,預設被訓練

  • tf.placeholder, tf.constant皆不能被訓練

變量的創建

使用tf.Variable(initial_value=None, name=None, trainable=True, collections=None)
創建一個帶值為initial_value的新變量

  • initial_value:變量的初始值,可為隨機張量,固定張量等
  • name:表示變量的名字
  • trainable:為True時會隨著訓練過程不斷改變此值(會隨著梯度下降一起優化)
  • collections
    • 新變量將添加到列出的圖的集合中collections,預設為\[GraphKeys.GLOBAL_VARIABLES\]
    • trainableTrue情況下,變量亦會被添加到圖集合中GraphKeys.TRAINABLE_VARIABLES
  • 返回一個tensor類型的Variable

變量能調用的方法

  • assign(value) : 為變量分類一個新值,並返回新值
  • eval(session=None):計算並返回此變量的值(須在有Session的上下文環境中運行)

變量類型

1
2
3
4
5
6
7
8
9
10
import tensorflow as tf

const = tf.constant([1,2,3,4,5])
rand = tf.random_normal([1,5],mean=0.0,stddev =1.0)
variable = tf.Variable(tf.random_normal([2,3], mean=0.0, stddev=1.0))

print(const, rand, variable,sep='\n')

with tf.Session() as sess:
pass
1
2
3
Tensor("Const:0", shape=(5,), dtype=int32)
Tensor("random_normal:0", shape=(1, 5), dtype=float32)
<tf.Variable 'Variable:0' shape=(1, 5) dtype=float32_ref>
  • 其為tf.Variable的op對象

變量初始化

  • 變量在Session中使用時一定要先初始化
    • 否則在Session中使用時會報錯:
      tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value Variable
  • 顯示初始化的動作需先在graph中定義在Session中完成
  • 使用tf.global_variables_initializer()
    • 添加一個初始化所有變量的operation,在graph中定義
    • 在會話中啟動

Example

1
2
3
4
5
6
7
8
9
10
11
12
import tensorflow as tf

const = tf.constant([1,2,3,4,5])
variable = tf.Variable(tf.random_normal([2,3], mean=0.0, stddev=1.0))

# 必須完成顯示的初始化(定義)
variable_initialize = tf.global_variables_initializer()

with tf.Session() as sess:
# 必須先運行初始化op
sess.run(variable_initialize)
print(sess.run([const,variable]))

Result

1
[array([1, 2, 3, 4, 5], dtype=int32), array([[ 0.54134446,  0.8167209 ,  0.5819898 ],[-1.5506644 ,  0.05886701,  0.06756992]], dtype=float32)]

tips

  1. 變量其實與其他Tensor幾乎無異,差異在於能持久化保存
    • 普通的張量op是無法保存的
  2. 當程序當中有定義變量時,一定要在會話中完成運行初始化
    • 在graph中定義顯示的初始化動作