模型的输出张量必须是Keras图层的输出(因此保留了过去的图层元数据)

时间:2019-04-15 19:48:25

标签: python tensorflow keras

我正在尝试使用自定义Keras层构建模型。尽管我模型的输出是Keras图层,但由于Keras认为不是,所以我无法使用它。

这是我的自定义图层代码:

from keras import backend as K
from keras.layers import Layer

class MyLayer(Layer):

    def __init__(self, output_dim, **kwargs):
        self.output_dim = output_dim
        super(MyLayer, self).__init__(**kwargs)

    def build(self, input_shape):
        # Create a trainable weight variable for this layer.
        self.kernel = self.add_weight(name='kernel', 
                                      shape=(input_shape[1], self.output_dim),
                                      initializer='uniform',
                                      trainable=True)
        self.out_estimate = self.add_weight(name='out_estimate',
                                              shape=(self.output_dim,),
                                              initializer='uniform',
                                              trainable=True)
        self.loss_input_estimate = self.add_weight(name='loss_input_estimate',
                                               shape=(self.output_dim,),
                                               initializer='uniform',
                                               trainable=True)
        super(MyLayer, self).build(input_shape)  # Be sure to call this at the end

    def call(self, x):        
        return loss_input_estimate

    def compute_output_shape(self, input_shape):
        return (input_shape[0], self.output_dim)

这是引发错误的模型代码:

from keras.models import  Model
from keras import layers
from keras import Input

input_tensor = layers.Input(shape=(28 * 28,))
output_tensor = MyLayer(input_tensor)

model = Model(input_tensor, output_tensor)
model.summary()


0 个答案:

没有答案