tensorflow中的變數管理

2021-08-16 02:15:02 字數 2713 閱讀 6539

變數管理:

通過名稱獲取變數:tf.get_variable 和tf.variable_scope 函式實現。

tf.get_variable() 建立變數或者獲取變數,與tf.variable()基本等價

#下面二個變數等價

v = tf.get_variable(「v」, shape = [1], initializer = tf.constant_initializer(1, 0))

v = tf.variable(tf.constant(1.0, shape = [1]), name = 「v」)

但是二者最大的區別:tf.variable()中變數name = 『v』是乙個可選引數,

而對應tf.get_variable(「name」,)中是乙個必填引數,函式會通過變數名稱去建立或者尋找已經存在的引數

tf.constant_initializer() 與tf.constant()功能基本一致,將變數初始化為給定的常量,引數為常量的取值。

tf.variable_scope() 建立乙個上下文管理器,來管理tf.get_variable()函式。

當reuse = true時候,tf.get_variable() 只能獲取已經建立的變數,預設reuse = false, 可以建立新的變數。

#在名字為fee的命名空間內建立a的變數,此時resue 預設為false, 函式將會建立新的變數

with tf.variable_scope("fee"):

a = tf.get_variable("v", [1], initializer = tf.constant_initializer(1.0)

# 在fee命名空間中,已經建立了v,再次建立時候將會報錯

with tf.variable_scope("fee"):

a = tf.get_variable("v", [1])

error: variable fee/a alredy exists, disallowed. did you mean to

set resue = true

in varscope?

# resue引數設定為true後,只能獲取已經建立的變數

with tf.variable_scope("fee", reuse = true):

b = tf.get_variable("v", [1])

print(b == a)

true

# 變數空間不存在,報錯

with tf.variable_scope("foo", reuse = true):

c = tf.get_variable("v", [1])

warining: variable foo.v dose not exist, disallowed. did you mean to

set resues = true

in varscope?

with tf.variable_scope("root"):

#通過tf.get_variable_scope().reuse 函式獲取當前上下文管理器中的resue引數

print(tf.get_variable_scope().reuse) #輸出為false,最外層reuse為false

with tf.variable_scope("foo", reuse = true):

print(tf.get_variable_scope().reuse) #輸出為true

with tf.variable_scope("foo1"):

print(tf.get_variable_scope().reuse) #輸出為true,與外層巢狀保持一致,如果不指定reuse的值的話

print(tf.get_variable_scope().reuse

#輸出為false

v1 = tf.get_variable("v", [1])

print(v1.name) #輸出v:0. 「v」為變數的名稱, 「0」表示這個變數是生成變數的這個運算的第乙個結果

with tf.variable_scope("foo"):

v2 = tf.get_variable("v", [1])

print(v2.name)

#輸出 foo/v:0 .在variable_scope函式中建立的變數,名稱前會加入命名的空間的名稱,並通過/來分割命名空間和變數

with tf.variable_scope("foo"):

with tf.variable_scope("bar"):

v3 = tf.get_variable("v", [1])

print(v3.name)

#輸出 foo/bar/v:0 命名空間的巢狀,同時變數的名稱也會加入所有命名空間的名稱為字首

#建立乙個名稱為空的命名空間,並且設定reuse = true

with tf.variable_scope("", reuse = true):

v5 = tf.get_variable("foo/bar/v", [1]) #通過命名空間的變數名稱來獲取其他命名空間下的變數

print(v5 == v3) #output = true

v6 = tf.get_variable("foo/v1". [1])

print(v6 == v4) # output = true

tensorflow中的變數管理

import tensorflow as tf variable scope 示例 tensorflow中通過變數名稱獲取變數的機制主要是通過tf.get variable和tf.variable scope函式實現的 tf提供tf.get variable函式來建立或獲取變數 當tf.get va...

83 Tensorflow中的變數管理

created on apr 21,2017 author p0079482 如何通過tf.variable scope函式來控制tf.ger variable函式獲取已經建立過的變數 在名字為foo的命名空間內建立名字為v的變數 import tensorflow as tf with tf.va...

Tensorflow中變數的重複使用

tf.get variables name,shape,initializer 和tf.variable name,shape,initializer 都是相同的,建立 初始化 乙個變數.但是tf.get variables 中name是必寫項,而tf.variable 是可選項。且tf.get v...