请教keras中如何获取自定义层的weights啊,单独创建层是可以通过get_weights()得到的,但是通过model和其他层组合之后,自定义层就被拆分成了几个操作层,这样就没办法通过model.layer.get_weights()获取了,因为每个操作层没有weights。
自定义层代码:
class PixelBaseConv(Layer):
def __init__(self, output_dim, **kwargs):
self.output_dim = output_dim
super(PixelBaseConv, self).__init__(**kwargs)
def build(self, input_shape):
# kernel_shape: w*h*c*output_dim
kernel_size = input_shape[1:]
kernel_shape = (1,) + kernel_size + (self.output_dim, )
print(input_shape)
# 为该层创建一个可训练的权重
self.kernel = self.add_weight(name='kernel',
shape=kernel_shape,
initializer='uniform',
trainable=True)
super(PixelBaseConv, self).build(input_shape)
def call(self, inputs):
# output_shape: w*h*output_dim
outputs = []
inputs = K.cast(inputs, dtype="float32")
for i in range(self.output_dim):
#output = tf.keras.layers.Multiply()([inputs, self.kernel[..., i]])
output = inputs*self.kernel[...,i]
output = K.sum(output, axis=-1)
if len(outputs) != 0:
outputs = np.dstack([outputs, output])
else:
outputs = output[..., np.newaxis]
return tf.convert_to_tensor(outputs)
def compute_output_shape(self, input_shape):
return input_shape + (self.output_dim, )
def get_config(self):
base_config = super(PixelBaseConv, self).get_config()
return base_config
自定义层是位于input层之后
模型前几层信息
前几层weights的length