TensorFlow
定义:
TensorFlow 是由 Google 开发的一个深度学习框架,旨在为生产环境提供高性能的机器学习解决方案。
特点:
静态图(Static Computation Graph):早期版本使用静态计算图,需要在训练前定义整个模型结构,但 TensorFlow 2.0 引入了 Eager Execution,支持动态计算图。
强大的生态系统:包括 TensorFlow Serving(模型部署)、TensorFlow Lite(移动设备)和 TensorFlow.js(浏览器)。
可视化工具:提供 TensorBoard,用于可视化训练过程和模型性能。
1.数据类型
数值型 ——其是TensorFlow的主要数据载体
字符串型
布尔型
1.1数值类型
数值类型的张量是TensorFlow的主要数据载体,分为:
标量(Scalar) 单个的实数,维度数(Dimension,也叫秩)为0,shape=[]
向量(Vector) n个实数的有序集合,通过中括号包裹,如[1,2],维度数位1,长度不定,shape=[n]
矩阵(Matrix) n行m列实数的有序集合,如[[1,2],[3,4]],维度数为2,每个维度上的长度不定,shape=[n,m]
**张量(Tensor) ** 所有维度数dim > 2的数组统称为张量,张量的每个维度也做轴(Axis), 比如Shape =[2,32,32,3]的张量共有 4 维
在 TensorFlow 中间,为了表达方便,一般把标量、向量、矩阵也统称为张量,
In :
aa = tf.constant(1.2) # 创建标量
type(aa)
Out:
(float, tensorflow.python.framework.ops.EagerTensor, True)
In :
x = tf.constant([1,2.,3.3]) #创建向量
x,x.shape
Out:
(<tf.Tensor: id=165, shape=(3,), dtype=float32, numpy=array([1. , 2. , 3.3], dtype=float32),TensorShape([3])>)
其中 id 是 TensorFlow 中内部索引对象的编号,shape 表示张量的形状,dtype 表示张量的数值精度,张量 numpy()方法可以返回 Numpy.array 类型的数据。
In :
a = tf.constant([[1,2],[3,4]]) #创建矩阵
a, a.shape
Out:
(<tf.Tensor: id=13, shape=(2, 2), dtype=int32, numpy=
array([[1, 2],[3, 4]])>, TensorShape([2, 2]))
1.2字符串类型
TensorFlow 还支持字符串(String)类型的数据,例如在表示图 片数据时,可以先记录图片的路径,再通过预处理函数根据路径读取图片张量。
In :
a = tf.constant('Hello, Deep Learning.')
Out:
<tf.Tensor: id=17, shape=(), dtype=string, numpy=b'Hello, Deep Learning.'>
在 tf.strings 模块中,提供了常见的字符串型的工具函数,如拼接 join(),长度 length(),切 分 split()等等。
1.3布尔类型
布尔类型的张量只需要传入 Python 语言的布尔类型数据,转换成 TensorFlow 内部布尔型即可。
In :
a = tf.constant(True)
Out:
<tf.Tensor: id=22, shape=(), dtype=bool, numpy=True>
TensorFlow 的布尔类型和 Python 语言的布尔类型并不对等,不能通用。