如何在Keras / Tensorflow中模仿Caffe的最大池化行为?

时间:2019-01-28 13:58:16

标签: python tensorflow keras caffe

如果我在Keras中拥有MaxPooling2D的{​​{1}}层。 应用于pool_size=(2,2), strides=(2,2)输入要素图,将导致3x3空间输出大小。 Caffe(1x1)中的相同操作将导致输出大小为pool: MAX; kernel_size: 2; stride: 2

众所周知,Caffe和Tensorflow / Keras behave differently when applying max pooling

有一种2D卷积的解决方法:要避免使用asymmetric padding of Conv2D in TensorFlow,可以在其前面加上explicit zero padding,并将填充类型从2x2更改为same

是否有类似的解决方法来更改Keras中的valid行为,使其性能类似于Caffe?更准确地说,我正在寻找MaxPooling2D周围的包装,该包装应等于Caffe中的最大合并2D 2x2。

也许在MaxPooling2D输入的左边和顶部填充一个像素?

我正在使用TensorFlow中的MaxPooling2D

1 个答案:

答案 0 :(得分:1)

好,我找到了答案,让我保存在这里。必须用零填充输入的底部/右侧。这是最小的工作示例:

import os
import math
import numpy as np

import tensorflow as tf
from tensorflow.python.keras.models import Model
from tensorflow.python.keras.layers import Input, MaxPool2D
from tensorflow.python.keras import backend as K

import caffe
from caffe.model_libs import P
from caffe import layers as L
from caffe.proto import caffe_pb2


def MaxPooling2DWrapper(pool_size=(2, 2), strides=None, padding='valid', data_format=None, **kwargs):

    def padded_pooling(inputs):
        _, h, w, _ = K.int_shape(inputs)
        interm_input = inputs
        if h % 2 != 0 or w % 2 != 0:
            interm_input = tf.keras.layers.Lambda(lambda x: tf.pad(inputs, [[0, 0], [0, 1], [0, 1], [0, 0]]),
                                                  name='input_pad')(inputs)
        return MaxPool2D(pool_size, strides, padding, data_format, **kwargs)(interm_input)

    return padded_pooling


def build_caffe_model(h, w):
    caffe_spec = caffe.NetSpec()

    pool_config = {                                                                                                                                                                                                                                                   
        'pool': P.Pooling.MAX,                                                                                                                                                                                                                                        
        'kernel_size': 2,                                                                                                                                                                                                                                             
        'stride': 2                                                                                                                                                                                                                                                   
    }                                                                                                                                                                                                                                                                 

    caffe_spec['input'] = L.Input(shape=caffe_pb2.BlobShape(dim=(1, 1, h, w)))                                                                                                                                                                                        
    caffe_spec['max_pool'] = L.Pooling(caffe_spec['input'], **pool_config)                                                                                                                                                                                            

    proto = str(caffe_spec.to_proto())                                                                                                                                                                                                                                
    with open('deploy.prototxt', 'w') as f:                                                                                                                                                                                                                           
        f.write(proto)                                                                                                                                                                                                                                                
    net = caffe.Net('deploy.prototxt', caffe.TEST)                                                                                                                                                                                                                    

    return net                                                                                                                                                                                                                                                        


def build_keras_model(h, w):                                                                                                                                                                                                                                          
    inputs = Input(shape=(h, w, 1))                                                                                                                                                                                                                                   

    maxpool = MaxPooling2DWrapper()(inputs)                                                                                                                                                                                                                           
    return Model(inputs, maxpool)                                                                                                                                                                                                                                     


def main():                                                                                                                                                                                                                                                           
    caffe.set_mode_cpu()                                                                                                                                                                                                                                              
    os.environ['GLOG_minloglevel'] = '2'                                                                                                                                                                                                                              
    h = 3                                                                                                                                                                                                                                                             
    w = 3                                                                                                                                                                                                                                                             
    size_input = h * w                                                                                                                                                                                                                                                

    caffe_net = build_caffe_model(h, w)                                                                                                                                                                                                                               
    keras_model = build_keras_model(h, w)                                                                                                                                                                                                                             
    keras_model.summary()                                                                                                                                                                                                                                             

    keras_out = keras_model.predict(np.arange(size_input).reshape(1, h, w, 1))
    caffe_net.blobs['input'].data[...] = np.arange(size_input).reshape(1, 1, h, w)
    caffe_out = caffe_net.forward()['max_pool']

    print('Input:')
    print(np.arange(size_input).reshape(h, w))

    print('Caffe result:')
    print(np.squeeze(caffe_out))

    print('Keras result:')
    print(np.squeeze(keras_out))


if __name__ == '__main__':
    main()

包装器仅在需要时才添加填充。这段代码的输出:

Layer (type)                 Output Shape              Param #   
=================================================================
input_1 (InputLayer)         (None, 3, 3, 1)           0         
_________________________________________________________________
input_pad (Lambda)           (None, 4, 4, 1)           0         
_________________________________________________________________
max_pooling2d (MaxPooling2D) (None, 2, 2, 1)           0         
=================================================================


Input:
[[0 1 2]
 [3 4 5]
 [6 7 8]]
Caffe result:
[[4. 5.]
 [7. 8.]]
Keras result:
[[4. 5.]
 [7. 8.]]