我正在尝试在 Keras 中创建一个带有输入(batch、channels(3)、64、32)的神经网络,但使用 Batch 归一化时出现错误(因为错误从上述层开始,所以我选择隔离该部分导致错误)模型开始如下:
input_imgC = Input(shape=(X.shape[1], X.shape[2], X.shape[3]))
x = Conv2D(32, (5, 5), activation='relu', padding='same', data_format="channels_first")(input_imgC)
out = BatchNormalization(axis=1)(x)
我收到以下异常:
Shape must be rank 1 but is rank 0 for 'batch_normalization_1/cond/Reshape_4' (op: 'Reshape') with input shapes: [1,32,1,1], [].
我认为数据从卷积层转换得很糟糕,这就是为什么我尝试了没有批量归一化的模型。型号:
input_imgC = Input(shape=(X.shape[1], X.shape[2], X.shape[3]))
out = Conv2D(32, (5, 5), activation='relu', padding='same', data_format="channels_first")(input_imgC)
正确生成以下摘要:
Layer (type) Output Shape Param #
================================================================= > input_1 (InputLayer) (None, 3, 64, 32) 0
conv2d_1 (Conv2D) (None, 32, 64, 32) 2432
================================================================= Total params: 2,432 Trainable params: 2,432 Non-trainable params: 0
我知道我可以使用
out = BatchNormalization(axis=-1)(x)
模型输入为 (batch, 64, 32, Channels(3)) ,它会工作(我已经尝试过),但我需要在开始时配置 channel ,以便使用以下包测试模型显示对象的显着性。
有人知道在这里做什么吗?
最佳答案
我不知道问题是什么,这似乎是一个 Keras bug(更新版本或在 GitHub 上搜索问题可能会显示有关此问题的提示)。
我的建议是,像往常一样,您从一开始就排列维度,最后将所有内容用作 channel 。
最后,如果您的输出是图像,请将尺寸恢复为您想要的顺序。
input_imgC = Input(shape=(X.shape[1], X.shape[2], X.shape[3]))
x = Lambda(lambda inputs: K.permute_dimensions(inputs,(0,2,3,1)))(input_imgC)
x = Conv2D(32, (5, 5), activation='relu', padding='same')(x)
x = BatchNormalization()(x)
out = .......
out = Lambda(lambda inputs: K.permute_dimensions(inputs,(0,3,1,2)))(out)
提示:
理想情况下,我会在 relu 之前使用批量标准化。这会将 relu 变成一种安全激活,很少会被卡住,但如果不小心使用,情况就不是这样。
x = Conv2D(..., activation='linear')(x) #or no activation
x = BatchNormalization()(x)
x = Activation('relu')(x)
使用其他激活(例如 sigmoid 和 tanh)来执行此操作有一些优点,因为批量归一化可能有助于逃离饱和区域。
关于Keras:批量归一化(axis=1)的等级为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53634842/