gpt4 book ai didi

python - 是否有相当于 np.nanmean() 的 Keras?

转载 作者:太空宇宙 更新时间:2023-11-03 21:07:10 25 4
gpt4 key购买 nike

在 Keras 损失函数中,我希望有一个 np.nanmean() 等效函数:

在损失函数中,以下简化示例的等效项由于明显的原因而失败。找不到处理该问题的方法,例如使用 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,这将在损失函数中返回 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)

最佳答案

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.wherenp.where

非常相似

https://www.tensorflow.org/api_docs/python/tf/where

关于python - 是否有相当于 np.nanmean() 的 Keras?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55325692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com