TensorFlow-在计算张量的平均值时忽略无限值 [英] TensorFlow - Ignore infinite values when calculating the mean of a tensor

查看:279
本文介绍了TensorFlow-在计算张量的平均值时忽略无限值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个基本问题,但我找不到解决方案:

This is probably a basic question, but I can't find a solution:

我需要计算张量的均值忽略任何非有限值.

I need to calculate the mean of a tensor ignoring any non-finite values.

例如,mean([2.0, 3.0, inf, 5.0])应该返回3.333,而不是inf2.5.

For example mean([2.0, 3.0, inf, 5.0]) should return 3.333 and not inf nor 2.5.

我尝试了sess.run(tf.reduce_mean([2.0, 3.0, inf, 5.0])),但它返回了inf.

I have tried sess.run(tf.reduce_mean([2.0, 3.0, inf, 5.0])) but it returns inf.

推荐答案

您可以使用 is_finite boolean_mask.

import tensorflow as tf

x = tf.constant([2, 3, float('Inf'), 5])
mymean = tf.reduce_mean(tf.boolean_mask(x, tf.is_finite(x)))

sess = tf.Session()
sess.run(mymean)

请注意,is_finite也将摆脱NaN值.

这篇关于TensorFlow-在计算张量的平均值时忽略无限值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