简体   繁体   English

tensorflow model 中的随机 select 层

[英]Randomly select layer in tensorflow model

I want to use different layers with specific probabilities in my network.我想在我的网络中使用具有特定概率的不同层。 Layers are the following classes.层是以下类。

class plus1(keras.layers.Layer):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
    def call(self, X):
        return X + 1    
    def compute_output_shape(self, batch_input_shape):
        return batch_input_shape

class plus2(keras.layers.Layer):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
    def call(self, X):
        return X + 2
    def compute_output_shape(self, batch_input_shape):
        return batch_input_shape

class plus3(keras.layers.Layer):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
    def call(self, X):
        return X + 3
    def compute_output_shape(self, batch_input_shape):
        return batch_input_shape

And the network is like below.网络如下图。

def f1():
    return plus1()
def f2():
    return plus2()
def f3():
    return plus3()

def simple_model(input_num):
    input_layer = Input(input_num)
    rand = tf.random.uniform((1,), minval=0, maxval=3, dtype=tf.int32)
    r = tf.switch_case(rand[0], branch_fns={0: f1, 1: f2, 2: f3})
    res = r(input_layer)
    model = Model(inputs=input_layer, outputs=res)
    return model

model = simple_model([1,])

Each time I run the code below, I get the same output, but I expected different ones.每次我运行下面的代码时,我都会得到相同的 output,但我预计会有不同的。 Is there any way to implement this?有什么方法可以实现吗?

model.predict([1])
>>> array([[4.]], dtype=float32)

It was the same problem I was facing and I found no solution.这是我面临的同样问题,但我没有找到解决方案。 So I implemented distinct networks and then randomly selected from their output.所以我实现了不同的网络,然后从他们的 output 中随机选择。

I've been dealing with the same issue: I have a list of layers from which I need to select randomly on every iteration.我一直在处理同样的问题:我有一个层列表,我需要在每次迭代时随机从其中 select 。 tf.switch_case() gave me the same problem you describe. tf.switch_case()给了我你描述的同样的问题。

For whatever reason, and I don't have enough background depth to tell you why (it's entirely plausible that my tf.switch_case implementation was buggy in an unrelated way), this code worked for me:无论出于何种原因,我没有足够的背景深度来告诉你为什么(我的tf.switch_case实现完全有可能以一种不相关的方式出现错误),这段代码对我有用:

def random_layer(layers, image_tensor):
"""
Selects and executes a random layer chosen from a list
"""
to_use = tf.random.uniform(shape=[], maxval=len(layers), dtype=tf.int32)
out = image_tensor

for i, layer in enumerate(layers):
    # out is either image_tensor or the actual output, *but*
    # since we can't break this loop, when it matches it will become the actual output
    # and any further calls will return that value
    
    def _match():
        # tf.print("using {}".format(layer))
        return layer(out, training=True)
    out = tf.cond(to_use==i, _match, lambda: out)
    
return out 

(Note that I'm using a local function just so I can verify the randomness.) And I pass in: (请注意,我使用的是本地 function 只是为了验证随机性。)然后我传入:

NOISE_LAYERS = [tf.keras.layers.GaussianNoise(stddev=.1),
               tf.keras.layers.GaussianNoise(stddev=.2),
               tf.keras.layers.GaussianNoise(stddev=.3),
               tf.keras.layers.GaussianNoise(stddev=.4)]

(This is part of dataset preparation in which I want images to contain varying amounts of noise.) (这是数据集准备的一部分,我希望图像包含不同数量的噪声。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM