一、上下文管理器(context manager)

上下文管理器是实现了上下文协议的对象,主要用于资源的获取与释放。上下文协议包括__enter__、__exit__,简单说就是,具备__enter__()和__exit__()方法的类就可以实现上下文管理,做到文件的自动关闭,这样的类实例化的对象就是上下文管理器。

典型的例子就是读写文件的操作。使用open()函数打开文件,操作之后再用close()函数关闭文件。如果使用上下文管理器的的话就会简洁方便些,因为File()类内部包含有__enter__、__exit__这两种方法。同时,python提供的with也能简化资源操作后的清除操作,实现原理建立在上下文管理器之上。

with open('test.txt','w') as file:
file.write(data)

二、name_scope

定义python op使用的上下文管理器

该上下文管理器验证给定的values是否来自相同的Graph、将该Graph设为默认Graph、将命名空间(name scope)存入图中。

下面的代码定义了一个叫做my_op的python op:

def my_op(a, b, c, name=None):
with tf.name_scope(name, "MyOp", [a, b, c]) as scope:
a = tf.convert_to_tensor(a, name="a")
b = tf.convert_to_tensor(b, name="b")
c = tf.convert_to_tensor(c, name="c")
# Define some computation that uses `a`, `b`, and `c`.
return foo_op(..., name=scope)

tf.name_scope()主要是用来管理命名空间的,这样能使模型更加有条理。

三、variable_scope

定义创建变量这一操作的上下文管理器

变量空间允许您创建新的变量并共享已经创建的变量,同时提供检查以避免意外地创建或共享

如何创建新变量的示例:

with tf.variable_scope("foo"):
with tf.variable_scope("bar"):
v = tf.get_variable("v", [1])
assert v.name == "foo/bar/v:0"

使用AUTO_REUSE共享变量:

with tf.variable_scope("foo"):
with tf.variable_scope("bar"):
v = tf.get_variable("v", [1])
assert v.name == "foo/bar/v:0"

使用reuse=True共享变量:

with tf.variable_scope("foo"):
v = tf.get_variable("v", [1])
with tf.variable_scope("foo", reuse=True):
v1 = tf.get_variable("v", [1])
assert v1 == v

通过捕获空间和设置重用共享变量:

with tf.variable_scope("foo") as scope:
v = tf.get_variable("v", [1])
scope.reuse_variables()
v1 = tf.get_variable("v", [1])
assert v1 == v

在non-resue scope中共享变量会报错:

with tf.variable_scope("foo"):
v = tf.get_variable("v", [1])
v1 = tf.get_variable("v", [1])
# Raises ValueError("... v already exists ...").

注意的是:reuse标志是会被继承的。即如果一个scope被设置为reuse mode,那么它的sub-scopes也会处于reuse mode。、

variable_scope大部分情况下和tf.get_variable()配合使用,实现变量共享。

import os
import tensorflow as tf
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

    with tf.Session() as sess:
with tf.name_scope('name_scope'): # 命名空间
var1 = tf.Variable(initial_value=[1], name='var1') # 创建变量
with tf.variable_scope('variable_scope'): # 变量空间
var2 = tf.Variable([2], name='var2') # 创建变量
var3 = tf.get_variable(name='var3', shape=[]) # 创建可共享变量
print('var1.name', var1.name)
print('var2.name', var2.name)
print('var3.name', var3.name)

运行结果:

var1.name name_scope/var1:0
    var2.name name_scope/variable_scope/var2:0
    var3.name variable_scope/var3:0

可以发现tf.name_scope()不会对tf.get_variable创建的变量有任何影响

tf.name_scope()主要是管理命名空间,让模型井然有序,而tf.variable_scope()的作用是配合tf.get_variable()实现变量共享

四、tf.Variable()tf.get_variable()

  • class Variable

变量在Graph中起到通过调用run()维持状态的作用。可以通过实例化类Variable向Graph添加变量。

import tensorflow as tf

# 创建一个变量
w = tf.Variable(<initial-value>, name=<optional-name>) # Use the variable in the graph like any Tensor.
y = tf.matmul(w, ...another variable or tensor...) # The overloaded operators are available too.
z = tf.sigmoid(w + y) # Assign a new value to the variable with `assign()` or a related method.
w.assign(w + 1.0)
w.assign_add(1.0)
  • tf.get_variable()

获取符合这些参数的现有变量或创建新参数.

该函数给当前变量空间的name加前缀并检查是否有重用。

def foo():
with tf.variable_scope("foo", reuse=tf.AUTO_REUSE):
v = tf.get_variable("v", [1])
return v v1 = foo() # Creates v. 创建一个新变量
v2 = foo() # Gets the same, existing v. 得到一个符合参数的现有变量
assert v1 == v2

创建变量有三种方式,但只有tf.get_variable()创建的变量会发生命名冲突。在实际使用中,三种创建变量方式的用途区别也是明显的:

  • tf.placeholder()      #占位符。trainable=False,不是训练参数
  • tf.Variable()           #一般变量的定义使用该种方式。trainablel类型可选
  • tf.get_variable()     #和tf.variable_scope()配合使用,实现变量共享的功能。trainablel类型可选

