TensorFlow reuse variable with tf.layers.conv2d

后端 未结 1 1371
悲哀的现实
悲哀的现实 2020-12-14 04:09

I am trying to make 2 conv layers share the same weights, however, it seems the API does not work.

import tensorflow as tf

x = tf.random_normal(shape=[10,          


        
相关标签:
1条回答
  • 2020-12-14 04:30

    In the code you wrote, variables do get reused between the two convolution layers. Try this :

    import tensorflow as tf
    
    x = tf.random_normal(shape=[10, 32, 32, 3])
    
    conv1 = tf.layers.conv2d(x, 3, [2, 2], padding='SAME', reuse=None, name='conv')
    
    conv2 = tf.layers.conv2d(x, 3, [2, 2], padding='SAME', reuse=True, name='conv')
    
    print([x.name for x in tf.global_variables()])
    
    # prints
    # [u'conv/kernel:0', u'conv/bias:0']
    

    Note that only one weight and one bias tensor has been created. Even though they share the weights, the layers do not share the actual computation. Hence you see the two different names for the operations.

    0 讨论(0)
提交回复
热议问题