tensorflow1.X命名空间内创建变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import tensorflow as tf 

with tf.name_scope('name_scope'):
ini = tf.constant_initializer(value=0)#用常数来初始化变量
var1 = tf.get_variable(name='var1',shape=[1],dtype=tf.float32,initializer=ini)
var2 = tf.Variable( name='var2',shape=[1],dtype=tf.float32,initial_value=[1])
var2_1 = tf.Variable( name='var2',shape=[1],dtype=tf.float32,initial_value=[2])
var2_2 = tf.Variable( name='var2',shape=[1],dtype=tf.float32,initial_value=[3])

with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(var1.name)
print(sess.run(var1))
print(var2.name)
print(sess.run(var2))
print(var2_1.name)
print(sess.run(var2_1))
print(var2_2.name)
print(sess.run(var2_2))


'''
var1:0
[0.]
name_scope/var2:0
[1.]
name_scope/var2_1:0
[2.]
name_scope/var2_2:0
[3.]
'''
# get_variable() 创建的变量不在scope内
# Variable() 创建的变量在scope内,重名自动加 _i

转载请注明来源 https://tianweiye.github.io