五、参考链接

tensorflow入门笔记(五) name_scope和variable_scope的更多相关文章

  1. 1 TensorFlow入门笔记之基础架构

    ------------------------------------ 写在开头:此文参照莫烦python教程(墙裂推荐!!!) ---------------------------------- ...

  2. TensorFlow入门(五)多层 LSTM 通俗易懂版

    欢迎转载,但请务必注明原文出处及作者信息. @author: huangyongye @creat_date: 2017-03-09 前言: 根据我本人学习 TensorFlow 实现 LSTM 的经 ...

  3. TensorFlow入门(四) name / variable_scope 的使

    name/variable_scope 的作用 欢迎转载,但请务必注明原文出处及作者信息. @author: huangyongye @creat_date: 2017-03-08 refer to: ...

  4. tensorflow+入门笔记︱基本张量tensor理解与tensorflow运行结构

    Gokula Krishnan Santhanam认为,大部分深度学习框架都包含以下五个核心组件: 张量(Tensor) 基于张量的各种操作 计算图(Computation Graph) 自动微分(A ...

  5. 5 TensorFlow入门笔记之RNN实现手写数字识别

    ------------------------------------ 写在开头:此文参照莫烦python教程(墙裂推荐!!!) ---------------------------------- ...

  6. 2 TensorFlow入门笔记之建造神经网络并将结果可视化

    ------------------------------------ 写在开头:此文参照莫烦python教程(墙裂推荐!!!) ---------------------------------- ...

  7. tensorflow学习笔记五----------逻辑回归

    在逻辑回归中使用mnist数据集.导入相应的包以及数据集. import numpy as np import tensorflow as tf import matplotlib.pyplot as ...

  8. tensorflow学习笔记五:mnist实例--卷积神经网络(CNN)

    mnist的卷积神经网络例子和上一篇博文中的神经网络例子大部分是相同的.但是CNN层数要多一些,网络模型需要自己来构建. 程序比较复杂,我就分成几个部分来叙述. 首先,下载并加载数据: import ...

  9. tensorflow入门笔记(二) 滑动平均模型

    tensorflow提供的tf.train.ExponentialMovingAverage 类利用指数衰减维持变量的滑动平均. 当训练模型的时候,保持训练参数的滑动平均是非常有益的.评估时使用取平均 ...

随机推荐

  1. 从去除毛刺的策略看开运算opening_circle和闭运算closing_circle的异同

    例一:毛刺在往外凸的面上 策略1:分割出黑色部分,然后通过开运算去掉毛刺,再通过原黑色部分区域减去开运算之后的区域,得到毛刺部分的区域. read_image (Tu, 'C:/Users/xiahu ...

  2. recyclerView插入(add)和删除(remove)item后,item错乱,重复,覆盖在原recyclerView上

    项目用到,实现一个recyclerView列表的item翻转动效,翻转的同时会将指定item置顶. (比如交换AB位置,A在0位置,指定的item B 在 i 位置) 原始使用的是插入B到0位置,然后 ...

  3. Gson - 学习

    Google 的 Gson 库,Gson 是一个非常强大的库,可以将 JSON 格式的数据转化成 Java 对象,也支持将 Java 对象转成 JSON 数据格式. Gson 依赖 本文将会快速开始使 ...

  4. windows 注册表讲解

    注册表存储结构: 整个注册表内容主要由项(键).值(键值)构成.(通过regedit命令打开注册表) 5个根键: HKEY_CLASSES_ROOT    (缩写HKCR) HKEY_CURRENT_ ...

  5. mac air 2012 mid 使用bootcamp 安装windows

    一切都按正常顺序进行,到开始安装时,遇到错误: "提示windows无法安装到这个磁盘.选中的磁盘具有MBR分区表" 解决方法: 重新进入mac系统,使用bootcamp从头开始, ...

  6. 关于spring boot自动注入出现Consider defining a bean of type 'xxx' in your configuration问题解决方案

    搭建完spring boot的demo后自然要实现自动注入来体现spring ioc的便利了,但是我在实施过程中出现了这么一个问题,见下面,这里找到解决办法记录下来,供遇到同样的问题的同僚参考 Des ...

  7. 查看CPU/CACHE的拓扑结构

    转自 http://smilejay.com/2017/12/cpu-cache-topology/ Linux上,CPU和Cache相关的拓扑结构,都可以从sysfs文件系统的目录 /sys/dev ...

  8. Tomcat -- 启动错误 -- 解决锦集

    java.lang.NoSuchMethodException: org.apache.catalina.deploy.WebXml addFilter :在Tomacat7的context.xml文 ...

  9. mysql性能调整三板斧

    大意是,用2/8原则,多快好省的解决大部分事情.所以三板斧,仅限整体调整,不牵扯具体细节. 1.innodb 使用innodb引擎 2.innodb_buffer_pool 调整和innodb有关的参 ...

  10. 国内常用NTP服务器地址及

    210.72.145.44 (国家授时中心服务器IP地址) 133.100.11.8 日本 福冈大学 time-a.nist.gov 129.6.15.28 NIST, Gaithersburg, M ...