0

I am working on creating a custom loss function in Keras. Here is an example.

import keras.backend as K
def test(y_true, y_pred):
     loss = K.square(y_pred - y_true)
     loss = K.mean(loss, axis = 1)
return loss 

Now in this example, I would like to only subtract let's say specific values from y_pred, but since this is in tensorflow, how do I iterate throw them.

For example, can I iterate through y_pred to pick values? and how? Lets say for this example, the batch size is 5.

I have tried things such as y_pred[0...i] tf.arange and many more...

1 Answers1

0

Just pass it when you are compiling model. Like

model.compile(optimizer='sgd', loss = test)

Keras will Iterate over it automatically. You have also intentaion error in return statement.

import keras.backend as K
def test(y_true, y_pred):
     loss = K.square(y_pred - y_true)
     loss = K.mean(loss, axis = 1)
     return loss 

def test_accuracy(y_true, y_pred):
     return 1 - test(y_true, y_pred)

By this way you can pass your custom loss function to the model and you can also pass accuracy funtion similarly

model.compile(optimizer='sgd', loss = test, metrics=[test_accuracy])
Sohaib Anwaar
  • 1,517
  • 1
  • 12
  • 29
  • hello Sohaib, i am creating a custom loss function so I can find the average of the highest values in a set interval from the y_pred. So I understand that it would automatically iterate, but is it possible to make it iterate every set intervals of my choosing? – Toxic Gamer Jul 01 '20 at 03:26
  • 1
    Yaa! you can I will try to answer this in some time after checking it on my notebook. – Sohaib Anwaar Jul 01 '20 at 03:28
  • Thank you! and also it would be helpful if you can show how I can pick a value from the y_pred. So simply put in an example, I want to be able to check the highest value, lets say every 10 points, and then find the loss of that – Toxic Gamer Jul 01 '20 at 03:32