我在尝试理解为什么Keras中ResNet50的实现禁止使用小于32x32x3的图像。
根据他们的实现: https://github.com/keras-team/keras-applications/blob/master/keras_applications/resnet50.py,用于捕获这一限制的函数是_obtain_input_shape
为了解决这个问题,我基于他们的代码进行了自己的实现,并删除了限制最小尺寸的代码。在我的实现中,我还增加了使用预训练模型处理超过三个通道的可能,通过复制第一层conv1的RGB权重来实现。
def ResNet50(load_weights=True, input_shape=None, pooling=None, classes=1000): img_input = Input(shape=input_shape, name='tuned_input') x = ZeroPadding2D(padding=(3, 3), name='conv1_pad')(img_input) # Stage 1 (conv1_x) x = Conv2D(64, (7, 7), strides=(2, 2), padding='valid', kernel_initializer=KERNEL_INIT, name='tuned_conv1')(x) x = BatchNormalization(axis=CHANNEL_AXIS, name='bn_conv1')(x) x = Activation('relu')(x) x = ZeroPadding2D(padding=(1, 1), name='pool1_pad')(x) x = MaxPooling2D((3, 3), strides=(2, 2))(x) # Stage 2 (conv2_x) x = _convolution_block(x, 3, [64, 64, 256], stage=2, block='a', strides=(1, 1)) for block in ['b', 'c']: x = _identity_block(x, 3, [64, 64, 256], stage=2, block=block) # Stage 3 (conv3_x) x = _convolution_block(x, 3, [128, 128, 512], stage=3, block='a') for block in ['b', 'c', 'd']: x = _identity_block(x, 3, [128, 128, 512], stage=3, block=block) # Stage 4 (conv4_x) x = _convolution_block(x, 3, [256, 256, 1024], stage=4, block='a') for block in ['b', 'c', 'd', 'e', 'f']: x = _identity_block(x, 3, [256, 256, 1024], stage=4, block=block) # Stage 5 (conv5_x) x = _convolution_block(x, 3, [512, 512, 2048], stage=5, block='a') for block in ['b', 'c']: x = _identity_block(x, 3, [512, 512, 2048], stage=5, block=block) # Condition on the last layer if pooling == 'avg': x = layers.GlobalAveragePooling2D()(x) elif pooling == 'max': x = layers.GlobalMaxPooling2D()(x) inputs = img_input # Create model. model = models.Model(inputs, x, name='resnet50') if load_weights: weights_path = get_file( 'resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5', WEIGHTS_PATH_NO_TOP, cache_subdir='models', md5_hash='a268eb855778b3df3c7506639542a6af') model.load_weights(weights_path, by_name=True) f = h5py.File(weights_path, 'r') d = f['conv1'] # Used to work with more than 3 channels with pre-trained model if input_shape[2] % 3 == 0: model.get_layer('tuned_conv1').set_weights([d['conv1_W_1:0'][:].repeat(input_shape[2] / 3, axis=2), d['conv1_b_1:0']]) else: m = (3 * int(input_shape[2] / 3)) + 3 model.get_layer('tuned_conv1').set_weights( [d['conv1_W_1:0'][:].repeat(m, axis=2)[:, :, 0:input_shape[2], :], d['conv1_b_1:0']]) return model
我用10x10x3的图像运行了我的实现,看起来是可以工作的。因此我不理解他们为什么设定了这个最小界限。
他们没有提供关于这个选择的任何信息。我还查看了原始论文,也没有发现关于最小输入形状的任何限制。我猜测这个界限是有原因的,但我不清楚是什么原因。
因此我想知道为什么在ResNet的实现中设置了这样的限制。
回答:
ResNet50有5个降采样阶段,包括2×2的最大池化和步长为2像素的步进卷积。这意味着最小输入尺寸是2^5 = 32,这个值也是感受野的大小。
使用小于32×32的图像没有太大意义,因为这样降采样不起作用,这将改变网络的行为。对于如此小的图像,最好使用其他具有较少降采样(如DenseNet)或较浅的网络。