张量项水平的Keras/Tf自定义损失函数

2024-04-19 00:44:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在Keras中编写一个自定义损失函数,它接受预测值的张量,然后对于每个过程,在增加损失之前通过另一个函数。这是它的样子。这是一个完整的代码示例,请查看函数示例

class AE():
    def __init__(self,inputSize=78,numNeurons = 50, latentSize=5,expSize = 10,batchSize = 1, activation="relu"):
        K.clear_session()

        self.inputSize = inputSize
        self.latentSize = latentSize
        self.activation = activation
        self.numNeurons = numNeurons
        self.expSize = expSize
        self.batchSize = batchSize

        self.encoder = self.createEncoder()
        self.decoder = self.createDecoder()
        self.filterModel = self.createFilterModel()
        self.AE = self.createAE()

    def sample_loss(self,y_pred ):

        loss = 0.0

        for j in tf.range(0,self.inputSize ,2):

            pt = y_pred[j:j+2]
            loss += K.sum(self.filterModel.predict(pt))

        return loss

    def createEncoder(self):
        # create the encoder
        xIn = Input(shape=(self.inputSize,), name="data_in")
        y_train = Input(shape=(self.latentSize,), name='y_train')

        x = Dense(self.numNeurons,activation=self.activation)(xIn)
        xlatent = Dense(self.latentSize,activation=self.activation)(x)

        # create the encoder
        encoder = Model(xIn,xlatent)
        return encoder

    def createDecoder(self):
        # create the decoder
        latentIn = Input(shape=(self.latentSize,))
        x = Dense(self.numNeurons,activation=self.activation)(latentIn)
        out = Dense(self.inputSize,activation="linear")(x)

        # create a decoder
        decoder = Model(latentIn,out)

        return decoder

    def createAE(self):
        xIn = Input(shape=(self.inputSize,), name="ae_data_in")

        # create the total model
        latentOutput = self.encoder(xIn)
        dataOutput = self.decoder(latentOutput)

        model = Model(inputs=xIn,outputs=dataOutput)
        model.add_loss( self.sample_loss( dataOutput) )

        model.summary()

        return model

    def createFilterModel(self):
        xIn = Input(shape=(2,), name="filter_data_in")

        x = Dense(4, activation='sigmoid')(xIn)
        x = Dense(1, activation='sigmoid')(x)

        model = Model(xIn,x)
        model.compile(optimizer='adam', loss='binary_crossentropy')

        return model


modelAE = AE()
modelAE.AE.compile(optimizer='adam',loss="mse", metrics=['accuracy'])

所以我有一本模型词典,filterModels。这些实际上是Keras中的预测模型。对于本词典中的每个模型,我希望将其传递给y_pred的相应部分,然后将其输出添加到损失中

我该怎么做

以下是当前代码给我的错误: ''' ValueError:向模型提供符号张量时,我们希望张量具有静态批量大小。有形状的张量:(无,78) '''