Keras选择随机分支

时间:2018-01-21 23:16:09

标签: deep-learning keras

我想在训练和执行期间在网络的两个分支之间随机选择。我希望能够做出许多随机选择。

我的动机是在整个系统收敛后探索网络中可交换部分之间的相似性。最后,我希望我的系统看起来像这样: enter image description here

我尝试过这种方法,但似乎K.switch语句的条件存在问题:

# can ignore details of this function
def make_first_half(input):
    m = Conv2D(16,
               kernel_size=(3, 3),
               activation='relu',
               input_shape=input_shape)(input)
    m = Conv2D(32, (3, 3), activation='relu')(m)
    m = MaxPooling2D(pool_size=(2, 2))(m)
    m = Flatten()(m)
    return m

# can ignore details of this function
def make_second_half(input):
    m = Dense(32, activation='relu')(input)
    m = Dense(num_classes, activation='softmax')(m)
    return m


input = Input(shape=input_shape)

a1 = make_first_half(input)
a2 = make_first_half(input)

a = K.switch(
    lambda x: 1 == random.randint(0, 1),
    a1, a2)

prediction = make_second_half(a)

我想我明白了什么是错的:K.switch的条件应该是张量而不是返回布尔值的函数。但是,我不确定如何在每次达到这一点时制作一个随机的张量。也就是说,我不想在一开始就随机选择路径,然后每次都走这条路,而忽略另一条路径。

我也更喜欢只运行一个而不是多个训练课程(即只有一个Model语句,一个compile语句和一个fit语句。

我正在使用TensorFlow后端。

我完全有可能在想错。请解释我如何实现这种随机分支。

0 个答案:

没有答案