tf.Variable()与tf_get_Variable();tf.variable_scope()与tf.name_scope()以及tf.get_variable_scope()

TensorFlow入门(七) 充分理解 name / variable_scope 欢迎转载,但请务必注明原文出处及作者信息。@author: huangyongye @creat_date: 2017-03-08 前言: 本例子主要介绍 name_scope 和 variable_scope 的正确使用方式,学习并理解本例之后,你就能够真正读懂 TensorFlow 的很多代码并能够清晰地理解模型结构了。之前写过一个例子了: TensorFlow入门(四) name / v 阅读详情

两种定义图变量的方法

  1. tf.Variable

tf.Variable(initial_value, trainable=True, collections=None, validate_shape=True, name=None)

虽然有一堆参数,但只有第一个参数initial_value是必需的,用法如下(assign函数用于给图变量赋值)

import tensorflow as tf

v = tf.Variable(3, name='v')

v2 = v.assign(5)

with tf.Session() as sess:

    init_op = tf.global_variables_initializer()

    sess.run(init_op)

       # 这里sess.run(v.initializer)

    print(sess.run(v)) # 输出3

    print(sess.run(v2))     # 输出5

 

  1. tf.get_Variable

tf.get_variable跟tf.Variable都可以用来定义图变量,但是前者的必需参数(即第一个参数)并不是图变量的初始值,而是图变量的名称。

tf.get_Variable的用法要更丰富一点,当指定名称的图变量已经存在时表示获取它,当指定名称的图变量不存在时表示定义它,用法如下:

tf.get_variable( name, shape=None, dtype=None, initializer=None,

              regularizer=None, trainable=True, collections=None,

 caching_device=None, partitioner=None, validate_shape=True,

              use_resource=None, custom_getter=None, constraint=None)

 

Scope如何划分命名空间

一个深度学习模型的参数变量往往是成千上万的,不加上命名空间加以分组整理,将会成为可怕的灾难。TensorFlow的命名空间分为两种,tf.variable_scope和tf.name_scope。

  1. tf.variable_scope

下面示范使用tf.variable_scope把图变量划分为4组:

import tensorflow as tf

for i in range(4):

    with tf.variable_scope('scope-{}'.format(i)):

        for j in range(25):

            v = tf.Variable(1, name=str(j))

 

当使用tf.get_variable定义变量时,如果出现同名的情况将会引起报错

>>> v1 = tf.get_variable('var', [1])

>>> v2 = tf.get_variable('var', [1])

执行结果: ValueError: Variable var already exists

 

而对于tf.Variable来说,却可以定义“同名”变量

>>>  v1 = tf.Variable(1, name='var')

>>>  v2 = tf.Variable(2, name='var')

执行结果:正确执行

print(v1.name)  # var_5:0

print(v2.name)  # var_6:0

是把这些图变量的name属性打印出来,就可以发现它们的名称并不是一样的。

 

如果想使用tf.get_variable来定义另一个同名图变量,可以考虑加入新一层scope,比如:

 

import tensorflow as tf

with tf.variable_scope('scope1'):

    v1 = tf.get_variable('var', shape=[1])

with tf.variable_scope('scope2'):

    v2 = tf.get_variable('var', shape=[1])

print(v1.name)

print(v2.name)   

执行结果:

scope1/var:0

scope2/var:0

 

  1. tf.name_scope

当tf.get_variable遇上tf.name_scope,它定义的变量的最终完整名称将不受这个tf.name_scope的影响,如下:

import tensorflow as tf

with tf.variable_scope('v_scope'):

    with tf.name_scope('n_scope'):

        x = tf.Variable([1], name='x')

        y = tf.get_variable('x', shape=[1], dtype=tf.int32)

        z = x + y

print(x.name, y.name, z.name)

执行结果:

v_scope/n_scope/x:0, v_scope/x:0, v_scope/n_scope/add:0

 

图变量的复用

想象一下,如果我们正在定义一个循环神经网络RNN,想复用上一层的参数以提高模型最终的表现效果,应该怎么做呢?

方法一:

import tensorflow as tf

with tf.variable_scope('scope'):

    v1 = tf.get_variable('var', [1])

    tf.get_variable_scope().reuse_variables()

    v2 = tf.get_variable('var', [1])

print(v1.name, v2.name)

执行结果:

