使用 keras 创建减少通道大小的自定义激活时出错

Error in creating custom activation that reduces the channel size with keras

我用 keras 创建了一个自定义激活函数,它将通道大小减少了一半(最大特征映射激活)。

下面是部分代码:

import tensorflow as tf
import keras
from keras.utils.generic_utils import get_custom_objects
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D, Activation

def MyMFM (x):
    Leng = int(x.shape[-1])
    ind1=int(Leng/2)   
    X1=x[:,:,:,0:ind1]
    X2=x[:,:,:,ind1:Leng]
    MfmOut=tf.maximum(X1,X2)
    return MfmOut

get_custom_objects().update({'MyMFM ': Activation(MyMFM)})

model = Sequential()
model.add(Conv2D(32, kernel_size=(5, 5),strides=(1, 1), padding = 'same',input_shape = (513,211,1)))
model.add(Activation(MyMFM))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(48, kernel_size=(1, 1),strides=(1,  1 ), padding = 'same'))

当我编译这段代码时,出现以下错误:

 number of input channels does not match corresponding dimension of filter, 16 != 32 

这个错误来自最后一行代码。激活后,通道长度从 32 减少到 16。但下一层自动将通道长度视为 32(第一层中的过滤器数量)而不是 16。我尝试在第二个卷积层中添加 input_shape 参数将输入形状定义为 (513,211,16)。但这也给了我同样的错误。激活后如何将张量的形状传递到下一层?

谢谢

因此 - 根据 this 文档,您可能会看到 keras 引擎会自动将图层的输出形状设置为其输入形状。

改为使用 Lambda 图层。