tensorflow--变量管理

一、变量管理简介

       如可以通过一个函数来实现神经网络前向传播,def inference(input_tensor, avg_class, weights1, biases1, weights2, biases2),调用这个函数需要传递神经网络的所有参数。然而,当神经网络的结构更加复杂、参数更多时,就需要一个更好的方法传递和管理神经网络中的参数。

      Tensorflow提供了通过变量名称来创建和获取一个变量的机制。通过这个机制,在不同的函数中可以直接通过变量的名字来使用变量,而不需要将变量通过参数的形式到处传递。Tensorflow中通过名称获取变量的机制主要通过tf.get_variable()和tf.variable_scope()函数实现。

      通过tf.Variable()函数可以创建一个变量。除该函数外,Tensorflow还提供了tf.get_variable()函数来创建或者获取变量。当tf.get_variable()用于创建变量时,它和tf.Variable()的功能是基本等价的。以下三种定义方式:

方式一:

v1 = tf.get_variable("v", shape=[1], initializer=tf.constant_initializer([1.0]))
v2 = tf.Variable(tf.constant([1.0], shape=[1]), name="v")
print(v1)
print(v2)

输出:

<tf.Variable 'v:0' shape=(1,) dtype=float32_ref>
<tf.Variable 'v_1:0' shape=(1,) dtype=float32_ref>

方式二:

v1 = tf.Variable(tf.constant([1.0], shape=[1]), name="v")
#v1 = tf.get_variable(name="v", shape=[1], initializer=tf.constant_initializer([2.0]))
v2 = tf.get_variable(name="v", shape=[1], initializer=tf.constant_initializer([1.0]))
print(v1)
print(v2)

输出:

<tf.Variable 'v:0' shape=(1,) dtype=float32_ref>
<tf.Variable 'v_1:0' shape=(1,) dtype=float32_ref>

方式三:

v1 = tf.get_variable(name="v", shape=[1], initializer=tf.constant_initializer([2.0]))
print(v1)
v2 = tf.get_variable(name="v", shape=[1], initializer=tf.constant_initializer([1.0]))
print(v2)

输出:

<tf.Variable 'v:0' shape=(1,) dtype=float32_ref>
Traceback (most recent call last):

第一个可以变量可以创建成功,第二个变量创建失败。

第四种情况:

v1 = tf.Variable(tf.constant([1.0], shape=[1]), name="v")
print(v1)
v2 = tf.get_variable(name="v", shape=[1], initializer=tf.constant_initializer([1.0]))
print(v2)
v3 = tf.get_variable(name="v", shape=[1], initializer=tf.constant_initializer([1.0]))
print(v3)

输出:

<tf.Variable 'v:0' shape=(1,) dtype=float32_ref>
<tf.Variable 'v_1:0' shape=(1,) dtype=float32_ref>
Traceback (most recent call last):

前两个创建成功,最后一个失败


通过上述代码可以看出两者创建变量的过程基本上是一样的。但两者也有区别,其中最大的区别在于指定变量名称的参数。对于tf.Variable函数,变量名称是一个可选的参数,通过name=“v”形式给出,但对于tf.get_variable()函数,变量名称是一个必填的参数。它会根据这个名字去创建或者获取变量。在上面的实例中,tf.get_variable()函数首先会试图去创建一个名字为v的参数,如果变量中有同名的变量但这个变量是通过tf.Variable()创建的,则可以创建一个名为v_1的变量,但如果同名的变量是通过tf.get_variable()创建的,则会创建失败,程序会报错,因为有通过tf.get_variable创建的同名变量。这是为了避免无意识的变量复用造成错误。如在定义神经网络参数时,第一层网络权值叫做weights,第二层依然叫weights,这会触发变量重用错误,否则两个网络公用一个权重会出现难以发现的错误。

      如果通过tf.get_variable()获取一个已经创建的变量,需要通过tf.variable_scope函数来生成一个上下文管理器,并明确指定在这个变量管理器中tf.get_variable()将直接获取已经生成的变量。实例如下:

v1 = tf.Variable(tf.constant([1.0], shape=[1]), name="v")
print(v1)
v2 = tf.get_variable(name="v", shape=[1], initializer=tf.constant_initializer([1.0]))
print(v2)
with tf.variable_scope("",reuse=True):
    v3 = tf.get_variable(name="v", shape=[1], initializer=tf.constant_initializer([1.0]))
    print(v3==v2)

    v4 = tf.get_variable(name="v_1", shape=[1], initializer=tf.constant_initializer([4.0]))
    print(v4)

输出:

<tf.Variable 'v:0' shape=(1,) dtype=float32_ref>
<tf.Variable 'v_1:0' shape=(1,) dtype=float32_ref>
True