scope/var:0, scope/var:0

 

方法二:

import tensorflow as tf

with tf.variable_scope('scope'):

    v1 = tf.get_variable('x', [1])

with tf.variable_scope('scope', reuse=True):

    v2 = tf.get_variable('x', [1])

print(v1.name, v2.name)

执行结果:

scope/var:0, scope/var:0

 

tf.variable_scope和tf.name_scope的用法总结:

  1. tf.variable_scope可以让变量有相同的命名,包括tf.get_variable得到的变量,还有tf.Variable的变量
  2. tf.name_scope可以让变量有相同的命名,只是限于tf.Variable的变量
彻底弄懂tf.Variable、tf.get_variable、tf.variable_scope以及tf.name_scope异同 我之前有转载过一篇讲tf.variable_scope和tf.name_scope的文章,今天一看,觉得还是没介绍太清楚,没讲到点子上,毕竟英文什么的看起来还是挺麻烦的。故而,今天来细细梳理下tf.Variable、tf.get_variable、tf.variable_scope以及tf.name_scope四者之间的区别与联系。 阅读详情

相关推荐

tensorflow学习之路(2-2):tf.variable_scope(),tf.name_scope(),tf.get_variable()的认识(补充)

tensorflow tf.get_variable() tf.variable_scope() tf.name_scope()

IB_H20的博客 3717

tensorflow 变量生成 变量管理 tf.Variable、tf.get_variable、tf.variable_scope

____tz_zs学习笔记 tf.Variable 官网api:https://www.tensorflow.org/api_docs/python/tf/Variable def __init__(self, initial_value=None, trainable=True, colle

tz_zs的博客 1万+

tensorflow入门:tf.name_scope,tf.variable_scope、变量共享

1. tf.name_scope('scope_name')或tf.name_scope(named_scope)主要与tf.Variable搭配使用;当传入字符串时,用以给变量名添加前缀,类似于目录,如case1所示;当传入已存在的name_scope对象时,则其范围内变量的前缀只与当前传入的对象有关,与更上层的name_scope无关,如case2所示。import tensorflow as...

yeqiustu的博客 7527

深入浅出TensorFlow2函数——tf.Variable

