Tensorflow中scope命名方法

TCN+iTransformer时间序列预测实战:从风电功率预测到源码解析(附完整代码) 本文深入探讨了TCN与iTransformer融合模型在时间序列预测,特别是风电功率预测中的应用。通过解析iTransformer‘倒置’视角的创新架构与TCN强大的局部时序捕捉能力,文章提供了完整的融合方案设计、源码实现及实战调优经验,旨在构建更强大的下一代预测引擎。 阅读详情

两篇文章掌握Tensorflow中scope用法:

【1】Tensorflow中scope命名方法(本文)

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

微信公众号

1. tf.name_scope()

在 Tensorflow 当中有两种途径生成变量 variable,一种是 tf.get_variable(),另一种是tf.variable()。 如果在tf.name_scope()的框架下使用这两种方式,结果会如下。

import tensorflow as tf

with tf.name_scope("a_name_scope"):
    initializer = tf.constant_initializer(value=1)
    var1 = tf.get_variable(name='var1', shape=[1], dtype=tf.float32, initializer=initializer)
    var2 = tf.Variable(name='var2', initial_value=[2], dtype=tf.float32)
    var21 = tf.Variable(name='var2', initial_value=[2.1], dtype=tf.float32)
    var22 = tf.Variable(name='var2', initial_value=[2.2], dtype=tf.float32)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(var1.name)        # var1:0
    print(sess.run(var1))   # [ 1.]
    print(var2.name)        # a_name_scope/var2:0
    print(sess.run(var2))   # [ 2.]
    print(var21.name)       # a_name_scope/var2_1:0
    print(sess.run(var21))  # [ 2.1]
    print(var22.name)       # a_name_scope/var2_2:0
    print(sess.run(var22))  # [ 2.2]

结果:

分析:

在tf.name_scope()中使用tf.variable()定义变量的时候,虽然name都一样,但是为了不重复变量名,Tensorflow输出的变量名并不是一样的。所以,本质上var2、var21、var22并不是一样的变量。而另一方面,使用tf.get_variable()定义的变量不会被tf.name_scope()当中的名字所影响,相当于tf.name_scope()对tf.get_variable()是无效的。

2. tf.variable_scope()

如果想要达到重复利用变量的效果, 我们就要使用tf.variable_scope(), 并搭配tf.get_variable()。这种方式产生和提取变量,不像tf.Variable()每次都会产生新的变量,tf.get_variable() 如果遇到了同样名字的变量时, 它会单纯的提取这个同样名字的变量(避免产生新变量), 当在重复使用相同变量名字的时候, 一定要在代码中强调 scope.reuse_variables() ,否则系统将会报错, 以为你只是不小心重复使用到了一个已经使用过的变量。

import tensorflow as tf

with tf.variable_scope("a_variable_scope") as scope:
    initializer = tf.constant_initializer(value=3)
    var3 = tf.get_variable(name='var3', shape=[1], dtype=tf.float32, initializer=initializer)
    scope.reuse_variables()
    var3_reuse = tf.get_variable(name='var3', )
    var4 = tf.Variable(name='var4', initial_value=[4], dtype=tf.float32)
    var4_reuse = tf.Variable(name='var4', initial_value=[4], dtype=tf.float32)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(var3.name)  # a_variable_scope/var3:0
    print(sess.run(var3))  # [ 3.]
    print(var3_reuse.name)  # a_variable_scope/var3:0
    print(sess.run(var3_reuse))  # [ 3.]
    print(var4.name)  # a_variable_scope/var4:0
    print(sess.run(var4))  # [ 4.]
    print(var4_reuse.name)  # a_variable_scope/var4_1:0
    print(sess.run(var4_reuse))  # [ 4.]

结果:

分析: 

上面结果中,var3和var3_reuse是同一个变量,而var4和var4_reuse是不同的变量。

在tf.variable_scope()中,使用tf.get_variable()方法创建变量时,如果这个变量已经存在,想直接使用这个变量,加上scope.reuse_variables()即可;如果没有加上scope.reuse_variables(),Tensorflow会报重复使用变量的错误。

不管是在tf.name_scope还是在tf.variable_scope()中,tf.Variable()都是在创建新的变量。如果这个变量存在,则后缀会增加0、1、2等数字编号予以区别。

3. RNN应用例子

