[英]Custom Loss Function in Keras - Iterate through TensorFlow
I am working on creating a custom loss function in Keras.我正在努力在 Keras 中创建自定义损失 function。 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.现在在这个例子中,我只想从 y_pred 中减去特定值,但由于这是在 tensorflow 中,我该如何迭代抛出它们。
For example, can I iterate through y_pred to pick values?例如,我可以遍历 y_pred 来选择值吗? and how?
如何? Lets say for this example, the batch size is 5.
假设对于这个例子,批量大小是 5。
I have tried things such as y_pred[0...i] tf.arange and many more...我已经尝试过诸如 y_pred[0...i] tf.arange 等等...
Just pass it when you are compiling model.在编译 model 时传递它。 Like
喜欢
model.compile(optimizer='sgd', loss = test)
Keras will Iterate over it automatically. Keras 将自动迭代它。 You have also intentaion error in return statement.
您在 return 语句中也有意图错误。
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通过这种方式,您可以将自定义损失 function 传递给 model ,您也可以类似地传递准确度函数
model.compile(optimizer='sgd', loss = test, metrics=[test_accuracy])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.