在Keras损失函数中,我希望有一个np.nanmean()
等效项:
在损失函数中,与以下简化示例等效的en失败,原因很明显。找不到解决该问题的方法,例如使用K.gather()
。
一个简化的示例:
from keras import backend as K
import numpy as np
nominator = np.array([-6,4,-8,7,0,5,1,-2])
denominator = np.array([1,4,5,7,9,0,12,0])
Nom = K.variable(nominator,dtype='int32')
DeNom = K.variable(denominator,dtype='int32')
Ratio = Nom/DeNom
Loss = K.sum(Ratio)
由于分母为0,这将在Loss函数中返回一个nan:
K.eval(Loss)
nan
我想要某种方式来产生与
相同的结果Loss = K.nansum(Ratio)
或等同于索引:
Filter_Ratio = K.gather(Ratio,K.any(DeNom))
Loss = K.sum(Filter_Ratio)
Filter_Ratio = [-6,4,-8,7,0,1]/[1,4,5,7,9,12]
但是没有K.nansum()
并且K.gather()
不能像这样工作。
我想转移到Keras的numpy实现是:
nominator = np.array([-6,4,-8,7,0,5,1,2])
denominator = np.array([1,4,5,7,9,0,12,0])
ind = denominator!=0
ratio = nominator[ind]/denominator[ind]
loss = np.sum(ratio)
答案 0 :(得分:0)
from keras import backend as K
import tensorflow as tf
Nom = tf.constant([-6,4,-8,7,0,5,1,-2], dtype='int32')
DeNom = tf.constant([1,4,5,7,9,0,12,0], dtype='int32')
Ratio = Nom/DeNom
Ratio1 = tf.where(tf.is_inf(Ratio), tf.zeros_like(Ratio), Ratio)
Loss = K.sum(Ratio1)
with tf.Session() as sess:
print (sess.run(Loss))
输出:
-5.516666666666667
划分张量并将Ratio
张量中的无穷值替换为零
Ratio1 = tf.where(tf.is_inf(Ratio), tf.zeros_like(Ratio), Ratio)
tf.where
与np.where