我是机器学习、Python 和 Tensorflow 的新手。我习惯用 C++ 或 C# 编写代码,很难使用 tf.backend。
我正在尝试为 LSTM 网络编写一个自定义损失函数,尝试预测时间序列的下一个元素是正数还是负数。我的代码与binary_crossentropy损失函数一起运行得很好。我现在想改进我的网络,使其具有一个损失函数,如果预测概率大于 0.5,则添加下一个时间序列元素的值;如果概率小于或等于 0.5,则减去它。
我尝试过这样的事情:
def customLossFunction(y_true, y_pred):
temp = 0.0
for i in range(0, len(y_true)):
if(y_pred[i] > 0):
temp += y_true[i]
else:
temp -= y_true[i]
return temp
显然,尺寸是错误的,但由于我在调试时无法进入我的函数,因此很难在这里掌握尺寸。
您能告诉我是否可以使用逐元素函数吗?如果是,怎么办?如果没有,你能帮我解决 tf.backend 问题吗?
多谢
从 keras 后端函数中,您可以得到以下函数greater
您可以使用:
import keras.backend as K
def customLossFunction(yTrue,yPred)
greater = K.greater(yPred,0.5)
greater = K.cast(greater,K.floatx()) #has zeros and ones
multiply = (2*greater) - 1 #has -1 and 1
modifiedTrue = multiply * yTrue
#here, it's important to know which dimension you want to sum
return K.sum(modifiedTrue, axis=?)
The axis
应根据您想要求和的内容使用参数。
axis=0 -> batch or sample dimension (number of sequences)
axis=1 -> time steps dimension (if you're using return_sequences = True until the end)
axis=2 -> predictions for each step
现在,如果您只有一个 2D 目标:
axis=0 -> batch or sample dimension (number of sequences)
axis=1 -> predictions for each sequence
如果您只是想对每个序列的所有内容求和,那么就不要放置 axis 参数。
关于此功能的重要说明:
因为它只包含来自的值yTrue
,它不能反向传播来改变权重。这将导致“不支持任何值”错误或非常类似的错误。
虽然yPred
(与模型权重相关的)在函数中使用,它仅用于获取 true x false 条件,该条件是不可微分的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)