TensorFlow数据类型
基本数据类型
# 整形
tf.constant(1)
# <tf.Tensof: id=2, shape=(), dtype=int32, numpy=1>
# 浮点型
tf.constant(1.)
# <tf.Tensof: id=4, shape=(), dtype=float32, numpy=1.0>
tf.constant(2.2, dtype=tf.int32) #报错
tf.constant(2., dtype=tf.double)
# <tf.Tensof: id=7, shape=(), dtype=float64, numpy=2.0>
# 布尔型
tf.constant([True, False])
# <tf.Tensof: id=9, shape=(), dtype=bool, numpy=array([True, False])>
Tensor Property
分别在cpu和gpu下创建tensor
with tf.device("cpu"):
a = tf.constant([1])
with tf.device("gpu"):
b = tf.range(4)
在cpu上的tensor只能使用cpu的操作,gpu同理。
查看tensor所在的设备
a.device
将tensor转移至另一设备
aa = a.gpu()
将tensor转换为numpy
b.numpy()
# array([0, 1, 2, 3], dtype = int32)
查看tensor的shape和维度
b.shape
b.ndim
tf.rank(b)
Check Tensor Type
a = tf.constant([1.])
b = tf.constant([True,False])
c = tf.constant('hello, world.')
d = np.arange(4)
# 判断是否为tensor
tf.is_tensor(b) # True
tf.is_tensor(d) # False
# 显示数据类型
a.dtype,b.dtype,c.dtype
# tf.float32, tf.bool, tf.string
c.dtype==tf.string # True
Convert 类型转换
将numpy转换为tensor
a = np.arange(5) # 默认int64
aa = tf.convert_to_tensor(a)
aa = tf.convert_to_tensor(a, dtype=tf.int32)
tensor类型转换
tf.cast(aa, dtype=tf.float32)
a = tf.range(5)
b=tf.Variable(a, name='input_data')
b.name
b.trainable
tf.is_tensor(b) #True
显示tensor数据
调用numpy方法
a.numpy()
若a为标量,则可直接转换
int(a)
float(a)