首页 文章

VGG,在keras的感性损失

提问于
浏览
4

我想知道是否可以在keras中添加自定义模型到损失函数 . 例如:

def model_loss(y_true, y_pred):
    inp = Input(shape=(128, 128, 1))
    x = Dense(2)(inp)
    x = Flatten()(x)

    model = Model(inputs=[inp], outputs=[x])
    a = model(y_pred)
    b = model(y_true)

    # calculate MSE
    mse = K.mean(K.square(a - b))
    return mse

这是一个简化的例子 . 我实际上会在损失中使用VGG网,所以只是想了解keras的机制 .

1 回答

  • 4

    通常的方法是将VGG附加到模型的末尾,确保在编译之前其所有图层都有 trainable=False .

    然后你重新计算你的Y_train .

    假设你有这些模型:

    mainModel - the one you want to apply a loss function    
    lossModel - the one that is part of the loss function you want
    

    创建一个彼此追加的新模型:

    from keras.models import Model
    
    lossOut = lossModel(mainModel.output) #you pass the output of one model to the other
    
    fullModel = Model(mainModel.input,lossOut) #you create a model for training following a certain path in the graph.
    

    此模型将具有与mainModel和lossModel完全相同的权重,并且训练此模型将影响其他模型 .

    确保在编译之前不能训练lossModel:

    lossModel.trainable = False
    for l in lossModel.layers:
        l.trainable = False
    
    fullModel.compile(loss='mse',optimizer=....)
    

    现在调整您的数据进行培训:

    fullYTrain = lossModel.predict(originalYTrain)
    

    最后进行培训:

    fullModel.fit(xTrain, fullYTrain, ....)
    

相关问题