tf 变量共享

本文详细介绍TensorFlow中张量的分类及使用,包括常量、变量和占位符的区别与创建方式,并深入探讨变量域的概念及其在参数重用中的应用。此外,还对比了tf.nn与tf.layers模块的不同之处。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面内容由各处综合参考而来

TF官方文档链接

https://tensorflow.google.cn/versions/r1.15/api_docs/python/tf

问题1 tf中张量的分类和使用:常量 变量 占位符

明确创建和执行的区别 学会各种api使用

https://cloud.tencent.com/developer/news/65965

常量

tf.constant tf.zeros tf.ones tf.linspace tf.range tf.random_​

参数 value dtype shape name其中name属性在tensorboard中使用 ,例如

zero_t = tf.zeros([2,3],tf.int32,name='a')

zero_t在代码中使用到 name为name_scope在tensorboard中显示

创建常量中定义的数据类型(tensor)执行计算图之后 转换成为numpy数据类型

变量和占位符

创建变量和初始化变量的区别

https://www.jianshu.com/p/26faa5cb41f3

官方apihttps://tensorflow.google.cn/versions/r1.15/api_docs/python/tf/Variable

tf.Variable(
    initial_value=None, trainable=None, collections=None, validate_shape=True,
    caching_device=None, name=None, variable_def=None, dtype=None,
    expected_shape=None, import_scope=None, constraint=None, use_resource=None,
    synchronization=tf.VariableSynchronization.AUTO,
    aggregation=tf.VariableAggregation.NONE, shape=None
)
tf.get_variable(
    name, shape=None, dtype=None, initializer=None, regularizer=None,
    trainable=None, collections=None, caching_device=None, partitioner=None,
    validate_shape=True, use_resource=None, custom_getter=None, constraint=None,
    synchronization=tf.VariableSynchronization.AUTO,
    aggregation=tf.VariableAggregation.NONE
)
问题2 在tf中各种变量域的区别 如何进行参数重用

scope:范围 name:名字

在TF中用来对变量进行管理 每一个变量或者常量在计算图中都应该有自己的位置和名字

https://my.oschina.net/liusicong/blog/1593467

https://my.oschina.net/liusicong/blog/1593467

变量命名

当变量名相同的时候,tf会自动打上序号

with tf.name_scope('s'):    # or tf.variable_scope('s')
    a = tf.Variable(initial_value=10, name='a')
    b = tf.Variable(initial_value=10, name='a')
    print(a.name)
    print(b.name)

[out]
s/a:0
s/a_1:0

变量共享的几种方法 对于产生的变量需要重用,有下面几种情况

1 在同一个域下,重名是会报错的。

with tf.variable_scope('s'):
    a = tf.get_variable(name='a', shape=(10, 10))
    b = tf.get_variable(name='a')

[out]
ValueError: Variable s/a already exists, disallowed. Did you mean to set reuse=True in VarScope?

2 在需要复用变量之前改变scope的reuse状态

with tf.variable_scope('s') as s:
    a = tf.get_variable(name='a', shape=(10, 10))
    s.reuse_variables()
    b = tf.get_variable(name='a')
print(a == b)

[out]
True

s.reuse_variables()更改的是s这个变量域里面的变量的reuse状态为true 因此后面可以重用

3 设置tf.variable_scope的reuse参数为True来复用已经定义过的同名变量,但如果没定义过而设置reuse=True也是会报错的

报错:

with tf.variable_scope('s', reuse=True):
    a = tf.get_variable(name='a')

[out]
ValueError: Variable s/a does not exist, or was not created with tf.get_variable(). Did
ValueError: Variable s/a does not exist, or was not created with tf.get_variable(). Did you mean to set reuse=None in VarScope?
with tf.variable_scope('s'):
    a = tf.get_variable(name='a', shape=(10, 10))
with tf.variable_scope('s', reuse=True):
    b = tf.get_variable(name='a')
print(a == b)

[out]
True

4

1)

with tf.variable_scope("image_filters") as scope:
    result1 = my_image_filter(image1)
    scope.reuse_variables() # or 
    #tf.get_variable_scope().reuse_variables()
    result2 = my_image_filter(image2)

2)

with tf.variable_scope("image_filters1") as scope1:
    result1 = my_image_filter(image1)
with tf.variable_scope(scope1, reuse = True)
    result2 = my_image_filter(image2)

注意最好不要采用的方式:设置 reuse 标识为 False,然后在需要的时候设置 reuse 标识为 True。

上述中tf.get_varible 用于需要进行共享的变量创建 tf.varible创建的变量无论如何都不会进行变量共享

创建变量时候并没有reuse参数,只有trainable=None参数 reuse参数一般在定义的各种层scope里面

5 tf.layer的参数复用

例如tf.layers.dense(), tf.layers.conv2D()等,参数复用只需要再tf.layers.dense(x, 4, name=‘h1’, reuse=True),使得参数reuse为True,即可复用上一层的参数。
为了验证,我们可以通过:

x = tf.ones((1, 3))
y1 = tf.layers.dense(x, 4, name='h1')
y2 = tf.layers.dense(x, 4, name='h1', reuse=True)

# y1 and y2 will evaluate to the same values
sess = tf.Session()
sess.run(tf.global_variables_initializer())
print(sess.run(y1))
print(sess.run(y2))  # both prints will return the same values

这样就实现了参数的复用 通过设置reuse参数 这里面没有层的scope,因此就不存在是不是复用

注意上述代码中复用时候需要 名字相同

x = tf.ones((1, 3))
y1 = tf.layers.dense(x, 4, name='h1')
y2 = tf.layers.dense(x, 4, name='h1',reuse=True)  #正确能够重用 

y2 = tf.layers.dense(x, 4, name='h2', reuse=True) #报错 h2不存在

with tf.variable_scope('a'):
    y3 = tf.layers.dense(x, 4, name='h1', reuse=True)#报错 a/h1/kernel不存在
    y3 = tf.layers.dense(x, 4, reuse=True)#报错 a/dense/kernel 不存在 不加name的时候使用的就是默认的名字dense
    
    y3 = tf.layers.dense(x, 4, reuse=None/False) #正确 可以创建相关变量为 a/dense/kernel

with tf.variable_scope('b'):
    y4=tf.layers.dense(x, 4, reuse=True) #报错找不到变量

6 使用tf.varible创建的变量使用get_varible()能够共享吗 或者说在tf.variblescope中创建的sc

with tf.variable_scope('s') as s:
  ...:     a = tf.Variable(initial_value=10, name='a')
  ...:     s.reuse_variables()
  ...:     b = tf.get_variable(name='a')
  ...: print(a == b)

结果报错 s/a 不存在 尽管使用tf.Variable 产生的变量也是s/a 但是不是tf.get_variable产生的 因此就是不可以进行复用

3 tf.nn模块和tf.layers模块的区别

思考 如何使用tf.nn模块 达到reuse=True的效果 ?

使用tf.get_varible()创建变量

https://blog.youkuaiyun.com/qq_32791307/article/details/80536352

https://blog.youkuaiyun.com/Yuancccc/article/details/89472133

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值