很抱歉这个问题的措词不好,但基本上我正在尝试这样做:
1)假设我用CNN滤波器对输入进行卷积,然后得到(batch x,y,5,10)的特征图,其中x和y是取决于输入大小,步幅等的尺寸,而10是功能图
2)因此,现在不再将这些特征图作为下一层的输入,而是对其进行卷积, 我希望这些功能图在下一层中代表我自己的新CNN过滤器。
现在到下一层的输入实际上将是可训练的3d数组/内核。 因此,除了可以训练滤镜之外,它实际上是可以训练的3d阵列。
我尝试使用在keras中构建custom_layer来做到这一点,但是我遇到了这个错误:
TypeError:无法将类型的对象转换为Tensor。内容:(无,20、20、6、10)。考虑将元素强制转换为受支持的类型。
这是我的尝试:
#build my custom layer
from keras.layers import Dense, GlobalAveragePooling2D,Input, Conv2D
from keras.models import Model
from keras import backend as K
from keras.layers import Layer
import numpy as np
class MyLayer(Layer):
def __init__(self,output_dim, **kwargs):
self.height = output_dim[0] #height
self.width = output_dim[1] # width
self.filter = output_dim[2] #filter
super(MyLayer, self).__init__(**kwargs)
def build(self, input_shape): # input_shape[2] = channels
self.kernel = self.add_weight(name='kernel',
shape=(input_shape[0],self.height,self.width, input_shape[2],self.filter),
initializer='uniform',
trainable=True)
super(MyLayer, self).build(input_shape)
def call(self, inputs):
outputs = K.conv2d(
self.kernel, # array to be convolved upon
inputs, # inputs (feature maps) will be kernel
strides= 1,
padding= "same",
data_format= "channels_last",
dilation_rate= 1)
return outputs
def compute_output_shape(self, input_shape):
return (input_shape[0],self.output_dim)
if __name__ == "__main__":
rand_array = np.random.rand(10,10,3)
model_input = Input(shape = (10,10,3))
x = Conv2D (kernel_size = (5,5), filters = 10,padding = "valid", activation='relu')(model_input)
x =MyLayer(output_dim =(20,20,10))(x)
model = Model(inputs = model_input, outputs = x)
#x = GlobalAveragePooling2D()(x)
print(model.summary())