How to use a custom objective function for a model?
New to Keras and DL, so I may be asking really basic questions... appreciate if someone could explain in an easier term. Thanks!
How to use a custom objective function for a model? Any sample code I could look into to reference from?
It seems models can only accept a string of the pre-defined objective functions here : https://github.com/fchollet/keras/blob/master/keras/objectives.py
However, the doc (http://keras.io/models/) sounds like as if I could just plug in a custom function like score(true, pred): loss: str (name of objective function) or objective function.
The source code also seems to say it's only string: https://github.com/fchollet/keras/blob/master/keras/models.py#L240
You almost answer the question yourself. Create your objective function like ones in https://github.com/fchollet/keras/blob/master/keras/objectives.py like this,
import theano
import theano.tensor as T
epsilon = 1.0e-9
def custom_objective(y_true, y_pred):
'''Just another crossentropy'''
y_pred = T.clip(y_pred, epsilon, 1.0 - epsilon)
y_pred /= y_pred.sum(axis=-1, keepdims=True)
cce = T.nnet.categorical_crossentropy(y_pred, y_true)
return cce
and pass it to compile argument
model.compile(loss=custom_objective, optimizer='adadelta')
I am trying to write a new objective function like the following:
def expert_loss(y_true, y_pred):
# y_pred is n-dimensional, y_true is n+1 dimensional.
return T.sqr(T.dot(y_true[:-1].T, y_pred) - y_true[-1]).mean(axis=-1)
In this objective function the dimensions of y_true and y_pred are different. Keras gives error for shape mismatch. Is this a bug? Is there a way around?
@mthrok , this may be a naive question....but all you need to do is a create a loss function (although it looks like it is not simple if you are not familiar with Theano)? In back prop isnt the gradient needed?
Hi, can you tell me how to check the dimension of y_true and y_pred?? I want to define a objective function which is dependent on the dice coefficient instead of accuracy and as we are using it for segmentation
Hey, I also need to create a custom objective function, but in this case it should use the weights of the layer (instead of the output and prediction). Is there any workaround to access the weights? Thanks!
@rgalhama To access the weights of any layer after compilation of the entire model you can use
weights = model.layer[id].get_weights() # list of numpy arrays
Not sure whether this will work during run-time though. If your goal is to add loss component based on weights of the neural network then you can check regularization option too.
Is there a way of accessing the rest of the batch? I'm doing unsupervised learning and have a custom objective function which is " batch-wise" --- it depends on every example in the batch.
Hi, It is great to abstract the objective function to take (y_pred, y_true) as input. I'm wondering whether there are clean ways to define the objective as a whole? I feel a little bit awkward as I have to explicitly decompose my objective to y_pred and y_true in order to suit the objective interface. In my case, I only need to pass a X into my model and directly optimize the objective, without considering y. A work around is define a function which ignores y_true and pass a 1-vector during training. But I'm wondering whether there are some better ways for that.
@mthrok If I want to write a custom objective function myself, where should I put the function, in the objectives.py of keras file, or directly in my python file? I tried your example code and put it in my python file, but an error occured. 'Exception: Invalid objective: custom_objective'
@mthrok I used compile(loss='custom_objective', ....) And if I used compile(loss= custom_objective, ...) just as your example, keras threw out an error: 'NameError: global name 'custom_objective' is not defined'
@LeZhengThu loss= custom_objective should be okay. Are you sure you aren't misplacing/typo your custom objective function?
This is slightly off the topic, but how can I get shape of the theano tensor variables that go through a cost function?
I am trying to write a custom cost function for an auto-encoder I built. It is basically generalization of 'mean_squared_error' to this case where for each input vector the output is also a vector rather than a value. Mathematically, it is the following:
cost = sum_(i=1,...,N ) {||x_i - x'_i||^2} / N, where x_i is a vector. I modified mean_squared_error as follows:
def vector_mse(X_true, X_pred):
from keras import backend as K
n_featues = K.shape(X_true)[1]
return n_features * K.mean(K.square(y_pred - y_true), aix=None)
# 'axis=None' makes 'mean' to go over all elements of the tensor,
# so I need to multiply the result with n_features to get the mean as defined in equation above.
It fails on 'n_featues = K.shape(X_true)[1]' because K.shape(X_true) return 'Shape.0' instead of a tuple with number of rows/columns.
I am not very familiar with theano backend, but I tried evaluating it as 'K.eval(K.shape(X_true))' but it doesn't work.
Another thing I tried was to convert the tensors to numpy array
'X_true_numpy = K.eval(X_true), and go from there, but it also fails with following error:
raise MissingInputError("Undeclared input", variable) theano.gof.fg.MissingInputError: ('Undeclared input', sequential_2_target) as if X_true is not really assigned.
I appreciate any ideas on how to make this work.
I want to design a customized loss function in which we use the layer outputs in the loss function calculations. For a hypothetical example, lets consider a 3 layered DNN: x->h_1->h_2->y Let's consider that in addition to minimizing (y,y_pred) we want to minimize (h_1, h_2) (crazy hypothetical). In theano it is straightforward: cost=mse(y,y_pred)+mse(h_1,h_2) But with keras, how should I access h_1/h_2 so I could work on them?
One solution that comes to my mind is to create a new input/output pair, let's call them X/Y. Then define X=[y,h_1] and Y=[y_pred,h_2] by Merge(concatenate) them, and then build a new cost function that decouples the Merged symbols and compute mse on each of them. Is this something that might work? Thanks, Hamid
@M-Taha Did you ever resolve this issue involving shape mismatch? I have the same problem.
@shamidreza Have you found a cool way to do it? (I mean, avoiding the merge option)
@curiale Unfortunately, no. I had to go back to my beloved theano for that.
@shamidreza Thanks. I think that you should open a new issue about this.
@hadi-ds I met the same problem like yours, have you solved it?
@kobeee I ended up writing that objective function in theano as follows:
def vector_mse(y_true, y_pred):
from theano import tensor as T
diff2 = (y_true - y_pred)**2
return T.mean(T.sum(diff2, axis = -1))
hope this helps.
@hadi-ds Thank you! I have solved the problem.