因为最近在研究生成对抗网络GAN,在读别人的代码时发现了 with tf.variable_scope(self.name_scope_conv, reuse = reuse): 这样一条语句,查阅官方文档时明白了这是TensorFlow的变量共享机制。

举个例子:当我们研究生成对抗网络GAN的时候,判别器的任务是,如果接收到的是生成器生成的图像,判别器就尝试优化自己的网络结构来使自己输出0,如果接收到的是来自真实数据的图像,那么就尝试优化自己的网络结构来使自己输出1。也就是说,生成图像和真实图像经过判别器的时候,要共享同一套变量,所以TensorFlow引入了变量共享机制。

变量共享主要涉及到两个函数:  tf.get_variable(<name>, <shape>, <initializer>)  和  tf.variable_scope(<scope_name>)  。

1. tf.get_variable(<name>, <shape>, <initializer>)

例如,我们搭建一个卷积层:

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_initializer(0.0))
conv = tf.nn.conv2d(input, weights,
strides=[1, 1, 1, 1], padding='SAME')
return tf.nn.relu(conv + biases)

然后,我们调用两次:

input1 = tf.random_normal([1,10,10,32])
input2 = tf.random_normal([1,20,20,32])
x = conv_relu(input1, kernel_shape=[5, 5, 1, 32], bias_shape=[32])
x = conv_relu(x, kernel_shape=[5, 5, 32, 32], bias_shape = [32]) # This fails.

会发现报错信息。因为执行的命令不明确:第二次调用时是创建一套新的变量(weights,biases)还是再次使用已存在的那一套变量(第一次调用时生成的weights和biases)呢?

这时就需要用到第二个函数: tf.variable_scope(<scope_name>)

2. tf.variable_scope(<scope_name>)

请看例子:

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, 1, 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])

在不同的域内会生成不同的变量。

如果想要变量共享,TensorFlow提供了两种方法:

1. 设置  reuse=True

with tf.variable_scope("model"):
output1 = my_image_filter(input1)
with tf.variable_scope("model", reuse=True):
output2 = my_image_filter(input2)

2. 调用 scope.reuse_variables()

with tf.variable_scope("model") as scope:
output1 = my_image_filter(input1)
scope.reuse_variables()
output2 = my_image_filter(input2)

注:在官方文档的最后有这样一段话:Since depending on exact string names of scopes can feel dangerous, it's also possible to initialize a variable scope based on another one:

with tf.variable_scope("model") as scope:
output1 = my_image_filter(input1)
with tf.variable_scope(scope, reuse=True):
output2 = my_image_filter(input2)

TensorFlow学习笔记4——变量共享的更多相关文章

  1. TensorFlow学习笔记3——变量共享

    因为最近在研究生成对抗网络GAN,在读别人的代码时发现了 with tf.variable_scope(self.name_scope_conv, reuse = reuse): 这样一条语句,查阅官 ...

  2. tensorflow学习笔记二----------变量

    tensorflow里面的变量表示,需要使用特定的语法进行.如果想构造一个行(列)向量,需要调用Variable函数进行.对两个变量进行操作,也要调用相应的函数. import tensorflow ...

  3. tensorflow学习笔记——使用TensorFlow操作MNIST数据(2)

    tensorflow学习笔记——使用TensorFlow操作MNIST数据(1) 一:神经网络知识点整理 1.1,多层:使用多层权重,例如多层全连接方式 以下定义了三个隐藏层的全连接方式的神经网络样例 ...

  4. tensorflow学习笔记——自编码器及多层感知器

    1,自编码器简介 传统机器学习任务很大程度上依赖于好的特征工程,比如对数值型,日期时间型,种类型等特征的提取.特征工程往往是非常耗时耗力的,在图像,语音和视频中提取到有效的特征就更难了,工程师必须在这 ...

  5. TensorFlow学习笔记(一)

    [TensorFlow API](https://www.tensorflow.org/versions/r0.12/how_tos/variable_scope/index.html) Tensor ...

  6. Tensorflow学习笔记2019.01.22

    tensorflow学习笔记2 edit by Strangewx 2019.01.04 4.1 机器学习基础 4.1.1 一般结构: 初始化模型参数:通常随机赋值,简单模型赋值0 训练数据:一般打乱 ...

  7. 深度学习-tensorflow学习笔记(2)-MNIST手写字体识别

    深度学习-tensorflow学习笔记(2)-MNIST手写字体识别超级详细版 这是tf入门的第一个例子.minst应该是内置的数据集. 前置知识在学习笔记(1)里面讲过了 这里直接上代码 # -*- ...

  8. tensorflow学习笔记(1)-基本语法和前向传播

    tensorflow学习笔记(1) (1)tf中的图 图中就是一个计算图,一个计算过程.                                       图中的constant是个常量 计 ...

  9. TensorFlow学习笔记——LeNet-5(训练自己的数据集)

    在之前的TensorFlow学习笔记——图像识别与卷积神经网络(链接:请点击我)中了解了一下经典的卷积神经网络模型LeNet模型.那其实之前学习了别人的代码实现了LeNet网络对MNIST数据集的训练 ...

随机推荐

  1. HDU 3516 Tree Construction

    区间$dp$,四边形优化. #pragma comment(linker, "/STACK:1024000000,1024000000") #include<cstdio&g ...

  2. 初识.NET Core

    dotnet new console dotnet new web dotnet new webapi dotnet run dotnet build -r win-x64 dotnet publis ...

  3. centos7 启用iptables

    在centos 7下启用iptables systemctl stop firewalld.service systemctl disable firewalld.service yum instal ...

  4. Xamarin XAML语言教程控件模板的模板绑定

    Xamarin XAML语言教程控件模板的模板绑定 控件模板的模板绑定 为了可以轻松更改控件模板中控件上的属性值,可以在控件模板中实现模板绑定功能.模板绑定允许控件模板中的控件将数据绑定到公共属性上. ...

  5. [POJ1801]Formula Racing(模拟)

    Formula Racing Time Limit: 1000MS   Memory Limit: 30000K Total Submissions: 289   Accepted: 77 Descr ...

  6. 【分类讨论】Codeforces Round #395 (Div. 2) D. Timofey and rectangles

    D题: 题目思路:给你n个不想交的矩形并别边长为奇数(很有用)问你可以可以只用四种颜色给n个矩形染色使得相接触的 矩形的颜色不相同,我们首先考虑可不可能,我们分析下最多有几个矩形互相接触,两个时可以都 ...

  7. python3开发进阶-Djamgo框架中的JSON和AJAX

    阅读目录 什么是JSON 什么是AJAX AJAX常见的应用情景 jQery实现AJAX AJAX请求如何设置csrf_token AJAX上传文件 补充Django内置的serializers 一. ...

  8. ujmp使用心得

    1)对矩阵转置运算时: Matrix test2 = oneMatrix.transpose(); Matrix test2 = oneMatrix.transpose(Ret.LINK); Matr ...

  9. Android之startActivityForResult

    作用:当aAty跳转之bAty时,需要bAty回传数据,使用startActivityForResult. 相关的函数: aAty:--跳转至bAty(intent可以传递数据) void andro ...

  10. 大湿教我写程序(2)之走向AV之路

    一.大摆庆功宴 上一篇博文<大湿教我写程序(1)之菜单导航篇>中讲到了我撸码到晚上两点多,整出了一个还算是高端大气上档次的demo.半夜回到家里打算着可以好好睡上一个懒觉,到时候直接到客户 ...