tensorflow基础
文章目录
前言
tensorflow是一个面向深度学习算法的科学计算库,内部主要以张量的形式进行保存和运算。所有的操作都是基于张量对象进行。负责的神经网络其本质就是各种张量的相加、相乘等操作运算进行组合,并结合强大的数据量、计算力完成相关运算和推理。因此需要掌握基本的张量操作。本文主要讲解tensor的基本知识
一、数据基本类型
tensorflow中基本的类型有:数值类型、字符串类型和布尔类型。
1.1 数值类型
数值类型是tensorflow主要类型,根据维度可以分为以下几种:
(1)标量(sarlar)
单个的实数,如1、2、3.1等,维度为0,shape为[]。
#1.1定义一个标量
a=2.2 #python中定义的标量
aa=tf.constant(2.2)#tensorflow中定义的标量
print(type(a),a)
print(type(aa),aa)
运行结果如下:
<class 'float'> 2.2
<class 'tensorflow.python.framework.ops.EagerTensor'> tf.Tensor(2.2, shape=(), dtype=float32)
(2)向量(vector)
n个实数的集合,用中括号包裹。如[2,3],[2.3,4,8]等,维度数为1,shape为[n]。与标量不同,向量定义需要通过一个List容器传给tf.constant()函数。
#1.2 定义一个向量
创建一个元素向量
a=tf.constant([2.2])
print(a,type(a),a.shape)
运行结果:
tf.Tensor([2.2], shape=(1,), dtype=float32) <class 'tensorflow.python.framework.ops.EagerTensor'> (1,)
创建多个元素向量
a=tf.constant([2.2,3,4])
print(a,type(a),a.shape)
运行结果如下:
tf.Tensor([2.2 3. 4. ], shape=(3,), dtype=float32) <class 'tensorflow.python.framework.ops.EagerTensor'> (3,)
(3)矩阵(matrix)
n行m列实数组成有序集合,如[[2,3],[3,4]],维度为2,shape[n,m]
#1.3定义一个矩阵
a=tf.constant([[2,3],[5,6]])# 2行2列
print(a,type(a),a.shape)
运行结果如下:
tf.Tensor(
[[2 3]
[5 6]], shape=(2, 2), dtype=int32) <class 'tensorflow.python.framework.ops.EagerTensor'> (2