繁体   English   中英

如何在Keras的数组中找到非零的数量?

[英]How to find the number of non-zeros in an array in Keras?

我试图在 Keras 的自定义损失函数中找到零的数量。

def root_mean_squared_error(y_true, y_pred):

在此处输入此损失函数的位置:

model.compile(optimizer=sgd, loss=root_mean_squared_error,
              metrics=[metrics.mse, root_mean_squared_error])

我试图在数组y_true找到非零值的y_true并将我的数字除以这个值。

如何在y_true找到非零元素的y_true

您可以通过tf.count_nonzero后端使用tf.count_nonzero API。

from keras import backend as K
import numpy as np

def custom_loss(y_true, y_pred):
    return y_pred / K.cast(K.tf.count_nonzero(y_true), K.tf.float32)

y_t = K.placeholder((1,2))
y_p = K.placeholder((1,2))

loss = custom_loss(y_t, y_p)

print(K.get_session().run(loss, {y_t: np.array([[1,1]]), y_p: np.array([[2,4]])}))

结果是

[[1. 2.]]

也许您可以将布尔条件y_true != 0与 NumPy 数组一起使用:

z = np.array( y_true != 0 )
# Check the shape of z array.
print( z.shape )
count = z.shape[ 0 ]

这里,count 应该是y_true != 0条件为真的元素数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM