Python 的 %
运算符始终返回与除数(第二个参数)符号相同的数字,例如:
-7.0 % 3.0 -> 2.0
但是,Tensorflow 的 mod 运算符的实现方式似乎略有不同:
tf.mod(-7.0, 3.0).eval() -> -1.0
如何让 Tensorflow 返回与 python 实现相同的值?
import tensorflow as tf
def main():
v_num = -7.0
v_div = 3.0
mod_tf = tf.mod(v_num, v_div)
mod_py = v_num % v_div
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
print('TF: {} % {} = {}'.format(v_num, v_div, mod_tf.eval()))
print('PY: {} % {} = {}'.format(v_num, v_div, mod_py))
if __name__ == "__main__":
main()
最佳答案
有趣的发现。也许值得在这里提交一个 github 问题:https://github.com/tensorflow/tensorflow/issues
对于解决方法,我认为您可以使用这一行:
mod_tf = tf.cond(mod_tf < 0, lambda: mod_tf+v_div, lambda: mod_tf)
关于python - tensorflow的mod运算符可以匹配python的modulo实现吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39889349/