Tensorflow教程: tf.Variable() 和tf.get_variable()

七月 上海 | 高性能计算之GPU CUDA培训

7月27-29日 640?wx_fmt=jpeg 三天密集式学习  快速带你入门 阅读全文 >


正文共364个字,预计阅读时间8分钟。


一、简介


tf.Variable()


1tf.Variable(initial_value=None, trainable=True,    collections=None, validate_shape=True
2caching_device=None, name=None, variable_def=None, dtype=None, expected_shape=None
3import_scope=None)


tf.get_variable()


1tf.get_variable(name, shape=None, dtype=None, initializer=None, regularizer=None
2trainable=True, collections=None, caching_device=None, partitioner=None, validate_shape=True
3custom_getter=None)


2、区别


1、使用tf.Variable时,如果检测到命名冲突,系统会自己处理。使用tf.get_variable()时,系统不会处理冲突,而会报错


1import tensorflow as tf
2w_1 = tf.Variable(3,name="w_1")
3w_2 = tf.Variable(1,name="w_1")
4print w_1.name
5print w_2.name
6#输出
7#w_1:0
8#w_1_1:0


1import tensorflow as tf
2
3w_1 = tf.get_variable(name="w_1",initializer=1)
4w_2 = tf.get_variable(name="w_1",initializer=2)
5#错误信息
6#ValueError: Variable w_1 already exists, disallowed. Did
7#you mean to set reuse=True in VarScope?


2、基于这两个函数的特性,当我们需要共享变量的时候,需要使用tf.get_variable()。在其他情况下,这两个的用法是一样的


 1 import tensorflow as tf
2
3 with tf.variable_scope("scope1"):
4 w1 = tf.get_variable("w1", shape=[])
5 w2 = tf.Variable(0.0, name="w2")
6 with tf.variable_scope("scope1", reuse=True):
7 w1_p = tf.get_variable("w1", shape=[])
8 w2_p = tf.Variable(1.0, name="w2")
9
10 print(w1 is w1_p, w2 is w2_p)
11 #输出
12 #True  False


由于tf.Variable() 每次都在创建新对象,所有reuse=True 和它并没有什么关系。对于get_variable(),来说,如果已经创建的变量对象,就把那个对象返回,如果没有创建变量对象的话,就创建一个新的。


3、实例


 1import os
2os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
3
4import tensorflow as tf
5
6x1 = tf.truncated_normal([200100], name='x1')
7x2 = tf.truncated_normal([200100], name='x2')
8
9def two_hidden_layers_1(x):
10assert x.shape.as_list() == [200100]
11w1 = tf.Variable(tf.random_normal([10050]), name='h1_weights')
12b1 = tf.Variable(tf.zeros([50]), name='h1_biases')
13h1 = tf.matmul(x, w1) + b1
14assert h1.shape.as_list() == [20050]
15w2 = tf.Variable(tf.random_normal([5010]), name='h2_weights')
16b2 = tf.Variable(tf.zeros([10]), name='2_biases')
17logits = tf.matmul(h1, w2) + b2
18return logits
19
20def two_hidden_layers_2(x):
21assert x.shape.as_list() == [200100]
22w1 = tf.get_variable('h1_weights', [10050],  initializer=tf.random_normal_initializer())
23b1 = tf.get_variable('h1_biases', [50], initializer=tf.constant_initializer(0.0))
24h1 = tf.matmul(x, w1) + b1
25assert h1.shape.as_list() == [20050]
26w2 = tf.get_variable('h2_weights', [5010], initializer=tf.random_normal_initializer())
27b2 = tf.get_variable('h2_biases', [10], initializer=tf.constant_initializer(0.0))
28logits = tf.matmul(h1, w2) + b2
29return logits
30
31
32def fully_connected(x, output_dim, scope):
33with tf.variable_scope(scope, reuse=tf.AUTO_REUSE) as scope:
34w = tf.get_variable('weights', [x.shape[1], output_dim], initializer=tf.random_normal_initializer())
35b = tf.get_variable('biases', [output_dim], initializer=tf.constant_initializer(0.0))
36return tf.matmul(x, w) + b
37
38def two_hidden_layers_3(x):
39h1 = fully_connected(x, 50'h1')
40h2 = fully_connected(h1, 10'h2')
41return h2
42# with tf.variable_scope('two_layers') as scope:
43#     logits1 = two_hidden_layers_1(x1) 
44#     # scope.reuse_variables()
45#     logits2 = two_hidden_layers_1(x2)
46# 不会报错
47# ---------------
48
49# with tf.variable_scope('two_layers') as scope:
50#     logits1 = two_hidden_layers_2(x1)
51#     # scope.reuse_variables()
52#     logits2 = two_hidden_layers_2(x2)
53# 会报错
54# ---------------
55
56with tf.variable_scope('two_layers'as scope:
57logits1 = two_hidden_layers_3(x1)
58# scope.reuse_variables()
59logits2 = two_hidden_layers_3(x2)
60# 不会报错
61# -------
62writer = tf.summary.FileWriter('./graphs/cool_variables', tf.get_default_graph())
63writer.close()


原文链接:https://www.jianshu.com/p/2061b221cd8f


查阅更为简洁方便的分类文章以及最新的课程、产品信息,请移步至全新呈现的“LeadAI学院官网”:

www.leadai.org


请关注人工智能LeadAI公众号,查看更多专业文章

640?wx_fmt=jpeg

大家都在看

640.png?

LSTM模型在问答系统中的应用

基于TensorFlow的神经网络解决用户流失概览问题

最全常见算法工程师面试题目整理(一)

最全常见算法工程师面试题目整理(二)

TensorFlow从1到2 | 第三章 深度学习革命的开端:卷积神经网络

装饰器 | Python高级编程

今天不如来复习下Python基础

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值