我正在使用 Keras 函数式 API,并使用 TensorFlow 作为后端来定义卷积层,并且我需要实现一个自定义的 merge
层。
假设如下:
# 已导入所有必要的库。# image_shape = (28, 28, 3)# 16 和 (3,3) 分别是 kernel_count 和 kernel_size。def MyModel(image_shape): input = Input(shape=image_shape) conv1 = Conv2D(16, (3,3), kernel_initializer='he_normal')(input) conv2 = Conv2D(16, (3,3), kernel_initializer='he_normal')(input) conv3 = AddNL()[conv1, conv2]
其中我的自定义合并层 AddNL
在 keras.layers.merge
中实现如下:
class AddNL(_Merge): def _merge_function(self, inputs): nK1 = inputs[0].shape[-1] nK2 = inputs[1].shape[-1] # <?, image,image, channel> Channel = 核的数量。 k = nK1 if nK1 < nK2 else nK2 output = input[0][...,0:k] + input[1][...,0:k] return output
当我的代码运行到这一行时,会抛出以下 TypeError
错误:
TypeError: 'AddNL' 对象没有属性 '__getitem__'
回答:
这是一个拼写错误。代码应该如下所示:
conv3 = AddNL([conv1, conv2])