在使用循环神经网络(RNN)对序列化数据建模时,training RNN和test RNN的time_steps会有不同的取值,这将会影响整个RNN的结构,所以导致在test的时候,不能单纯的使用training时建立的那个RNN模型。但是,training RNN和test RNN又必须是有相同的weights biases的参数。所以,这时就是使用reuse variable的好时机。

下面给一个例子:

首先,定义training和test的不同参数:

class TrainConfig:
    batch_size = 20
    time_steps = 20
    input_size = 10
    output_size = 2
    cell_size = 11
    learning_rate = 0.01


class TestConfig(TrainConfig):
    time_steps = 1
    
train_config = TrainConfig()
test_config = TestConfig()

然后,让train_rnn 和 test_rnn 在同一个tf.variable_scope(‘rnn’) 之中。 并且定义scope.reuse_variables(), 使我们能把train_rnn的所有 weights, biases 参数全部绑定到test_rnn 中。这样,不管两者的time_steps有多不同,结构有多不同,train_rnn,W,b 参数更新成什么样,test_rnn的参数也更新成什么样。

with tf.variable_scope('rnn') as scope:
    sess = tf.Session()
    train_rnn = RNN(train_config)
    scope.reuse_variables()
    test_rnn = RNN(test_config)
    sess.run(tf.global_variables_initializer())

最后,给出RNN用tf.variable_scope()和get_variable_scope()实现参数共享的完整例子:

# 22 scope (name_scope/variable_scope)
from __future__ import print_function
import tensorflow as tf

class TrainConfig:
    batch_size = 20
    time_steps = 20
    input_size = 10
    output_size = 2
    cell_size = 11
    learning_rate = 0.01


class TestConfig(TrainConfig):
    time_steps = 1


class RNN(object):

    def __init__(self, config):
        self._batch_size = config.batch_size
        self._time_steps = config.time_steps
        self._input_size = config.input_size
        self._output_size = config.output_size
        self._cell_size = config.cell_size
        self._lr = config.learning_rate
        self._built_RNN()

    def _built_RNN(self):
        with tf.variable_scope('inputs'):
            self._xs = tf.placeholder(tf.float32, [self._batch_size, self._time_steps, self._input_size], name='xs')
            self._ys = tf.placeholder(tf.float32, [self._batch_size, self._time_steps, self._output_size], name='ys')
        with tf.name_scope('RNN'):
            with tf.variable_scope('input_layer'):
                l_in_x = tf.reshape(self._xs, [-1, self._input_size], name='2_2D')  # (batch*n_step, in_size)
                # Ws (in_size, cell_size)
                Wi = self._weight_variable([self._input_size, self._cell_size])
                print(Wi.name)
                # bs (cell_size, )
                bi = self._bias_variable([self._cell_size, ])
                # l_in_y = (batch * n_steps, cell_size)
                with tf.name_scope('Wx_plus_b'):
                    l_in_y = tf.matmul(l_in_x, Wi) + bi
                l_in_y = tf.reshape(l_in_y, [-1, self._time_steps, self._cell_size], name='2_3D')

            with tf.variable_scope('cell'):
                cell = tf.contrib.rnn.BasicLSTMCell(self._cell_size)
                with tf.name_scope('initial_state'):
                    self._cell_initial_state = cell.zero_state(self._batch_size, dtype=tf.float32)

                self.cell_outputs = []
                cell_state = self._cell_initial_state
                for t in range(self._time_steps):
                    if t > 0: tf.get_variable_scope().reuse_variables()
                    cell_output, cell_state = cell(l_in_y[:, t, :], cell_state)
                    self.cell_outputs.append(cell_output)
                self._cell_final_state = cell_state

            with tf.variable_scope('output_layer'):
                # cell_outputs_reshaped (BATCH*TIME_STEP, CELL_SIZE)
                cell_outputs_reshaped = tf.reshape(tf.concat(self.cell_outputs, 1), [-1, self._cell_size])
                Wo = self._weight_variable((self._cell_size, self._output_size))
                bo = self._bias_variable((self._output_size,))
                product = tf.matmul(cell_outputs_reshaped, Wo) + bo
                # _pred shape (batch*time_step, output_size)
                self._pred = tf.nn.relu(product)    # for displacement

        with tf.name_scope('cost'):
            _pred = tf.reshape(self._pred, [self._batch_size, self._time_steps, self._output_size])
            mse = self.ms_error(_pred, self._ys)
            mse_ave_across_batch = tf.reduce_mean(mse, 0)
            mse_sum_across_time = tf.reduce_sum(mse_ave_across_batch, 0)
            self._cost = mse_sum_across_time
            self._cost_ave_time = self._cost / self._time_steps

        with tf.variable_scope('trian'):
            self._lr = tf.convert_to_tensor(self._lr)
            self.train_op = tf.train.AdamOptimizer(self._lr).minimize(self._cost)

    @staticmethod
    def ms_error(y_target, y_pre):
        return tf.square(tf.subtract(y_target, y_pre))

    @staticmethod
    def _weight_variable(shape, name='weights'):
        initializer = tf.random_normal_initializer(mean=0., stddev=0.5, )
        return tf.get_variable(shape=shape, initializer=initializer, name=name)

    @staticmethod
    def _bias_variable(shape, name='biases'):
        initializer = tf.constant_initializer(0.1)
        return tf.get_variable(name=name, shape=shape, initializer=initializer)


