张量中的所有元素只能有一种数据类型。可以使用张量属性dtype获取数据类型。

import tensorflow as tf
m_shape = tf.constant([ [10, 11],
                        [12, 13],
                        [14, 15] ]                      
                     ) 

print(m_shape.dtype)    

输出

<dtype: 'int32'>    

在某些情况下,你希望更改数据的类型,可以使用tf.cast函数。

下面,使用cast方法将浮点类型的张量转换为整数类型。

# 更改数据类型
type_float = tf.constant(3.123456789, tf.float32)
type_int = tf.cast(type_float, dtype=tf.int32)
print(type_float.dtype)
print(type_int.dtype)   

输出

<dtype: 'float32'>
<dtype: 'int32'>

当张量在创建时没有指定数据类型,TensorFlow将自动选择数据类型。例如,如果张量创建时传入一个文本值,张量的数据类型将被设置为字符串类型。

相关文章:

  • 2021-08-05
  • 2021-10-15
  • 2021-06-23
  • 2021-12-04
  • 2021-07-11
  • 2021-07-15
  • 2021-09-27
猜你喜欢
  • 2021-11-23
  • 2022-02-09
  • 2021-05-17
  • 2021-05-27
  • 2021-09-03
  • 2022-01-21
  • 2021-08-23
相关资源
相似解决方案