TensorFLow 变量命名空间实例
作者:man_world 发布时间:2021-06-09 04:40:14
一、name_scope
with tf.name_scope(name):
name_scope: 为了更好地管理变量的命名空间而提出的。比如在 tensorboard 中,因为引入了 name_scope, 我们的 Graph 看起来才井然有序。
name_scope 对 get_variable 创建变量的 name 没有影响,即 get_variable 创建的变量不在 name_scope 这个命名空间中
二、variable_scope
with tf.variable_scope(name_or_scope, reuse=None):
variable_scope: 大部分情况下,跟 tf.get_variable() 配合使用,实现变量共享的功能
可通过tf.get_variable_scope().reuse == True/False 判断参变量是否共享
当前变量作用域可以用tf.get_variable_scope()进行检索并且reuse 标签可以通过调用tf.get_variable_scope().reuse_variables()设置为True
三、共享参变量
1、方法
使用 tf.Variable() 创建同一个 name 的变量(操作名不同),均不会报错,但系统会自动修改 name(实质还是不让共享参变量)
使用 tf.get_varible() 创建同一个 name 的变量(操作名不同),均会报错(为了避免无意识的参变量复用造成的错误)
我们可以在 variable_scope 中使用 tf.get_variable() 创建变量,并通过 with tf.variable_scope(name_or_scope, reuse=True) 来共享参变量:
reuse=True:将只能获取命名空间中已经创建过的变量,如果变量不存在,则tf.get_variable函数将报错。
reuse=None / False:tf.get_variable操作将创建新的变量,如果同名的变量已经存在,则tf.get_variable函数将报错。
2、代码示例
# 下面是定义一个卷积层的通用方式
def conv_relu(input, kernel_shape, bias_shape):
# Create variable named "weights".
weights = tf.get_variable("weights", kernel_shape,
initializer=tf.random_normal_initializer())
# Create variable named "biases".
biases = tf.get_variable("biases", bias_shape,
initializer=tf.constant_intializer(0.0))
conv = tf.nn.conv2d(input, weights,
strides=[1, 1, 1, 1], padding='SAME')
return tf.nn.relu(conv + biases)
# 定义一个图片过滤器
def my_image_filter(input_images):
with tf.variable_scope("conv1"):
# Variables created here will be named "conv1/weights", "conv1/biases".
relu1 = conv_relu(input_images, [5, 5, 32, 32], [32])
with tf.variable_scope("conv2"):
# Variables created here will be named "conv2/weights", "conv2/biases".
return conv_relu(relu1, [5, 5, 32, 32], [32])
# 实验一:调用 my_image_filter() 两次
result1 = my_image_filter(image1)
result2 = my_image_filter(image2)
>>> Raises ValueError(... conv1/weights already exists ...), tf.get_variable()会检测已经存在的变量是否已经共享
# 解决方法一, 可以在设计网络时加上一个布尔型的 reuse 参数
with tf.variable_scope("image_filters"):
result1 = my_image_filter(image1)
with tf.variable_scope("image_filters", reuse=True):
result2 = my_image_filter(image2)
# 解决方法二
with tf.variable_scope("image_filters") as scope:
# 下面我们两次调用 my_image_filter 函数,但是由于引入了变量共享机制
# 可以看到我们只是创建了一遍网络结构。
result1 = my_image_filter(image1)
scope.reuse_variables()
result2 = my_image_filter(image2)
# 解决方法三
with tf.variable_scope("image_filters") as scope:
result1 = my_image_filter(image1)
with tf.variable_scope(scope, reuse=True):
result2 = my_image_filter(image2)
# 打印出所有的可训练参变量
vs = tf.trainable_variables()
print('There are %d trainable_variables in the Graph: ' % len(vs))
for v in vs:
print(v)
# 输出结果证明确实:参变量共享,因为只有四个变量,没有创建新的变量。
There are 4 trainable_variables in the Graph:
Tensor("image_filters/conv1/weights/read:0", shape=(5, 5, 32, 32), dtype=float32)
Tensor("image_filters/conv1/biases/read:0", shape=(32,), dtype=float32)
Tensor("image_filters/conv2/weights/read:0", shape=(5, 5, 32, 32), dtype=float32)
Tensor("image_filters/conv2/biases/read:0", shape=(32,), dtype=float32)
四、取出所有可训练参数
# Returns all variables created with trainable=True in a var_list
var_list = tf.trainable_variables()
init = tf.global_variables_initializer()
sess.run(init)
for var in var_list:
sess.run(var)
来源:https://blog.csdn.net/mzpmzk/article/details/78647688


猜你喜欢
- 1、何为ansible-playbookplaybook是ansible用于配置,部署,和管理被控节点的剧本,通过playbook的详细描述
- 1.背景一直苦恼于本地机器和服务器上都要配置一些机器学习方面的环境,今天花了点时间研究了下Jupter notebook远程访问服务器,所以
- 我就废话不多说了,大家还是直接看例子吧!import numpy as npfrom numpy import randommatrix1
- <?php header(“Content-Type:text/html;charset=utf-8″); if (isset($_G
- 系统环境centos7python2.7先在操作系统安装expect[root@V71 python]# vi 3s.py#!/usr/bi
- 本文实例讲述了wxPython主框架的简单用法,分享给大家供大家参考。具体如下:程序代码如下:import wx class MyApp(w
- 本文主要介绍了Python利用numpy实现三层神经网络的示例代码,分享给大家,具体如下:其实神经网络很好实现,稍微有点基础的基本都可以实现
- 按比例获取样本数据或执行任务By:授客 QQ:1033553122开发环境win 10python 3.6.5需求已知每种分类的样本占比数,
- 如下所示:screen.widthscreen.heightscreen.availHeight //获取去除状态栏后的屏幕高度screen
- 基于Vue的页面切换左右滑动效果,具体内容如下HTML文本页面:<template> <div id="app&
- python中字典是非常常用的数据类型,了解各种方法的作用及优缺点对于字典的使用非常有用。dict.clear() 的方法用于清空所有的键值
- 题目描述原题链接 :35. 搜索插入位置 - 力扣(LeetCode) (leetcode-cn.com)给定一个排序数组和一个目标值,在数
- 本文实例讲述了SqlServer2016模糊匹配的三种方式及效率问题。分享给大家供大家参考,具体如下:数据库是Sqlserver 2016版
- 本文实例讲述了Python复制文件操作用法。分享给大家供大家参考,具体如下:这里用python实现了一个小型的自动发版本的工具。这个“自动发
- 在这里我想有必要再较系统说一下ADO的各种对象的方法、属性。毕竟ADO不仅应用在ASP中,VB,VC都可以用到。在这十天中我想主要提到的对象
- 1. 特定版本的python-opencv安装在https://www.lfd.uci.edu/~gohlke/pythonlibs/#op
- PIL:使用python自带图像处理库读取出来的图片格式numpy:使用python-opencv库读取出来的图片格式tensor:pyto
- Mysql 二进制安装方法下载mysqlhttps://dev.mysql.com/downloads/mysql/1.解压包tar xf
- 当你检查scrapy二进制文件时,你会注意到这么一段python script#!/usr/bin/pythonfrom scrapy.cm
- MySQL中涉及的几个字符集 character-set-server/default-character-set:服务器字符集,默认情况下