Tensorflow覆盖自定义层中的范围

时间:2019-02-02 17:11:24

标签: tensorflow scope

我正在尝试从tf.keras.layers.Layer继承来在tensorflow中实现一个嘈杂的线性层。除了重用变量外,其他所有东西都工作正常。这似乎是由于范围的问题而引起的:每当我使用超类中的add_weight函数并且已经存在具有相同名称的权重时,它似乎会忽略范围中给定的重用标志,而是创建一个新变量。有趣的是,在类似情况下,它没有像往常一样在变量名末尾添加1,而是在范围名前添加1。

import tensorflow as tf

class NoisyDense(tf.keras.layers.Layer):
    def __init__(self,output_dim):
        self.output_dim=output_dim

        super(NoisyDense, self).__init__()

    def build(self, input_shape):
        self.input_dim = input_shape.as_list()[1]
        self.noisy_kernel = self.add_weight(name='noisy_kernel',shape=  (self.input_dim,self.output_dim))

def noisydense(inputs, units):

    layer = NoisyDense(units)

    return layer.apply(inputs)

inputs = tf.placeholder(tf.float32, shape=(1, 10),name="inputs")



scope="scope"
with tf.variable_scope(scope):
    inputs3 = noisydense(inputs,
           1)
    my_variable = tf.get_variable("my_variable", [1, 2, 3],trainable=True)


with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):
    inputs2 = noisydense(inputs,
           1)
    my_variable = tf.get_variable("my_variable", [1, 2, 3],trainable=True)

tvars = tf.trainable_variables()



init=tf.global_variables_initializer()    
with tf.Session() as sess:
    sess.run(init)
    tvars_vals = sess.run(tvars)

for var, val in zip(tvars, tvars_vals):
    print(var.name, val)

这将导致变量

  scope/noisy_dense/noisy_kernel:0
   scope_1/noisy_dense/noisy_kernel:0
   scope/my_variable:0

被打印。我希望它可以重用嘈杂的内核,而不是像my_variable那样创建第二个内核。

0 个答案:

没有答案
相关问题