if __name__ == '__main__':
    train_config = TrainConfig()
    test_config = TestConfig()

    # the wrong method to reuse parameters in train rnn
    with tf.variable_scope('train_rnn'):
        train_rnn1 = RNN(train_config)
    with tf.variable_scope('test_rnn'):
        test_rnn1 = RNN(test_config)

    # the right method to reuse parameters in train rnn
    with tf.variable_scope('rnn') as scope:
        sess = tf.Session()
        train_rnn2 = RNN(train_config)
        scope.reuse_variables()
        test_rnn2 = RNN(test_config)
        # tf.initialize_all_variables() no long valid from
        # 2017-03-02 if using tensorflow >= 0.12
        if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:
            init = tf.initialize_all_variables()
        else:
            init = tf.global_variables_initializer()
        sess.run(init)

4. Reference

【1】莫烦PYTHON:scope命名方法

【2】共享变量RNN实现代码(reuse variable RNN代码)

《信息化项目文档模板十二——业务需求新增/变更审批确认表 》 系列文章目录 《信息化项目文档模板一——项目需求说明书》 《信息化项目文档模板二——项目启动会文档模板》 《信息化项目文档模板三——会议纪要模板》 《信息化项目文档模板四——系统项目蓝图设计模板》 《信息化项目文档模板五——系统详细设计模板》 《信息化项目文档模板六——系统详细设计模板》 《信息化项目文档模板七——系统开发计划模板》 《信息化项目文档模板八——系统功能测试模板》 《信息化项目文档模板九——系统压力测试模板》 《信息化项目文档模板十——系统推广上线计划模板》 《信息化项目文档模板十一——系统用 阅读详情

相关推荐

innovus中path group 的策略和应用(上)

在所有的后端工具里边,有三个重要的引擎:auto-place,CTS,auto-route三个。这里边的auto-place是决断了整个设计时序的基点。。当然,就算是到了CTS/route阶段后,也可以继续利用auto-place数据优化的功能,在数据库上做数据路径增量优化(optDesign -increment)。可以说,数据路径的优化手段,实际上是贯穿在整个后端流程上的。。看看这其中的奥妙和有趣的事情。ICer GO!

i_chip_backend的博客 4217

tensorflow中的scope命名方法:name_scope, variavle_scope

转自:知乎回答:tensorflow里面name_scope, variable_scope等如何理解? 1 在训练深度网络时,为了减少需要训练参数的个数(比如具有simase结构的LSTM模型)、或是多机多卡并行化训练大数据大模型(比如数据并行化)等情况时,往往需要共享变量。另外一方面是当一个深度学习模型变得非常复杂的时候,往往存在大量的变量和操作,如何避免这些变量名和操作名的唯一不重复...

taolusi的博客 1313

基于 WebGoat 平台的 SQL 注入攻击

基于 WebGoat 平台的 SQL 注入攻击

Labulongdong的博客 3522

关于tensorflow中的scope的命名及使用方法

相信大家在学习和使用tensorflow的过程中肯定会遇到过关于scope的一些问题,scope是一种给变量命名的方法,它会让变量命名变得简单,同时也常用于reusing variable 代码中,下面将会给大家讲解一下tensorflow中两种定义scope的方法,来帮助大家更好的理解和使用scope。前言:scope的命名方式分为两种,tf.name_scope( )和tf.variable_s

Winter_FDd的博客 1万+

H.264 Profile与Level详解:如何为不同应用场景选择合适的编码配置

本文深入解析了H.264编码标准中的Profile与Level概念,指导开发者如何为不同应用场景选择合适的配置。文章对比了Baseline、Main和High三大Profile的特性与适用场景,并解释了Level如何限定视频的分辨率、帧率与码率上限。通过实战指南,帮助读者在视频通话、在线点播和专业制作等场景中,平衡画质、兼容性与性能,实现高效编码。