Traceback (most recent call last):

上面实例说明,通过tf.variable_scope函数可以控制tf.get_variable函数的语义。当tf.variable_scope函数使用参数reuse=True生成上下文管理器时,这个上下文管理器内所有的tf.get_variable函数会直接获取已经创建的变量。如果变量不存在,则tf.get_variable()函数将报错。相反,如果tf.variable_scope函数使用参数reuse=None或者reuse=False创建上下文管理器,tf.get_variable操作将创建新的变量,如果同名的变量已经存在,则会报错。tf.variable_scope函数是可以嵌套的。下面实例说明当该函数嵌套时,reuse参数的取值是如何确定的。实例如下:

with tf.variable_scope("root"):
    print(tf.get_variable_scope())
    print(tf.get_variable_scope().reuse)
    
    with tf.variable_scope("foo", reuse=True):
        print(tf.get_variable_scope().reuse)
        
        with tf.variable_scope("bar"):
            print(tf.get_variable_scope().reuse)
    print(tf.get_variable_scope().reuse)

输出:

False
True
True
False


       tf.variable_scope函数会生成一个tensorflow的变量名称空间,在该空间内创建的变量都会带上这个名称空间名作为前缀。所以,tf.variable_scope函数除了可以控制tf.get_variable执行的功能外,这个函数也提供了一个管理变量名称空间的功能。实例如下:

v1 = tf.get_variable("v", [1])
print(v1.name)
with tf.variable_scope("foo"):
    v2 = tf.get_variable("v",[1])
    print(v2.name)

with tf.variable_scope("foo"):
    with tf.variable_scope("bar"):
        v3 = tf.get_variable("v",[1])
        print(v3.name)
    
    v4 = tf.get_variable("v1",[1])
    print(v4.name)
#创建一个名称为空的空间, 设置reuse=True
with tf.variable_scope("",reuse=True):
    v5 = tf.get_variable("foo/bar/v", [1])
    print(v5==v3)
    v6 = tf.get_variable("foo/v1", [1])
    print(v6==v4)

输出:

v:0
foo/v:0
foo/bar/v:0
foo/v1:0
True
True


二、利用get_variable构建神经网络

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
INPUT_NODE = 784
OUTPUT_NODE = 10
LAYER1_NODE = 500
BATCH_SIZE = 100

LEARNING_RAGE_BASE = 0.8
LEARNING_RAGE_DECAY = 0.99
REGULARIZATION_RATE = 0.0001
TRAINING_STEPS = 3000
MOVING_AVERAGE_DECAY = 0.99
def inference(input_tensor, avg_class, reuse=False):
    with tf.variable_scope("layer1", reuse=reuse):
        weights = tf.get_variable("weights", [INPUT_NODE, LAYER1_NODE],
                                  initializer=tf.truncated_normal_initializer(stddev=0.1))
        biases = tf.get_variable("biases", [LAYER1_NODE],
                                 initializer=tf.constant_initializer(0.0))
        if avg_class == None:
            layer1 = tf.nn.relu(tf.matmul(input_tensor, weights)+biases)
        else:
            layer1 = tf.nn.relu(tf.matmul(input_tensor, avg_class.average(weights))+avg_class.average(biases))
    
    with tf.variable_scope("layer2", reuse=reuse):
        weights = tf.get_variable("weights", [LAYER1_NODE, OUTPUT_NODE],
                                  initializer=tf.truncated_normal_initializer(stddev=0.1))
        biases = tf.get_variable("biases", [OUTPUT_NODE],
                                 initializer=tf.constant_initializer(0.0))
        if avg_class == None:
            layer2 = tf.matmul(layer1, weights)+biases
        else:
            layer2 = tf.matmul(layer1, avg_class.average(weights))+avg_class.average(biases)
    
    return layer2

