简体   繁体   English

Tensorflow - 从int转换为float奇怪的行为

[英]Tensorflow - casting from int to float strange behavior

I am working on tensorflow 0.12 and am having problem with casting. 我正在研究tensorflow 0.12,我遇到了铸造问题。 The following snippet of code does a strange thing: 以下代码片段做了一件奇怪的事情:

sess = tf.InteractiveSession()
a = tf.constant(1)
b = tf.cast(a, tf.float32)
print b.eval()

I get a value: 6.86574233e-36 我得到一个值:6.86574233e-36

I also tried using tf.to_float() and tf.saturate_cast . 我也尝试过使用tf.to_float()tf.saturate_cast Both gave the same result. 两者都给出了相同的结果。

Please help. 请帮忙。

sess = tf.InteractiveSession()
a = tf.constant(1, tf.int64)  <--------
b = tf.cast(a, tf.float32)
print b.eval()  # 1.0

You need to declare the dtype for your tf.constant : https://www.tensorflow.org/api_docs/python/tf/constant 您需要声明dtype为您tf.constanthttps://www.tensorflow.org/api_docs/python/tf/constant

I checked the code in python3 and python2 for the same tensorflow version as well the code seems to be working correctly as in both the cases I got the following output for python2 我检查了python3和python2中的代码相同的tensorflow版本以及代码似乎正常工作,因为在两种情况下我得到了python2的以下输出

print b.eval()
1.0

I would suggest checking the tensorflow installation or the virtualenv. 我建议检查tensorflow安装或virtualenv。

No error in your program. 你的程序没有错误。

import tensorflow as tf
sess = tf.InteractiveSession()
a = tf.constant(1)
b = tf.cast(a, tf.float32)
print b.eval()

This is an online environment for TF https://codeenv.com/env/run/gXGpnR/ 这是TF的在线环境https://codeenv.com/env/run/gXGpnR/
Test your code there to run, use 测试你的代码在那里运行,使用

  • click on test_tf.py 点击test_tf.py
  • add your code 添加你的代码
  • in left side CLI, type ipython test_tf.py 在左侧CLI中,键入ipython test_tf.py

由于我发现这仍然受到一些关注,我应该提到较新版本的tensorflow没有显示这种行为,我建议使用tensorflow版本1.13或更高版本

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

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