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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:52:49  来源:igfitidea点击:

TensorFlow: cast a float64 tensor to float32

pythonmachine-learningtensorflow

提问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 lossfrom tf.float64to only tf.float32.

我正在尝试使用:train = optimizer.minimize(loss)但标准优化器不适用于tf.float64. 因此,我想我的截断losstf.float64tf.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.float64to tf.float32using the tf.cast()op:

简短的回答是,你可以将张量从转换tf.float64tf.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.float64is a known issue.) The optimizers require that all of the tf.Variableobjects that you are trying to optimize must also have type tf.float32.

更长的答案是,这不会解决优化器的所有问题。(缺乏对 的支持tf.float64是一个已知问题。)优化器要求tf.Variable您尝试优化的所有对象也必须具有 type tf.float32