本文用于收集在使用keras过程中遇见的各种各样的注意事项和小问题。

BatchNormalization报错Shape must be rank 1 but is rank 0

根据keras Document[^1a]所述,BN层的axis应取需要标准化的轴(通常是特征轴)。

即在 data_format="channels_first" ,对应为*(batch,channel,img_h,img_w)时,设置 axis=1 ;在(batch,img_h,img_w,channel)*时,设置为axis=3

然而在我使用ResNet的过程中,当数据设置为后者时,工作正常;设置为前者时,系统报错提示Shape must be rank 1 but is rank 0 for 'batch_normalization_1/cond/Reshape_4' (op: 'Reshape') with input shapes

据查,该问题为keras的版本bug。可考虑通过permute_dimensions变换来规避该问题[^1b]。但如果你的keras为2.2.x-2.4.x版本,更直接的方法是通过以下方法将keras回退[^1c]。

1
2
pip uninstall keras
pip3 install keras==2.1.6 -i http://pypi.douban.com/simple --trusted-host pypi.douban.com

[^1a]: Layers »标准化层 Normalization
[^1b]: Keras: Batch normalization(axis=1) has rank 0
[^1c]: Shape must be rank 1 but is rank 0 for ‘bn_conv1_4/Reshape_4’ (op: ‘Reshape’)