Variable就是一个创建变量的op
代码:
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
def variable_demo():
"""
变量的演示
:return:
"""
# 创建变量
a = tf.Variable(initial_value=50)
b = tf.Variable(initial_value=40)
c = tf.add(a, b)
print("a:\n", a)
print("b:\n", b)
print("c:\n", c)
# 初始化变量
init = tf.global_variables_initializer()
# 开启会话
with tf.Session() as sess:
# 运行初始化
sess.run(init)
a_value, b_value, c_value = sess.run([a, b, c])
print("a_value:\n", a_value)
print("b_value:\n", b_value)
print("c_value:\n", c_value)
return None
variable_demo()
一定要进行初始化,然后再开启会话前先开启初始化在进行接下来操作
在没有命名时,变量都是variable
而用with+修改后
每个模块会比较清晰,相当于分成了几个空间,每个空间名称不同
代码:
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
def variable_demo():
"""
变量的演示
:return:
"""
# 创建变量
空间1
with tf.variable_scope("my_scope"):
a = tf.Variable(initial_value=50)
b = tf.Variable(initial_value=40)
空间2
with tf.variable_scope("your_scope"):
c = tf.add(a, b)
print("a:\n", a)
print("b:\n", b)
print("c:\n", c)
# 初始化变量
init = tf.global_variables_initializer()
# 开启会话
with tf.Session() as sess:
# 运行初始化
sess.run(init)
a_value, b_value, c_value = sess.run([a, b, c])
print("a_value:\n", a_value)
print("b_value:\n", b_value)
print("c_value:\n", c_value)
return None
结果:
a_value:
50
b_value:
40
c_value:
90