问题描述
我正在尝试使用:train = optimizer.minimize(loss)
,但是标准优化器不适用于tf.float64
.因此,我想将loss
从tf.float64
截断为仅tf.float32
.
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
.
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].
推荐答案
简短的答案是,您可以使用tf.float64转换为tf.float32
. org/versions/r0.7/api_docs/python/array_ops.html#cast"rel =" noreferrer> tf.cast()
op:
The short answer is that you can convert a tensor from tf.float64
to tf.float32
using the tf.cast()
op:
loss = tf.cast(loss, tf.float32)
更长的答案是,这不能解决优化器的所有问题. (缺少对tf.float64
的支持是已知问题.)优化器要求您要优化的所有 tf.Variable
对象也必须具有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
.
这篇关于TensorFlow:将float64张量转换为float32的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!