为什么 Python int
不能转换成 Tensorflow dtype?
将给定的 type_value 转换为 DType。
<块引用>TensorFlow 将 Python 整数转换为 tf.int32,将 Python 浮点数转换为 tf.float32。
Numpy 类型和 Python float
可以转换为 Tensorflow dtypes,但 int
会导致错误。请帮助理解原因。
print("np.float equivalent in TF is %s" % tf.dtypes.as_dtype(np.float))
print("Python float equivalent in TF is %s" % tf.dtypes.as_dtype(float))
# TypeError: Cannot convert value <class 'int'> to a TensorFlow DType.
print("Python int equivalent in TF is %s" % tf.dtypes.as_dtype(int))
np.float equivalent in TF is <dtype: 'float32'>
Python float equivalent in TF is <dtype: 'float32'>
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-31-d36ebc2109e2> in <module>
2 print("Python float equivalent in TF is %s" % tf.dtypes.as_dtype(float))
3 # TypeError: Cannot convert value <class 'int'> to a TensorFlow DType.
----> 4 print("Python int equivalent in TF is %s" % tf.dtypes.as_dtype(int))
~/conda/envs/tensorflow/lib/python3.8/site-packages/tensorflow/python/framework/dtypes.py in as_dtype(type_value)
647 return _INTERN_TABLE[type_value.as_datatype_enum]
648
--> 649 raise TypeError("Cannot convert value %r to a TensorFlow DType." %
650 (type_value,))
TypeError: Cannot convert value <class 'int'> to a TensorFlow DType.
答案 0 :(得分:1)
函数声明:
<块引用>可以转换为 tf.DType 对象的值。这可能目前 是 tf.DType 对象、DataType 枚举、字符串类型名称或 numpy.dtype。
您可以检查source code:
...
// Data types that all computation devices are expected to be
// capable to support.
DT_FLOAT = 1;
DT_DOUBLE = 2;
DT_INT32 = 3;
DT_UINT8 = 4;
DT_INT16 = 5;
...
当您传递 float32
时,它会强制转换为 float
,但没有直接推断 int
。您需要表明您正在通过 int32
或其他任何东西。
print("Python int equivalent in TF is %s" % tf.dtypes.as_dtype('int32'))
--> Python int equivalent in TF is <dtype: 'int32'>
还有:
print("Python int equivalent in TF is %s" % tf.dtypes.as_dtype(3)) # order
Python int equivalent in TF is <dtype: 'int32'>