rgv2345678的博客 238

【电力电子控制】基于强化学习的单相逆变器并网电流控制

本文将尝试以 DQN(Deep Q-Network)为例,设计并训练一个面向单相逆变器的智能控制器,实现对并网电流的精准调节。

weixin_62596197的博客 463

tensorflow scope的意义

tensorflow中创建variable的2种方式 tf.Variable():只要使用该函数,一律创建新的variable,如果出现重名,变量名后面会自动加上后缀 var:0 var_1:0 var_2:0 tf.get_variable():如果变量存在,则共享以前创建的变量,如果不存在,则新创建一个变量 1,变量存在,但无法共享 2,变量不存在,但无法创建 tensorflow中的两种作用域 命名域(name scope):通过tf.name_scope()来实现; 变量

潘钟鸣的博客 578

【遥感数字图像处理(朱文泉)】第一章 数字图像基础

关于图像的定义、类型、模拟图像和数字图像

甜子yu的博客 4404

TensorFlow基础三(Scope)

用到变量名了,就涉及到了名字域的概念。通过不同的域来区别变量名,毕竟给所有变量都直接取不同名字还是有点辛苦的。 主要是name_scope和variable_scope,name_scope 作用于操作,variable_scope 可以通过设置reuse 标志以及初始化方式来影响域下的变量。当然还有个更直观的感受就是:在tensorboard 里可视化的时候用名字域进行封装后会更清晰。 之所...

weixin_30878501的博客 278

CCC数字钥匙Release 3实战:如何用BLE/UWB实现无钥匙进入(附避坑指南)

本文深入解析CCC数字钥匙Release 3标准下BLE/UWB无钥匙进入系统的开发实践,涵盖硬件选型、安全测距协议、时序同步等关键环节,并提供实战调试技巧与安全攻防案例。特别针对BLE芯片配置、UWB模块选型等常见陷阱给出解决方案,帮助开发者高效实现厘米级精度的数字钥匙系统。

weixin_29326909的博客 255

使用 MATLAB/Simulink + Simscape Electrical + Simulink Design Optimization,构建一个沙漠环境中光伏组件灰尘积累与效率下降仿真模型

本文通过,构建了沙漠环境中光伏组件灰尘积累与效率下降仿真模型✅ 建立了风速-沙尘-积尘速率的物理关系✅ 仿真了灰尘积累过程及其对Isc 和 Pmax的影响✅ 量化分析了不同清洁策略的经济性✅ 提出了优化设计与智能运维建议。

xiaoheshang_123的博客 123

tensorflow scope()函数大型指导

目录 get_model_varibales()和get_variables() tf.valuable_scope() tf.name_scope()名称覆盖机制 slim升级至tf.contrib.framework.arg_scope()/tf.contrib.layers get_model_varibales()和get_variables() ...

猫头军师兵书 672

PyTorch实战(13)——图卷积网络(Graph Convolutional Network,GCN)

图卷积网络 (Graph Convolutional Network, GCN) 模型能够同时结合节点级特征和图级(邻域)信息进行分类,显著提升了图数据建模能力,适用于节点分类、图分类等多种任务。本节中,我们通过 PyTorch Geometric 库在 CiteSeer 图数据集上构建模型,们首先用前馈神经网络作为基线模型完成节点分类任务,随后用 GCN 模型替代前馈网络显著提升了分类准确率。

盼小辉丶的博客 3261

tensorflow:scope 命名方法

文章目录遇到问题两种命名空间tf.name_scope()tf.variable_scope()项目中的解决方法参考 遇到问题 在使用cleverhans这个对抗工程时https://github.com/tensorflow/cleverhans,想把他给的网络结构改成自己的网络结构,然后进行攻击和防御时,一直遇到关于tensorflow命名变量的问题,特此来记录下 两种命名空间 tf.name...

苏门蒲元的博客 279

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

tensorflow scope命名方法(variable_scope()与name_scope()解析)

学习资料: 不同 scope 对比代码 reuse variable RNN 代码 sharing variable tensorflow 官网介绍 scope 能让你命名变量的时候轻松很多. 同时也会在 reusing variable 代码中常常见到. 所以今天我们会来讨论下 tensorflow 当中的两种定义 scope 的方式. 最后并附加一个 RNN 运用 reuse vari