tf.Variable( initial_value=None, trainable=None, validate_shape=True, caching_device=None, name=None, variable_def=None, dtype=None, import_scope=None, constraint=None, synchronization=tf.VariableSynchronization.AUTO

冯·诺依曼 1万+

tensorflow里面共享变量、name_scope, variable_scope等如何理解

tensorflow里面共享变量、name_scope, variable_scope等如何理解 name_scope, variable_scope目的:1 减少训练参数的个数。 2 区别同名变量 为什么要共享变量?我举个简单的例子:例如,当我们研究生成对抗网络GAN的时候,判别器的任务是,如果接收到的是生成器生成的图像,判别器就尝试优化自己的网络结构来使自己输出0,如果接收到的是来自真实数据的图

u012564409的专栏 4433

LVGL移植教程(正点原子)

学习正点原子LVGL移植教程,根据视频教程写的博客

papalila的博客 941

Tensorflow:variable变量和变量空间

name_scope: 为了更好地管理变量的命名空间而提出的。比如在 tensorboard 中,因为引入了 name_scope, 我们的 Graph 看起来才井然有序。 variable_scope: 大部分情况下,跟 tf.get_variable() 配合使用,实现变量共享的功能。with tf.variable_scope('scopename', reu...

皮皮blog 5112

手把手教你用MATLAB和PSIM搞定Buck电路控制器:从传递函数到运放电路实战

本文详细介绍了如何使用MATLAB和PSIM协同设计Buck电路控制器,从传递函数推导到运放电路实现的完整流程。通过小信号建模、波特图分析和双平台仿真验证,帮助电力电子工程师解决理论到实践的转化难题,提升Buck电路控制器设计的效率和可靠性。

weixin_29271053的博客 269

ValueError: Variable XX/XX does not exist, or was not created with tf.get_variable().

【报错描述】ValueError: Variable lsi/bias_global does not exist, or was not created with tf.get_variable(). Did you mean to set reuse=tf.AUTO_REUSE in VarScope? 【原因分析】 【解决办法】 # 改前 with tf.variable_scope('lsi', reuse=true) # 改后 with tf.variable_scope('lsi', reus

InitialHeart2021的博客 984

STM32H7 FOC控制时序优化与PWM中点更新策略

在永磁同步电机(PMSM)的磁场定向控制(FOC)系统中,控制时序精度是决定电流环带宽、观测器收敛性与动态响应能力的基础要素。其核心在于理解PWM生成、ADC采样与控制计算三者之间的硬件级时间耦合关系——尤其在中心对齐模式下,标准更新机制引入的半周期延迟会破坏电压-电流瞬时映射,导致滑模观测器失配与高频相位滞后。通过将PWM更新事件绑定至重复计数器(RCR)清零点,可实现控制指令在开关周期中点生效,使等效电压矢量中心与计算时刻严格对齐。该策略显著提升系统确定性,为20 kHz以上高频电流环提供物理支撑,并广

flink9streamer的博客 857

使用MeshLab高效对齐3D模型:从OBJ导入到坐标修正全流程

本文详细介绍了使用MeshLab高效对齐3D模型的全流程,涵盖从OBJ导入、坐标修正到最终导出的核心步骤。通过将模型中心归位至坐标原点,并利用主轴对齐功能快速摆正模型,为后续的3D打印、体素化等处理奠定精确的几何基础。

weixin_29313423的博客 93

tf.Variable()、tf.get_variable()

- tf.Variable() W = tf.Variable(<initial-value>, name=<optional-name>) 用于生成一个初始值为initial-value的变量。必须指定初始化值 -tf.get_variable() W = tf.get_variabl

步步拾遗 493

手把手教你配置UEFI Secure Boot:从密钥生成到系统验证(附避坑指南)

本文详细介绍了如何配置UEFI Secure Boot,从密钥生成到系统验证的全过程,包括PK、KEK等关键密钥的生成方法,以及常见问题的解决方案。通过实战案例和避坑指南,帮助用户有效提升系统启动安全性,防止恶意软件植入。

weixin_30776273的博客 341

tf.name_scope用法

tf.name_scope:用于定义Python op的上下文管理器。 tf.name_scope( name ) 此上下文管理器将推送名称范围,这将使在其中添加的所有操作的名称带有前缀。 例如,定义一个新的Python opmy_op: def my_op(a, b, c, name=None): with tf.name_scope("MyOp") as scope: a = tf.convert_to_tensor(a, name="a") b = tf.co.

qq_36201400的博客 7786

matlab实现MSK调制解调

文章目录一、要求二、设计三、代码四、结果五、结论 一、要求 画出MSK信号产生的信息、I路、Q路信号对比图以及接收端解调的信息恢复的对比图。 二、设计 1.MSK调制 2.MSK解调 三、代码 clear all;clc; N=20; T=1; fc=10; Fs=100; bitstream=randi([0,1],1,N); bitstream1=2*bitstream-1; b0=1; for i=1:N encode_output(i)=b0*bitstream

Time_book的博客 1万+

166、Sim2Real中的强化学习:域随机化与鲁棒策略

第二,训练时监控每个随机化维度对策略梯度的贡献,如果某个维度对loss的方差贡献极小,说明策略已经忽略它了,要么加大范围,要么删掉。第四,如果条件允许,用真实数据来校准随机化分布——采集真机上的传感器数据,拟合出参数分布,再把这个分布作为随机化的采样依据,这比拍脑袋定范围靠谱得多。动态随机化是很多人忽略的维度。域随机化的核心思想说白了就一句话:别去精确建模现实,而是把仿真环境本身变成一个随机分布的集合,让策略在“各种乱七八糟的物理参数”里都见过世面,这样到了真机上,不管现实落在哪个参数区间,策略都能兜住。

sundong_81的博客 27

tensorflow 变量及命名空间 tf.Variable() vs tf.get_variable() & tf.name_scope() vs tf.variable_scope()

tf.Variable() vs tf.get_variable() tf.name_scope() vs tf.variable_scope() 1. 基础功能 1.1 tf.Variable() 是一个类,tensorflow.python.ops.variables.Variable,其构造函数原型为 def __init__( self, initial_value: Any = None, trainable: bool = True, collections:

撒旦先生的博客 2667

SwinTransformer改进(5):与CBAM结合的视觉模型

这个模型的核心思想是将Swin Transformer的强大特征提取能力与CBAM的注意力机制相结合,以提升模型对重要特征的关注度。​​CBAM模块​​:包含通道注意力和空间注意力两个子模块​​Swin Transformer主干网络​​:作为基础特征提取器​​集成结构​​:在Swin Transformer的不同阶段插入CBAM模块使用移动窗口(Moving Window)机制减少计算量层次化设计,特征图逐渐缩小,通道数逐渐增加在不同阶段使用Patch Merging进行下采样。

2401_82355416的博客 688

tf.variable_scope和tf.name_scope的用法

tf.variable_scope可以让变量有相同的命名,包括tf.get_variable得到的变量,还有tf.Variable的变量 tf.name_scope可以让变量有相同的命名,只是限于tf.Variable的变量 例如: import tensorflow as tf; import numpy as np; import matplotlib.pyplot as plt

UESTC_C2_403的博客 5万+

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

深入理解tf.Variable、tf.get_variable、tf.variable_scope与tf.name_scope

很多博客都有讲tf.Variable、tf.get_variable、tf.variable_scope与tf.name_scope的使用,但是它们要么不全,要么很片面。本博客打算从全面与详细两个方面进行深入探讨它们的用法。 首先纠正一点,很多博客说tf.variable_scope是变量作用域,其实要这么说也无妨,但是实际上它并不那么严格,因为,这里的作用域只是用于命名与搜索,并不具有局部有...

edward_zcl的博客 1330

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

tf.Variable() 和 tf.get_variable(),tf.name_scope() 和 tf.variable_scope()

在gpu并行训练网络时,往往需要共享已创建的变量,tensorflow中为了使这些变量名和操作名唯一并且不重复,用了几个函数来应对这种情况。于是就有了tf.Variable(), tf.get_variable(), tf.Variable_scope(), tf.name_scope()这四个最常见的函数。下面来进行逐对比较和分析。 ** 一、tf.Variable() 和 tf.get_...

a6840231的博客 820

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

Tensorflow中tf.name_scope() 和 tf.variable_scope() 的区别

目录 一、name_scope和variable_scope的用途 (1)variable_scope用途:共享变量 (2)可视化用途:画Tensorboard流程图时封装 二、TensorFlow中name_scope和variable_scope区别 (1)TF中创建变量的方式有两种:tf.get_variable()和tf.Variable() (2)Tensorflow中有两种...

Microstrong 1640

tensorflow变量共享——VariableScope的reuse模式、tf.get_variable()、tf.Variable() 探索

Reusing模式会被子vs继承 tf.get_variable_scope().reuse_variables() print('"'+tf.get_variable_scope().name+'"', tf.get_variable_scope().reuse) with tf.variable_scope('ss'): # ss是默认vs的子vs,故虽然没有使用reuse=True,wit...

pyxiea 7038

Tensorflow中tf.Variable()和tf.get_variable()的区别与关系

从两个方法的名称上,可以简单理解一下,Variable是定义变量,而get_variable是获取变量(只不过如果获取不到就重新定义一个变量),如果按照这种逻辑,已经基本上可以理解两者的差异了。 下面我们通过一些代码,来更深入理解一下两者的差异和各自的特点 先看下面这段代码(最好先不要看下面注释中的输出结果,先自己思考一下会是什么结果) import tensorflow as tf v...

拼命先生的AI之旅 2029

tf.variable_scope()和tf.name_scope()的正确用法

tf.variable_scope() tf官网对tf.variable_scope()的说明。 tf.variable_scope()和tf.get_variable()是配合使用的,主要用于变量共享。当reuse=False或None,重复创建变量会报错。当reuse=True而变量不存在,也会报错。 reuse参数相互之间是怎么传递的?没有设置reuse参数时,会继承上层的reuse参数值。 scope.reuse_variables()。在同一个scope中,可以通过这个语句重用定义过的变量。

wxgaws的博客 2062

tf.get_variable_scope().reuse_variables() 的使用

tf.name_scope()对tf.get_variable_scope().reuse_variables() 不起作用 # tf.get_variable_scope().reuse_variables() 的使用 import tensorflow as tf with tf.variable_scope('a1'): print(tf.get_variable_scope()....

跨过一座座山 6754
上一篇: TensorFlow 常用的函数
下一篇: tf.nn.depthwise_conv2d如何实现深度卷积?
Key_jiang
博客等级 码龄9年 4粉丝 25原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值