数据类型

数值类型

标量(Scalar):单个的实数,如1.2,1.3等,维度数dim为0,形状shape为[]。
向量(Vector):n个实数的有序集合,通过中括号包裹,如[1,2],[1,2,3.4]等,维度数dim为1,长度不定,形状shape为[n]。
矩阵(Matrix):n行m列实数的有序集合,如[[1,2],[3,4]],维度数dim为2,每个维度上的长度不定,形状shape为[n,m]。
张量(Tensor):所有维度数dim>2的数组统称为张量。张量的每个维度也叫作轴(Axis)。一般维度代表了具体的物理含义,比如shape为[2,32,32,3]的张量共有4维,如果表示图像数据的话,每个维度代表的含义分别是图像的数量、图像高度、图像宽度、图像通道数。张量的维度数以及每个维度所代表的具体物理含义需要由用户自行定义。

import tensorflow as tf
a = tf.constant(1.2)
b = tf.constant([1.2])
c = tf.constant([[1, 2], [3, 4]])
d = tf.constant([[[1, 2], [3, 4]], [[5, 6],[7, 8]]])
print("标量:", a)
print("向量:", b)
print("矩阵:", c)
print("张量:", d)

np = c.numpy()
print("Numpy:", np)

输出情况如下:

标量: tf.Tensor(1.2, shape=(), dtype=float32)
向量: tf.Tensor([1.2], shape=(1,), dtype=float32)
矩阵: tf.Tensor(
[[1 2]
 [3 4]], shape=(2, 2), dtype=int32)
张量: tf.Tensor(
[[[1 2]
  [3 4]]

 [[5 6]
  [7 8]]], shape=(2, 2, 2), dtype=int32)
Numpy: [[1 2]
 [3 4]]

shape表示张量的形状,dtype表示张量的数据精度
通过张量的numpy()方法可以返回Numpy.array类型的数据。

字符串类型

Tensorflow还支持字符串(String)类型的数据,例如在表示图像数据时,可以先记录图像的路径字符串,再通过预处理函数根据路径读取图像张量。通过传入字符串对象即可创建字符串类型的张量。

a = tf.constant("Hello, Deep Learning")
print("字符串:", a)
# 输出结果
字符串: tf.Tensor(b'Hello, Deep Learning', shape=(), dtype=string)

在tf.strings模块中,提供常见的字符串类型的工具函数,如小写lower()、大写upper()、拼接join()、长度length()、切分split()等。

tf.strings.lower(a)

布尔类型

布尔类型的张量只需要传入Python语言的布尔类型数据,转换成TensorFlow内部布尔型即可。

import tensorflow as tf
a = tf.constant(True)
print("布尔类型:", a)
# 输出结果
布尔类型: tf.Tensor(True, shape=(), dtype=bool)

TensorFlow的布尔类型和Python语言的布尔类型并不等价,不能通用。只可数字等价,对象不等价

数字精度

常用的精度类型有tf.int16, tf.int32, tf.int64, tf.float16, tf.float32, tf.float64等,其中tf.float64即为tf.double。

在创建张量时,可以指定张量的保存精度

tf.constant(123456, dtype=tf.int16)  # tf.Tensor(-7616, shape=(), dtype=int16)数据发生了溢出
tf.constant(123456, dtype=tf.int32)  # tf.Tensor(123456, shape=(), dtype=int32)

对于大部分深度学习算法,一般使用tf.int32和tf.float32可满足大部分场合的精度需求。
可以使用tf.cast()进行类型的转换 注意:高精度转向低精度,可能发生溢出隐患

tf.cast(a, tf.double)

待优化张量

为了区分需要计算梯度信息的张量与不需要计算梯度信息的张量,TensorFlow增加了一种专门的数据类型来支持梯度信息的记录:tf.Variable()。tf.Variable类型在普通张量类型的基础上添加了name、trainable等属性来支持计算图的构建。通过tf.Variable()函数可以将普通张量转换为待优化张量。

import tensorflow as tf
a = tf.constant(1.23)
b = tf.Variable(a)  # 通过普通张量赋值
print("普通张量:", a)
print("待优化张量:", b)

c = tf.Variable([1,2,3])  # 直接赋值
print("待优化张量:", c)

# 通过GradientTape.watch()方法临时加入跟踪梯度信息的列表,从而支持自动求导功能
with tf.GradientTape() as tape:
    tape.watch([a])

输出结果:

普通张量: tf.Tensor(1.23, shape=(), dtype=float32)
待优化张量: <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.23>
待优化张量: <tf.Variable 'Variable:0' shape=(3,) dtype=int32, numpy=array([1, 2, 3], dtype=int32)>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。