AI_盲的博客 4074

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

TensorFlow入门(四) name / variable_scope 的使用

name/variable_scope 的作用欢迎转载,但请务必注明原文出处及作者信息。@author: huangyongye @creat_date: 2017-03-08 refer to: Sharing Variables name / variable_scope 详细理解请看: TensorFlow入门(七) 充分理解 name / variable_scope* 起因:在运行

大学之道,在明明德 2万+

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

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

tensorflow中计算图节点和张量的命名

做模型转换的时候需要指明网络输入输出节点的名字,第一次看还挺一头雾水的,大概记录了一下tensorflow节点和张量的命名。

qq_43802016的博客 472

Tensorflow学习记录8 scope

""" 命名方式 What's name_scope? What's variable_scope? 基本上都是把变量的名字动一下手脚 """ import tensorflow as tf # # ############## name_scope ####################################################################...

RonnyChan的博客 252

TensorFlow # Scope,Name,Reuse参数意义及变量重用机制

scope参数用途 tensorflow的执行过程:1)定义Graphs,包括Variables和Operations 。2)创建session,运行Graphs 在定义Variables的时候,Scope相当于C++中的命名空间,可以用Scope来避免命名冲突,以及方便重用Variables。 with tf.variable_scope(scope, reuse=reuse): out = input out = layers.fully_connected(out, num_outpu

skysys的研究小屋 1193

TensorFlow入门变量 variable_scope、 name_scope

#tf.variable_scope可以让变量有相同的命名,包括tf.get_variable得到的变量,还有tf.Variable的变量 这两个不能同时出现需要引掉一个 #tf.name_scope可以让变量有相同的命名,只是限于tf.Variable的变量 import tensorflow as tf #使用tf.name_scope tf.variable_scope时的区别 with ...

Anitaw的博客 312

tensorflow学习笔记(十五): variable scope

variable scopetensorflow 为了更好的管理变量,提供了variable scope机制 官方解释: Variable scope object to carry defaults to provide to get_variable.Many of the arguments we need for get_variable in a variable store are

Keith 3万+

关于tensorflow中tf.variable_scope 和tf.name_scope的一些理解

资料来源:https://blog.youkuaiyun.com/UESTC_C2_403/article/details/72328815 tf.variable_scope 和tf.name_scope都是tensorflow框架中用来表示流图上各个节点、变量等的名字,其区别在于: tf.variable_scope相当于建立一个可以保存多个变量的文件夹,冒号后的变量命名为"V1/a1"、"V2/a2...

m0_37982806的博客 460

tensorflow变量命名相关以及tf.variable_scope和tf.name_scope

1.tensorflow变量名字 tensorflow提供了通过变量名称来创建或者获取一个变量的机制。可以通过变量的名字来使用变量,同时也能通过判断变量名称知道变量是否重复。当reuse为False或者None时(这也是默认值),同一个tf.variable_scope下面的变量名不能相同;当reuse为True时,tf.variable_scope只能获取已经创建过的变量。 reuse=F...

weixin_42752435的博客 1487

tensorflow中name_scope和variable_scope变量的使用

1. variable_scope的使用 首先,使用variable_scope可以很方便的管理get_varibale。 如何确定 get_variable 的 prefixed name? 1.1 variable scope是可以嵌套的: import tensorflow as tf with tf.variable_scope("tet1"): var3 = tf....

lilong117194的博客 3516

Tensorflow学习(二) name_scope和variable_scope

tf.name_scope()创建名称作用域,可以影响tf.Variable和tf.Operation,主要用于对节点名称命名,方便Tensorboard记录和分类节点创建名称作用域,可以影响tf.Variable和tf.Operationwith tf.name_scope('foo') as foo_scope:     a = tf.Variable(1, name='a')     ass...

yangbin7752的博客 332

tf.variable_scope()和tf.name_scope()

1.tf.variable_scope 功能:tf.variable_scope可以让不同命名空间中的变量取相同的名字,无论tf.get_variable或者tf.Variable生成的变量 TensorFlow链接:https://tensorflow.google.cn/api_docs/python/tf/variable_scope?hl=en 举例: with tf...

dili8870的博客 260
上一篇: 【LeetCode】91. Decode Ways
下一篇: 对循环神经网络(RNN)中time step的理解
Microstrong0305
Microstrong0305 领域专家: 算法与数据结构技术领域 领域专家: 算法与数据结构技术领域
博客等级 码龄12年 6405粉丝 312原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值