TF1版本下:
import tensorflow as tf
with tf.name_scope('conv1') as scope:#作用域conv1
weights1 = tf.Variable([1.0, 2.0], name='weights')#定义变量
bias1 = tf.Variable([0.3], name='bias')
with tf.name_scope('conv2') as scope:#作用域conv2
weights2 = tf.Variable([4.0, 2.0], name='weights')#定义变量
bias2 = tf.Variable([0.33], name='bias')
# weights1 和 weights2 这两个变量在两个作用域,不会冲突
print(weights1.name)
print(weights2.name)
print(bias1.name)
print(bias2.name)
执行三次:
# 第一次执行结果
conv1/weights:0
conv2/weights:0
conv1/bias:0
conv2/bias:0
# 第二次执行结果
conv1_1/weights:0
conv2_1/weights:0
conv1_1/bias:0
conv2_1/bias:0
# 第三次执行结果
conv1_2/weights:0
conv2_2/weights:0
conv1_2/bias:0
conv2_2/bias:0
会不断产生新的张量,加上tf.reset_default_graph(),在每次运行时会清空变量。
import tensorflow as tf
tf.reset_default_graph()
with tf.name_scope('conv1') as scope:#作用域conv1
weights1 = tf.Variable([1.0, 2.0], name='weights')#定义变量
bias1 = tf.Variable([0.3], name='bias')
with tf.name_scope('conv2') as scope:#作用域conv2
weights2 = tf.Variable([4.0, 2.0], name='weights')#定义变量
bias2 = tf.Variable([0.33], name='bias')
# weights1 和 weights2 这两个变量在两个作用域,不会冲突
print(weights1.name)
print(weights2.name)
print(bias1.name)
print(bias2.name)
执行三次:
# 第一次执行结果
conv1/weights:0
conv2/weights:0
conv1/bias:0
conv2/bias:0
# 第二次执行结果
conv1/weights:0
conv2/weights:0
conv1/bias:0
conv2/bias:0
# 第三次执行结果
conv1/weights:0
conv2/weights:0
conv1/bias:0
conv2/bias:0
不会产生新的张量。
【TensorFlow】tf.reset_default_graph()函数_duanlianvip的博客-CSDN博客_reset_default_graph
需要注意的是,tf.reset_default_graph是tensorflow1上的 需要迁移到tensorflow2上,即
import tensorflow as tf #TF2版本
tf.compat.v1.reset_default_graph()