Custom loss function in Keras

巧了我就是萌 提交于 2019-11-26 12:58:15

问题


I\'m working on a image class-incremental classifier approach using a CNN as a feature extractor and a fully-connected block for classifying.

First, I did a fine-tuning of a VGG per-trained network to do a new task. Once the net is trained for the new task, i store some examples for every class in order to avoid forgetting when new classes are available.

When some classes are available, i have to compute every output of the exemplars included the exemplars for the new classes. Now adding zeros to the outputs for old classes and adding the label corresponding to each new class on the new classes outputs i have my new labels, i.e: if 3 new classes enter....

Old class type output: [0.1, 0.05, 0.79, ..., 0 0 0]

New class type output: [0.1, 0.09, 0.3, 0.4, ..., 1 0 0] **the last outputs correspond to the class.

My question is, how i can change the loss function for a custom one to train for the new classes? The loss function that i want to implement is defined as:

where distillation loss corresponds to the outputs for old classes to avoid forgetting, and classification loss corresponds to the new classes.

If you can provide me a sample of code to change the loss function in keras would be nice.

Thanks!!!!!


回答1:


All you have to do is define a function for that, using keras backend functions for calculations. The function must take the true values and the model predicted values.

Now, since I'm not sure about what are g, q, x an y in your function, I'll just create a basic example here without caring about what it means or whether it's an actual useful function:

import keras.backend as K

def customLoss(yTrue,yPred):
    return K.sum(K.log(yTrue) - K.log(yPred))

All backend functions can be seen here: https://keras.io/backend/#backend-functions

After that, compile your model using that function instead of a regular one:

model.compile(loss=customLoss, optimizer = .....)


来源:https://stackoverflow.com/questions/43818584/custom-loss-function-in-keras

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!