Tensorflow中變數的重複使用

2021-09-10 04:48:53 字數 2264 閱讀 4248

tf.get_variables(name, shape, initializer)和tf.variable(name, shape, initializer)都是相同的,建立(初始化)乙個變數.但是tf.get_variables()中name是必寫項,而tf.variable()是可選項。且tf.get_variables()主要與tf.variable_scope(scope_name): 相作用。tf.variable_scope(scope_name):的作用就是為tf.get_variables()申明乙個作用空間。

在tf.variable_scope(scope_name):相同的作用域內,tf.get_variables()name不可以相同,否則在tf.variable_scope(scope_name,reuse=true):或者在宣告tf.get_variables()之前加tf.get_variable_scope().reuse_variables()

如下import tensorflow as tf

情況一相同scope建立相同變數名

#在名字為a的命名空間內建立名字為v的變數,下面**會報錯

with tf.variable_scope(「a」):

v= tf.get_variable(『v』,[1],initializer = tf.constant_initializer(1.0))

with tf.variable_scope(「a」):

v= tf.get_variable(『v』,[1],initializer = tf.constant_initializer(1.0))

#因為在a空間已經建立v的變數,但是reuse=true,則正確

with tf.variable_scope(「a」):

tf.get_variable_scope().reuse_variables()

vv= tf.get_variable(『v』,[1],initializer = tf.constant_initializer(1.0))

with tf.variable_scope(「a」,reuse=true):

vv= tf.get_variable(『v』,[1],initializer = tf.constant_initializer(1.0))

情況二相同scope建立不同變數名

相同scope建立不同變數名時,reuse必須為false

#reuse=false,下面**正確

with tf.variable_scope(「a」):

v= tf.get_variable(『v』,[1],initializer = tf.constant_initializer(1.0))

with tf.variable_scope(「a」):

v= tf.get_variable(『w』,[1],initializer = tf.constant_initializer(1.0))

#reuse=true,下面**錯誤

with tf.variable_scope(「a」):

v= tf.get_variable(『v』,[1],initializer = tf.constant_initializer(1.0))

with tf.variable_scope(「a」):

tf.get_variable_scope().reuse_variables()

vv= tf.get_variable(『v』,[1],initializer = tf.constant_initializer(1.0))

with tf.variable_scope(「a」,reuse=true):

vv= tf.get_variable(『v』,[1],initializer = tf.constant_initializer(1.0))

在scope上下文內用tf.variable定義相同的變數名不報錯,無論是否reuse=true因為scope只和tf.get_variable_scope()相互作用

with tf.variable_scope(「a」) as scope:

v= tf.get_variable(『v』,[1],initializer = tf.constant_initializer(1.0))

with tf.variable_scope(「a」):

vv= tf.variable(『v』,[1])

tensorflow中的變數管理

變數管理 通過名稱獲取變數 tf.get variable 和tf.variable scope 函式實現。tf.get variable 建立變數或者獲取變數,與tf.variable 基本等價 下面二個變數等價 v tf.get variable v shape 1 initializer tf...

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...