Tensorflow学习之变量使用及共享变量

1.变量操作基础:

 1.1 创建:

1.1.1使用Variable()来创建一个变量

eg:weights=tf.Variable(tf.random_normal([784,200],stddev=0.35),name='weights')

1.1.2使用tf.get_variable():这一函数必须指定变量名

eg: my_variable=tf.get_variable("my_variable,[1,2,3]) 参数1为name,参数2为shape为给定dtype和初始化方式时默认为tf.float32和tf.glorot_uniform_initializer 也可自己设置

eg:variable-tf.get_variable("other_variable",dtype=tf.int32,initializer=tf.constant([23,42]))

由initializer同时给出shape和初始化方式

1.1.3device配置:和其他tf中的操作一样,可以将变量配置在特定的device上:

eg:with tf. device("/device :GPU:1"):

    v=tf.get_variable("v",[1])

对于分布式设置,变量的device_placement非常重要,使用tf.train.replica_device_setter,可以自动将变量配置在参数服务器上

这里不做详解,具体将在分布式章学习

1.2 初始化initialize variables

  全局初始化:session.run(tf.global_variables_initializer())该函数未指定初始化顺序,若某一变量初始化依赖于其他变量,则可能出错,最好在创建该变量时使用variable.initialized_value()而非variable

eg:v=tf.get_variable("v",shape=(),initializer=tf.zeros_initializer())

      w=tf.get_variable("w",initializer=v.initialized_value()+1)

  单变量初始化:session.run(my_variable.initializer)

2共享变量:通过tf.variable_scope()创建命名空间进行共

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)

当多次调用规格一样的conv_relu时会出错

eg:input1=tf.random_normal([1,10,10,32])

      input2=tf.random_normal([1,10,10,32])

      x=conv_relu(input1,kernel_shape=[5,5,32,32],bias_shape=[32])

      x=conv_relu(x,kernel_shape=[5,5,32,32],bias_shape=[32])

第二次使用将会出错,因为系统不知道应该创建新的weights,biases还是使用已经存在的,因为他们的名字一样

使用tf.variable_scope()创建不同的名字空间

def my_image_filter(input_images):

        with tf.variable_scpoe("conv1"): #此处创建的变量被命名为conv1/weights

                relu1=conv_relu(input_iamges,kernel_shape=[5,5,32,32],bias_shape=[32])

       with tf.variable_scpoe("conv2"):#此处创建的变量被命名为conv2/weights

                relu2=conv_relu(relu1,kernel_shape=[5,5,32,32],bias_shape=[32])

                   return relu2

若想共享已存在的变量可以使用下面操作

1.with tf.variable_scope("model"):

output1=my_image_filter(input1)

with tf.variable_scope("model",reuse=True):

output2=my_image_filter(input2)   #此处使用的参数依然是之前创建的

2.with tf.variable_scope("model")  as scope:

            output1=my_image_filter(input1)

             scope.resue_variables()

            output2=my_image_filter(input2)

 3第一种方法的修改版

with tf.variable_scope("model") as scope:

output1=my_image_filter(input1)

with tf.variable_scope(scope,reuse=True):

output2=my_image_filter(input2)   #此处使用的参数依然是之前创建的


猜你喜欢

转载自blog.csdn.net/qq_40103460/article/details/80556133