人工智能深度学习入门练习之(17)TensorFlow – 张量数据类型

张量中的所有元素只能有一种数据类型。可以使用张量属性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将自动选择数据类型。例如,如果张量创建时传入一个文本值,张量的数据类型将被设置为字符串类型。

猜你喜欢

转载自www.cnblogs.com/huanghanyu/p/13164075.html