为什么Tensorflow会输出这些简单的结果?

为什么Tensorflow会输出这些简单的结果?,tensorflow,Tensorflow,我是Tensorflow的新手,但我想弄清楚为什么这些结果会以..001,..002等结尾 我在这里遵循教程: 代码: """This is a Tensorflow learning script.""" import tensorflow as tf sess = tf.Session() W = tf.Variable([.3], dtype=tf.float32) b = tf.Variable([-.3], dtype=tf.float32) x = tf.placeholder(

我是Tensorflow的新手,但我想弄清楚为什么这些结果会以
..001
..002
等结尾

我在这里遵循教程:

代码:

"""This is a Tensorflow learning script."""
import tensorflow as tf

sess = tf.Session()

W = tf.Variable([.3], dtype=tf.float32)
b = tf.Variable([-.3], dtype=tf.float32)
x = tf.placeholder(tf.float32)
linear_model = W*x + b

sess.run(tf.global_variables_initializer()) #This is the same as the above 2 lines

print(sess.run(linear_model, {x: [1, 2, 3, 4]}))
它看起来像一个简单的数学函数,如果我使用2作为输入,它将是
(0.3*2)+-0.3=0.3

输出:

"""This is a Tensorflow learning script."""
import tensorflow as tf

sess = tf.Session()

W = tf.Variable([.3], dtype=tf.float32)
b = tf.Variable([-.3], dtype=tf.float32)
x = tf.placeholder(tf.float32)
linear_model = W*x + b

sess.run(tf.global_variables_initializer()) #This is the same as the above 2 lines

print(sess.run(linear_model, {x: [1, 2, 3, 4]}))
[0.0.30000001 0.600000002 0.90000004]

我希望:

[0.0.30.6 0.9]


这可能是一个浮点错误,因为您将变量作为tf.float32数据类型引入。您可以使用tf.round(),但它似乎还没有舍入到最接近的小数点的功能。为此,请查看中的响应:。

问题是a(如tf.float32)无法准确地存储
0.3
,因为它是二进制存储的。这就像试图准确地存储十进制的
1/3
,它将是
0.33…
,但你必须无限远才能得到准确的数字(这在我们的凡人领域是不可能的!)

有关此主题的更深入的回顾,请参阅


Tensorflow还没有办法处理十进制数(据我所知)!但是,一旦这些数字返回python,您就可以进行取整,然后转换为a。

我添加了函数,并添加了一行
linear\u model=my\u tf\u round(linear\u model,1)
,它影响了结果,但现在它们是
[0.0.3000001 0.6000002 0.8999998]
。不太清楚发生了什么…我认为他们应该先做一个更好的例子。对于你的特定例子,你可以简单地用
linear\u model=W*x+b
替换为
linear\u model=tf.cast(10*(W*x+b),tf.int32)/10
。我刚刚试着用这个替换来运行你的代码,它给了我输出
[0.0.3 0.6 0.9]
。我对二进制非常熟悉,可以从十进制转换过来,但我甚至没有考虑存储浮点数…非常好的信息。Tom Scott实际上已经了解了这个主题(我在那里学到了这个)。或者在谷歌搜索时,我找到了一个关于这个话题的答案。但是tl;dr是浮点数有点像二进制的科学符号,它们实际上是两个二进制数X&Y,其中的数字是:X+2^Y。