117、TensorFlow变量共享

# sharing variables
# Tensorflow supports two ways of sharing variables
# 1、Explicitly passing tf.Variable objects around
# 2、Implicitly wrapping tf.Variable objects within tf.variable_scope objects
# For example , let's write a function to create a convolutional / relu layer
import tensorflow as tf
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))
    # stride表示步长 , weight表示卷积核 , padding 表示卷积核是否可以停留在图像的边缘
    conv = tf.nn.conv2d(input, weights, strides=[1, 1, 1, 1], padding='SAME')
    return tf.nn.relu(conv + biases)


# 这个函数使用了简写的weights和biases 
# 在声明的时候是有帮助的,
# 但是在真实的模型中,我们更想要以下的卷积层,重复调用这个函数是不会起作用的
input1 = tf.random_normal([1, 10, 10, 32])
input2 = tf.random_normal([1, 20, 20, 32])
x = conv_relu(input1, kernel_shape=[5, 5, 32, 32], bias_shape=32)
# This fails 不支持重复调用 , 因为想要的行为还不清楚
# 是创建新的变量还是使用现有的变量
# x = conv_relu(x, kernel_shape=[5, 5, 32, 32], bias_shape=[32]) 

 

posted @ 2018-02-17 10:59  香港胖仔  阅读(180)  评论(0编辑  收藏  举报