ValueError: Inputs have incompatible shapes. Received shapes (20, 20, 16) and (22, 22, 16)

ValueError: Inputs have incompatible shapes. Received shapes (20, 20, 16) and (22, 22, 16)

我尝试用我在一篇文章中看到的 Xception 构建一个版本的 ResNet 以供学习。

这是目前的模型(只有第一个块和跳过层):

input= Input(shape=(48,48,1))
L1 = Conv2D(filters=8, kernel_size=(3,3), strides=(1,1), activation='relu')(input)
bn = BN()(L1)

L2 = Conv2D(filters=8, kernel_size=(3,3), strides=(1,1), activation='relu')(bn)
bn = BN()(L2)


# First Depthwise, BN = BatchNormalization, SC2D = SeparableConv2D
L3 = SC2D(filters=16, kernel_size=(1,1),activation='relu')(bn)
L3 = BN()(L3)

L3 = SC2D(filters=16, kernel_size=(3,3),activation='relu')(L3)
L3 = BN()(L3)

L3 = SC2D(filters=16, kernel_size=(1,1),activation='relu')(L3)
L3 = BN()(L3)

L3 = MaxPooling2D(pool_size=(3,3), strides=(2,2))(L3)

# skipping layer
skip = Conv2D(filters=16, kernel_size=(1,1), strides=(2,2), activation='relu')(bn)
skip = BN()(skip)
print('skip2:',skip.shape)

sum1 = Add()([L3,skip])

model = Model(inputs=input, outputs=sum1, name='test')

当我 运行 我得到:

ValueError: Inputs have incompatible shapes. Received shapes (20, 20, 16) and (22, 22, 16)

这是我尝试做的事情的图片:

如你所见,我复制了1对1的方案,但出现了错误。

所以我的问题是:如何匹配形状,为什么这不起作用?

您可能忘记设置 padding=same。默认值为 valid。这是一个工作示例:

import tensorflow as tf

input= tf.keras.layers.Input(shape=(48,48,1))
L1 = tf.keras.layers.Conv2D(filters=8, kernel_size=(3,3), strides=(1,1), activation='relu', padding='same')(input)
bn = tf.keras.layers.BatchNormalization()(L1)

L2 = tf.keras.layers.Conv2D(filters=8, kernel_size=(3,3), strides=(1, 1), activation='relu', padding='same')(bn)
bn = tf.keras.layers.BatchNormalization()(L2)

L3 = tf.keras.layers.SeparableConv2D(filters=16, kernel_size=(1,1),activation='relu', padding='same')(bn)
L3 = tf.keras.layers.BatchNormalization()(L3)

L3 = tf.keras.layers.SeparableConv2D(filters=16, kernel_size=(3,3),activation='relu', padding='same')(L3)
L3 = tf.keras.layers.BatchNormalization()(L3)

L3 = tf.keras.layers.SeparableConv2D(filters=16, kernel_size=(1,1),activation='relu', padding='same')(L3)
L3 = tf.keras.layers.BatchNormalization()(L3)

L3 = tf.keras.layers.MaxPooling2D(pool_size=(3,3), strides=(2,2), padding='same')(L3)

# skipping layer
skip = tf.keras.layers.Conv2D(filters=16, kernel_size=(1,1), strides=(2,2), activation='relu', padding='same')(bn)
skip = tf.keras.layers.BatchNormalization()(skip)
sum1 = tf.keras.layers.Add()([L3,skip])

model = tf.keras.Model(inputs=input, outputs=sum1, name='test')