前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >tf.name_scope()和tf.variable_scope()

tf.name_scope()和tf.variable_scope()

作者头像
周小董
发布2019-03-25 10:35:37
6810
发布2019-03-25 10:35:37
举报
文章被收录于专栏:python前行者python前行者

tf.variable_scope可以让变量有相同的命名,包括tf.get_variable得到的变量,还有tf.Variable的变量

tf.name_scope可以让变量有相同的命名,只是限于tf.Variable的变量

例如:

代码语言:javascript
复制
import tensorflow as tf;  
import numpy as np;  
import matplotlib.pyplot as plt;  
 
with tf.variable_scope('V1'):
	a1 = tf.get_variable(name='a1', shape=[1], initializer=tf.constant_initializer(1))
	a2 = tf.Variable(tf.random_normal(shape=[2,3], mean=0, stddev=1), name='a2')
with tf.variable_scope('V2'):
	a3 = tf.get_variable(name='a1', shape=[1], initializer=tf.constant_initializer(1))
	a4 = tf.Variable(tf.random_normal(shape=[2,3], mean=0, stddev=1), name='a2')
  
with tf.Session() as sess:
	sess.run(tf.initialize_all_variables())
	print(a1.name)
	print(a2.name)
	print(a3.name)
	print(a4.name)

输出:

代码语言:javascript
复制
V1/a1:0
V1/a2:0
V2/a1:0
V2/a2:0

例子2:

代码语言:javascript
复制
import tensorflow as tf;  
import numpy as np;  
import matplotlib.pyplot as plt;  
 
with tf.name_scope('V1'):
	a1 = tf.get_variable(name='a1', shape=[1], initializer=tf.constant_initializer(1))
	a2 = tf.Variable(tf.random_normal(shape=[2,3], mean=0, stddev=1), name='a2')
with tf.name_scope('V2'):
	a3 = tf.get_variable(name='a1', shape=[1], initializer=tf.constant_initializer(1))
	a4 = tf.Variable(tf.random_normal(shape=[2,3], mean=0, stddev=1), name='a2')
  
with tf.Session() as sess:
	sess.run(tf.initialize_all_variables())
	print(a1.name)
	print(a2.name)
	print(a3.name)
	print(a4.name)

报错:Variable a1 already exists, disallowed. Did you mean to set reuse=True in VarScope? Originally defined at:

换成下面的代码就可以执行:

代码语言:javascript
复制
import tensorflow as tf;  
import numpy as np;  
import matplotlib.pyplot as plt;  
 
with tf.name_scope('V1'):
	# a1 = tf.get_variable(name='a1', shape=[1], initializer=tf.constant_initializer(1))
	a2 = tf.Variable(tf.random_normal(shape=[2,3], mean=0, stddev=1), name='a2')
with tf.name_scope('V2'):
	# a3 = tf.get_variable(name='a1', shape=[1], initializer=tf.constant_initializer(1))
	a4 = tf.Variable(tf.random_normal(shape=[2,3], mean=0, stddev=1), name='a2')
  
with tf.Session() as sess:
	sess.run(tf.initialize_all_variables())
	#print(a1.name)
	print(a2.name)
	#print(a3.name)
	print(a4.name)

输出:

代码语言:javascript
复制
V1/a2:0
V2/a2:0

参考:https://blog.csdn.net/UESTC_C2_403/article/details/72328815 https://www.imooc.com/article/22966

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019年01月03日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档