在 Keras 中使用 Tensorflow 层

Using Tensorflow Layers in Keras

我一直在尝试使用池化层 tf.nn.fractional_max_pool 在 Keras 中构建顺序模型。我知道我可以尝试在 Keras 中制作我自己的自定义层,但我想看看我是否可以使用 Tensorflow 中已有的层。对于以下代码片段:

p_ratio=[1.0, 1.44, 1.44, 1.0]

model = Sequential()
model.add(ZeroPadding2D((2,2), input_shape=(1, 48, 48)))
model.add(Conv2D(320, (3, 3), activation=PReLU()))
model.add(ZeroPadding2D((1,1)))
model.add(Conv2D(320, (3, 3), activation=PReLU()))
model.add(InputLayer(input_tensor=tf.nn.fractional_max_pool(model.layers[3].output, p_ratio)))

我明白了 error。我已经用 Input 而不是 InputLayer 和 Keras Functional API 尝试了一些其他的东西,但到目前为止没有运气。

开始使用了。为了将来参考,这就是您需要实现它的方式。由于tf.nn.fractional_max_pool returns 3个张量,你只需要得到第一个:

model.add(InputLayer(input_tensor=tf.nn.fractional_max_pool(model.layers[3].output, p_ratio)[0]))

或使用 Lambda 层:

def frac_max_pool(x):
    return tf.nn.fractional_max_pool(x,p_ratio)[0]

模型实现为:

model.add(Lambda(frac_max_pool))