前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >tf.AUTO_REUSE作用

tf.AUTO_REUSE作用

作者头像
狼啸风云
修改2022-09-03 20:16:30
2K0
修改2022-09-03 20:16:30
举报

概述

在tensorflow中,为了 节约变量存储空间 ,我们常常需要通过共享 变量作用域(variable_scope) 来实现 共享变量 。

大家比较常用也比较笨的一种方法是,在重复使用(即 非第一次使用)时,设置 reuse=True 来 再次调用 该共享变量作用域(variable_scope)。但是这种方法太繁琐了。

有种更简洁 的方法来一次性对variable_scope进行reuse,现将代码模板总结如下:

使用 tf.Variable_scope(…, reuse=tf.AUTO_REUSE)

代码

代码语言:javascript
复制
# -*- coding: utf-8 -*-

import tensorflow as tf

def func(in_put, in_channel, out_channel):
    with tf.variable_scope(name_or_scope='', reuse=tf.AUTO_REUSE):    ### 改动部分 ###
        weights = tf.get_variable(name="weights", shape=[2, 2, in_channel, out_channel],
                                  initializer=tf.contrib.layers.xavier_initializer_conv2d())
        convolution = tf.nn.conv2d(input=in_put, filter=weights, strides=[1, 1, 1, 1], padding="SAME")
    return convolution


def main():
    with tf.Graph().as_default():
        input_x = tf.placeholder(dtype=tf.float32, shape=[1, 4, 4, 1])

        for _ in xrange(5):
            output = func(input_x, 1, 1)
            with tf.Session() as sess:
                sess.run(tf.global_variables_initializer())
                import numpy as np
                _output = sess.run([output], feed_dict={input_x:np.random.uniform(low=0, high=255, size=[1, 4, 4, 1])})
                print _output

if __name__ == "__main__":
    main()
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/11/03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 概述
  • 代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档