keras ValueError:输入的形状不兼容,收到的形状为(20,20,16)和(22,22,16)

guz6ccqo  于 2023-03-23  发布在  其他
关注(0)|答案(1)|浏览(242)

我尝试用我在一篇文章中看到的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)

以下是我尝试做的事情的图像:

正如你所看到的,我复制了一个一个的方案,但得到了错误。
所以我的问题是:如何匹配形状,为什么这不起作用?

vi4fp9gy

vi4fp9gy1#

您可能忘记设置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')

相关问题