Python TensorFlow:将 float64 张量转换为 float32
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35725513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TensorFlow: cast a float64 tensor to float32
提问by Karishma Malkan
I am trying to use: train = optimizer.minimize(loss)
but the standard optimizers do not work with tf.float64
. Therefore I want to truncate my loss
from tf.float64
to only tf.float32
.
我正在尝试使用:train = optimizer.minimize(loss)
但标准优化器不适用于tf.float64
. 因此,我想我的截断loss
从tf.float64
只tf.float32
。
Traceback (most recent call last):
File "q4.py", line 85, in <module>
train = optimizer.minimize(loss)
File "/Library/Python/2.7/site-packages/tensorflow/python/training/optimizer.py", line 190, in minimize
colocate_gradients_with_ops=colocate_gradients_with_ops)
File "/Library/Python/2.7/site-packages/tensorflow/python/training/optimizer.py", line 229, in compute_gradients
self._assert_valid_dtypes([loss])
File "/Library/Python/2.7/site-packages/tensorflow/python/training/optimizer.py", line 354, in _assert_valid_dtypes
dtype, t.name, [v for v in valid_dtypes]))
ValueError: Invalid type tf.float64 for Add_1:0, expected: [tf.float32].
回答by mrry
The short answer is that you can convert a tensor from tf.float64
to tf.float32
using the tf.cast()
op:
简短的回答是,你可以将张量从转换tf.float64
到tf.float32
使用tf.cast()
OP:
loss = tf.cast(loss, tf.float32)
The longer answer is that this will not solve all of your problems with the optimizers. (The lack of support for tf.float64
is a known issue.) The optimizers require that all of the tf.Variable
objects that you are trying to optimize must also have type tf.float32
.
更长的答案是,这不会解决优化器的所有问题。(缺乏对 的支持tf.float64
是一个已知问题。)优化器要求tf.Variable
您尝试优化的所有对象也必须具有 type tf.float32
。