博客
关于我
tensorflow的variable scope和name scope
阅读量:271 次
发布时间:2019-03-01

本文共 1280 字,大约阅读时间需要 4 分钟。

在tensorflow中有着独特的变量共享机制,不需要传递reference就可以在不同的代码块中共享变量。而这种变量共享机制就是通过variable_scope和name_scope来实现的。

tf.get_variable

这个函数的作用是创建一个新的变量或者在已经创建的变量中检索一个变量。这个函数和tf.Variable有很大区别,后一个每次都会创建一个新的变量(而且如果创建时传入的名字已经存在,会在tensor的name中默认增加后缀进行区分)
在这里插入图片描述

两种scope在创建op和使用tf.Variable创建变量时有着相同的影响(都会在name前加上scope的前缀),但是当使用tf.get_variable时,name_scope将会被忽略。

import tensorflow as tfwith tf.name_scope('test_scope'):    test1=tf.get_variable('test1',[1],dtype=tf.float32)    test2=tf.Variable(1,name='test2',dtype=tf.float32)    a=tf.add(test1,test2)print(test1.name)  #test1:0print(test2.name)  #test_scope/test2:0print(a.name)      #test_scope/Add:0

如果想要一个tf.get_variable创建的变量可以被其他代码块访问,需要使用variable scope:

import tensorflow as tfwith tf.variable_scope('test_scope'):    test1=tf.get_variable('test1',[1],dtype=tf.float32)    test2=tf.Variable(1,name='test2',dtype=tf.float32)    a=tf.add(test1,test2)print(test1.name)  #test_scope/test1:0print(test2.name)  #test_scope/test2:0print(a.name)      #test_scope/Add:0
import tensorflow as tfwith tf.variable_scope('share'):    share=tf.get_variable('share_variable',[1])with tf.variable_scope('share',reuse=True):    share_test=tf.get_variable('share_variable',[1])    print(share.name)        #share/share_variable:0print(share_test.name)   #share/share_variable:0

转载地址:http://vrvx.baihongyu.com/

你可能感兴趣的文章
Mysql学习总结(26)——MySQL子查询
查看>>
Mysql学习总结(27)——Mysql数据库字符串函数
查看>>
Mysql学习总结(28)——MySQL建表规范与常见问题
查看>>
Mysql学习总结(29)——MySQL中CHAR和VARCHAR
查看>>
Mysql学习总结(2)——Mysql超详细Window安装教程
查看>>
Mysql学习总结(30)——MySQL 索引详解大全
查看>>
Mysql学习总结(31)——MySql使用建议,尽量避免这些问题
查看>>
Mysql学习总结(32)——MySQL分页技术详解
查看>>
Mysql学习总结(33)——阿里云centos配置MySQL主从复制
查看>>
Mysql学习总结(35)——Mysql两千万数据优化及迁移
查看>>
Mysql学习总结(36)——Mysql查询优化
查看>>
Mysql学习总结(37)——Mysql Limit 分页查询优化
查看>>
Mysql学习总结(38)——21条MySql性能优化经验
查看>>
Mysql学习总结(39)——49条MySql语句优化技巧
查看>>
Mysql学习总结(3)——MySql语句大全:创建、授权、查询、修改等
查看>>
Mysql学习总结(40)——MySql之Select用法汇总
查看>>
Mysql学习总结(41)——MySql数据库基本语句再体会
查看>>
Mysql学习总结(42)——MySql常用脚本大全
查看>>
Mysql学习总结(43)——MySQL主从复制详细配置
查看>>
Mysql学习总结(44)——Linux下如何实现mysql数据库每天自动备份定时备份
查看>>