简体   繁体   English

如何使用张量流准确舍入一半

[英]How to accurately round half up with tensorflow

I'm trying to replicate some C++ based code into Python API of Tensorflow, but I'm having few floating point inaccuracy issues, although I have been able to find one of them. 我正在尝试将一些基于C ++的代码复制到Tensorflow的Python API中,但是我几乎没有浮点错误问题,尽管我已经找到了其中一个。

Generally, Tensorflow seems to round decimals in a round half down manner, meaning that if we have an integer with fractional value exactly equal to 0.5 , the integral part of that decimal will be rounded down to zero: 通常,Tensorflow似乎以四舍五入的方式将小数点四舍五入 ,这意味着如果我们有一个分数精确等于0.5的整数,则该小数的整数部分将四舍五入为零:

>>> import tensorflow as tf
>>> tf.Session().run(tf.math.round(2.5))
2.0

whereas, many imperative programming languages that I've encountered do the rounding in a round half up manner. 然而,我已经遇到了许多命令式编程语言做的圆角圆半升的方式。 Some of these programming languages are C++ and Python . 其中一些编程语言是C ++Python

In fact, considering that Tensorflow was mostly written in C++, Python and Cuda C++, it seems like a weird convention for them to be using rounding half down method for their functions in API. 实际上,考虑到Tensorflow主要是用C ++,Python和Cuda C ++编写的,对于它们在API中的函数使用rounding half down方法似乎是很奇怪的约定。


Question : 问题

Is there any neat way to implement a rounding function that utilizes rounding half up method instead of rounding half down ? 是否有任何巧妙的方法来实现舍入功能,该方法使用rounding half up方法而不是rounding half down

The simplest function I could implement uses tf.floormod method: 我可以实现的最简单的函数使用tf.floormod方法:

>>> def classical_round(x): return tf.cond(tf.math.equal(tf.floormod(x, 1), tf.constant(0.5)), lambda: tf.math.ceil(x), lambda: tf.math.round(x))
...
>>> tf.Session().run(classical_round(4.5))
5.0
>>> tf.Session().run(classical_round(4.49))
4.0
>>> tf.Session().run(classical_round(4.49999999999999))
5.0
>>> tf.Session().run(classical_round(3.2))
3.0

Is this sufficiently accurate method? 这是足够准确的方法吗? or can something similar be done by using other tensorflow operations? 还是可以通过使用其他张量流操作来完成类似的事情?

Research : 研究方向

I could only find this Github issue relevant to my problem, I think they ended up adding tf.math.rint for which I couldn't find the place in this problem. 我只能找到与我的问题相关的Github问题,我认为他们最终添加了tf.math.rint ,而我在该问题中找不到位置。

Thank you! 谢谢!

called bankers rounding nothing wrong about that same thing happening in c# too. 所谓的银行家也对C#中发生的同一件事进行了正确处理。 you can try something like that: 您可以尝试类似的方法:

def classical_round(x):
    return tf.math.floor(x+0.5)

sess.run(classical_round(2.5)) #3.0

more information here: https://en.wikipedia.org/wiki/Rounding#Round_half_to_even 此处提供更多信息: https : //en.wikipedia.org/wiki/Rounding#Round_half_to_even

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

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