def train(mnist):
    x = tf.placeholder(tf.float32, [None, INPUT_NODE], name='x-input')
    y_=tf.placeholder(tf.float32, [None, OUTPUT_NODE], name='y-input')
    #weights1 = tf.Variable(tf.truncated_normal([INPUT_NODE, LAYER1_NODE], stddev=0.1))
    #biases1 = tf.Variable(tf.constant(0.1, shape=[LAYER1_NODE]))
    
    #weights2 = tf.Variable(tf.truncated_normal([LAYER1_NODE, OUTPUT_NODE], stddev=0.1))
    #biases2 = tf.Variable(tf.constant(0.1, shape=[OUTPUT_NODE]))
    
    #y = inference(x, None, weights1, biases1, weights2, biases2)
    y1 = inference(x, None)
    y = inference(x, None, reuse=True)
    global_step = tf.Variable(0, trainable=False)
    
    variable_average = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)
    variables_averages_op = variable_average.apply(tf.trainable_variables())
    average_y = inference(x, variable_average, reuse=True)
    print(y.get_shape())
    print(y.get_shape())
    lo = tf.argmax(y_, 1)
    print(lo.get_shape())
    cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y, labels =tf.argmax(y_, 1))
    cross_entropy_mean = tf.reduce_mean(cross_entropy)
    
    #计算L2正则化损失函数
    regularizer = tf.contrib.layers.l2_regularizer(REGULARIZATION_RATE)
    #regularization = regularizer(weights1)+regularizer(weights2)
    #loss = cross_entropy_mean + regularization
    print(cross_entropy.get_shape())
    loss = cross_entropy_mean
    print(cross_entropy_mean.get_shape())
    
    learning_rate = tf.train.exponential_decay(LEARNING_RAGE_BASE, global_step,
                                               mnist.train.num_examples/BATCH_SIZE, LEARNING_RAGE_DECAY)
    train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)
    #在训练神经网络模型时,每过一遍数据既需要通过反向传播来更新神经网络中的参数,又要更新每一个参数的滑动平均值
    #为了一次完成多个操作,Tensorflow提供了tf.control_dependencies和tf.group两种机制,两者等价
    #train_op = tf.group(train_step, variables_averages_op)
    with tf.control_dependencies([train_step,variables_averages_op]):
        train_op = tf.no_op(name='train')
    correct_prediction = tf.equal(tf.argmax(average_y, 1), tf.argmax(y_, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    with tf.Session() as sess:
        tf.global_variables_initializer().run()
        #准备验证数据,在神经网络训练过程中会通过验证数据来大致判断停止条件和判断训练的效果
        validate_feed = {x: mnist.validation.images, y_:mnist.validation.labels}
        test_feed = {x:mnist.test.images, y_:mnist.test.labels}
        for i in range(TRAINING_STEPS):
            if i%200 == 0:
                validate_acc = sess.run(accuracy, feed_dict=validate_feed)
                print("After %d training steps, validation accuracy using average model is %g" % (i,validate_acc))
            xs, ys = mnist.train.next_batch(BATCH_SIZE)
            sess.run(train_op, feed_dict={x:xs, y_:ys})
            #print("global_step is %d" % sess.run(global_step))
        
        test_acc = sess.run(accuracy, feed_dict=test_feed)
        print("after %d training steps, test accuracy is %g" % (TRAINING_STEPS, test_acc))
def main(argv=None):
    mnist = input_data.read_data_sets("/tmp/data", one_hot=True)
    train(mnist)
    #xs, ys = mnist.train.next_batch(10)
    #print(ys)

if __name__=="__main__":
    tf.app.run()


三、个人理解

tensorflow使用首先是构建一个计算图,无论在哪里创建的变量,当创建成功后,该变量就存在与图中了,变量的名字会根据你指定的名字进行设定,当这个名字已经存在了,则会按照同名进行编号,加入_n,对于通过tf.get_variable()创建同名变量则会报错,但是却可以使用同一个变量,这需要通过tf.variable_scope("", reuse=True)来设置。但是,通过tf.get_variable()无法找到tf.Variable创建的变量,即使使用相同的名字。如果是通过tf.Variable创建的变量,如果想要重用它,就需要将其引用赋给一个变量,如v1 = tf.Variable(),随后将v1传递到不同的位置进行使用,对于tf.get_variable()需要重用时,并不需要传递,可以直接在获取变量的名字即可。


实例如下:

def get_var1():
    v1 = tf.Variable(tf.constant([1.0]),name = "v")
    #v1 = tf.get_variable('v', shape=[1], initializer=tf.constant_initializer([1.0]))
    print(v1)
def get_var2():
    #v2 = tf.Variable(tf.constant([2.0]), name = 'v')
    v2 = tf.get_variable('v1',shape=[1], initializer=tf.constant_initializer([2.0]))
    print(v2)
def main():
    get_var1()
    get_var2()
    #v3 = tf.get_variable("v", shape=[1], initializer=tf.constant_initializer([3.0]))
    #print(v3)
    
    with tf.variable_scope("", reuse=True):
        v5 = tf.get_variable("v", shape=[1], initializer=tf.constant_initializer([5.0]))
        print(v5)

if __name__=="__main__":
    main()

输出:

<tf.Variable 'v:0' shape=(1,) dtype=float32_ref>
<tf.Variable 'v1:0' shape=(1,) dtype=float32_ref>
Traceback (most recent call last):












  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值