TensorFlow2.1基本概念与常见函数

TensorFlow2.1基本概念与常见函数

一、基本概念

1.1 Tensor的概念

TensorFlow 中的 Tensor 表示张量,是多维数组(列表),用阶表示张量的维数。

维数 名字 举例
0-D 0 标量 scalar s = 1 , 2 , 3 s=1,2,3 s=1,2,3
1-D 1 向量 vector v = [ 1 , 2 , 3 ] v=[1,2,3] v=[1,2,3]
2-D 2 矩阵 matrix m = [ [ 1 , 2 , 3 ] ] , [ 4 , 5 , 6 ] ] , [ 7 , 8 , 9 ] ] m=[[1,2,3]],[4,5,6]],[7,8,9]] m=[[1,2,3]],[4,5,6]],[7,8,9]]
n-D 3 张量 tensor t = [ [ [ . . . ] ] ] n 个 t=[[[...]]] n个 t=[[[...]]]n

张量可以表示0阶到n阶数组(列表)

1.2 Tensor数据类型

  • tf.inttf.float 整型、浮点型
    tf.int 32,tf.float 32,tf.float 64
  • tf.bool 布尔型
    tf.constant([True,False])
  • tf.string 字符串型
    tf.constant(“Hello,world!”)

1.3 创建Tensor

  1. 直接创建一个张量

tf.constant(张量内容,dtype=数据类型(可选))

import tensorflow as tf
a=tf.constant([1,5],dtype=tf.int64)
print(a)
print(a.dtype)
print(a.shape)

运行结果如下:

<tf.Tensor([1,5], shape=(2 , ) , dtype=int64)
<dtype: 'int64'>
(2,)
  1. 将numpy的数据类型转换为Tensor数据类型

tf.convert_to_tensor(数据名,dtype=数据类型(可选))

import tensorflow as tf
import numpy as np
a = np.arange(0, 5)
b = tf.convert_to_tensor( a, dtype=tf.int64 )
print(a)
print(b)

运行结果如下:

[0 1 2 3 4]
tf.Tensor([0 1 2 3 4], shape=( 5 , ), dtype=int64)
  1. 使用函数初始化
  • 创建全为0的张量 tf.zeros(维度)
  • 创建全为1的张量 tf.ones(维度)
  • 创建全为指定值的张量 tf.fill(维度,指定值)

维度:

  • 一维 直接写个数
  • 二维 用 [ 行,列 ] [行,列] [行,列]
  • 多维 用 [ n , m , j , k … … ] [n,m,j,k……] [n,m,j,k……]
a = tf.zeros([2, 3])
b = tf.ones(4)
c = tf.fill([2, 2], 9)
print(a)
print(b)
print(c)

运行结果如下:

tf.Tensor([[0. 0. 0.] [0. 0. 0.]], shape=(2, 3), dtype=float32)
tf.Tensor([1. 1. 1. 1.], shape=(4, ), dtype=float32)
tf.Tensor([[9 9] [9 9]], shape=(2, 2), dtype=int32)
  • 生成正态分布的随机数,默认均值为0,标准差为1
    tf. random.normal (维度,mean=均值,stddev=标准差)
  • 生成截断式正态分布的随机数
    tf. random.truncated_normal (维度,mean=均值,stddev=标准差)
    在tf.truncated_normal中如果随机生成数据的取值在(μ-2σ,μ+2σ)之外,则重新进行生成,保证了生成值在均值附近。
d = tf.random.normal ([2, 2], mean=0.5, stddev=1)
print(d)
e = tf.random.truncated_normal ([2, 2], mean=0.5, stddev=1)
print(e)

运行结果如下:

tf.Tensor(
[[0.7925745 0.643315 ]
[1.4752257 0.2533372]], shape=(2, 2), dtype=float32)
tf.Tensor(
[[ 1.3688478 1.0125661 ]
[ 0.17475659 -0.02224463]], shape=(2, 2), dtype=float32)
  • 生成均匀分布随机数 ( minval, maxval )
    tf.random.uniform(维度,minval=最小值,maxval=最大值)
f = tf.random.uniform([2, 2], minval=0, maxval=1)
print(f)

tf.Tensor(
[[0.28219545 0.15581512]
[0.77972126 0.47817433]], shape=(2, 2), dtype=float32)

二、常用函数

2.1 统计类函数

  1. 强制tensor转换为该数据类型
    tf.cast (张量名,dtype=数据类型)
  2. 计算张量维度上元素的最小值
    tf.reduce_min (张量名)
  3. 计算张量维度上元素的最大值
    tf.reduce_max (张量名)
x1 = tf.constant ([1., 2., 3.],
dtype=tf.float64)
print(x1)
x2 = tf.cast (x1, tf.int32)
print(x2)
print (tf.reduce_min(x2), 
tf.reduce_max(x2))

运行结果如下:

tf.Tensor([1. 2. 3.], shape=(3,), dtype=float64)
tf.Tensor([1 2 3], shape=(3,), dtype=int32)
tf.Tensor(1, shape=(), dtype=int32)
tf.Tensor(3, shape=(), dtype=intt32)

在一个二维张量或数组中,可以通过调整 axis 等于0或1 控制执行维度。

  • axis=0代表跨行(经度,down),
  • axis=1代表跨列(纬度,across)
  • 如果不指定axis,则所有元素参与计算

TensorFlow2.1基本概念与常见函数_第1张图片
4. 计算张量沿着指定维度的平均值
tf.reduce_mean (张量名,axis=操作轴)
5. 计算张量沿着指定维度的和
tf.reduce_sum (张量名,axis=操作轴)

x=tf.constant( [ [ 1, 2, 3],[ 2, 2, 3] ] )
print(x)
print(tf.reduce_mean( x ))
print(tf.reduce_sum( x, axis=1 ))

运行结果如下:

tf.Tensor([[1 2 3][2 2 3]], shape=(2, 3), dtype=int32)
tf.Tensor(2, shape=(), dtype=int32)
tf.Tensor([6 7], shape=(2,), dtype=int32)

2.2 数学运算函数

2.2.1 四则运算

  1. 实现两个张量的对应元素相加
    tf.add (张量1,张量2)
  2. 实现两个张量的对应元素相减
    tf.subtract (张量1,张量2)
  3. 实现两个张量的对应元素相乘
    tf.multiply (张量1,张量2)
  4. 实现两个张量的对应元素相除
    tf.divide (张量1,张量2)

只有维度相同的张量才可以做四则运算

a = tf.ones([1, 3])
b = tf.fill([1, 3], 3.)
print(a)
print(b)
print(tf.add(a,b))
print(tf.subtract(a,b))
print(tf.multiply(a,b))
print(tf.divide(b,a))

运行结果如下:

tf.Tensor([[1. 1. 1.]], shape=(1, 3), dtype=float32)
tf.Tensor([[3. 3. 3.]], shape=(1, 3), dtype=float32
tf.Tensor([[4. 4. 4.]], shape=(1, 3), dtype=float32)
tf.Tensor([[-2. -2. -2.]], shape=(1, 3), dtype=float32)
tf.Tensor([[3. 3. 3.]], shape=(1, 3), dtype=float32)
tf.Tensor([[3. 3. 3.]], shape=(1, 3), dtype=float32)

2.2.2 平方、次方与开方

  1. 计算某个张量的平方:tf.square (张量名)
  2. 计算某个张量的n次方:tf.pow (张量名,n次方数)
  3. 计算某个张量的开方:tf.sqrt (张量名)
a = tf.fill([1, 2], 3.)
print(a)
print(tf.pow(a, 3))
print(tf.square(a))
print(tf.sqrt(a))

运行结果如下:

tf.Tensor([[3. 3.]], shape=(1, 2), dtype=float32)
tf.Tensor([[27. 27.]], shape=(1, 2), dtype=float32)
tf.Tensor([[9. 9.]], shape=(1, 2), dtype=float32)
tf.Tensor([[1.7320508 1.7320508]], shape=(1, 2), dtype=float32)

2.2.3 矩阵乘法

实现两个矩阵的相乘:tf.matmul(矩阵1,矩阵2)

a = tf.ones([3, 2])
b = tf.fill([2, 3], 3.)
print(tf.matmul(a, b))

运行结果如下:

tf.Tensor(
[[6. 6. 6.]
[6. 6. 6.]
[6. 6. 6.]], shape=(3, 3), dtype=float32)

2.3 其他常用函数

1. tf.Variable()

tf.Variable () 将变量标记为“可训练”,被标记的变量会在反向传播
中记录梯度信息。神经网络训练中,常用该函数标记待训练参数

w = tf.Variable(tf.random.normal([2, 2], mean=0, stddev=1))

2.tf.data.Dataset.from_tensor_slices()

切分传入张量的第一维度,生成输入特征/标签对,构建数据集
data = tf.data.Dataset.from_tensor_slices((输入特征, 标签))

features = tf.constant([12,23,10,17])
labels = tf.constant([0, 1, 1, 0])
dataset = tf.data.Dataset.from_tensor_slices((features, labels))
print(dataset)
for element in dataset:
   print(element)

运行结果如下:

<TensorSliceDataset shapes: ((),()), types: (tf.int32, tf.int32))> 
(<tf.Tensor: id=9, shape=(), dtype=int32, numpy=12>, <tf.Tensor: id=10, shape=(), dtype=int32, numpy=0>) 
(<tf.Tensor: id=11, shape=(), dtype=int32, numpy=23>, <tf.Tensor: id=12, shape=(), dtype=int32, numpy=1>) 
(<tf.Tensor: id=13, shape=(), dtype=int32, numpy=10>, <tf.Tensor: id=14, shape=(), dtype=int32, numpy=1>) 
(<tf.Tensor: id=15, shape=(), dtype=int32, numpy=17>, <tf.Tensor: id=16, shape=(), dtype=int32, numpy=0>)

3.tf.GradientTape()

with结构记录计算过程,gradient求出张量的梯度

with tf.GradientTape( ) as tape:
   w = tf.Variable(tf.constant(3.0))
   loss = tf.pow(w,2) #loss=w^2 loss’=2w
grad = tape.gradient(loss,w) 
print(grad)

运行结果如下:

tf.Tensor(6.0, shape=(), dtype=float32)

4.enumerate()

enumerate是python的内建函数,它可遍历每个元素(如列表、元组
或字符串),组合为:索引 元素,常在for循环中使用。

seq = ['one', 'two', 'three']
for i, element in enumerate(seq):
   print(i, element)

运行结果如下:

0 one
1 two
2 three

5.tf.one_hot()

独热编码(one-hot encoding):在分类问题中,常用独热码做标签,
标记类别:1表示是,0表示非
tf.one_hot()函数将待转换数据,转换为one-hot形式的数据输出

tf.one_hot (待转换数据, depth=几分类)

classes = 3
labels = tf.constant([1,0,2]) # 输入的元素值最小为0,最大为2
output = tf.one_hot( labels, depth=classes )
print(output)

运行结果如下:

([[0. 1. 0.]
[1. 0. 0.]
[0. 0. 1.]], shape=(3, 3), dtype=float32)

6.tf.nn.softmax()

S o f t m a x ( y i ) = e y i ∑ j = 0 n e y j Softmax(y_i)=\frac{e^{y_i}}{\sum^n_{j=0}e^{y_j}} Softmax(yi)=j=0neyjeyi
当n分类的n个输出 ( y 0 , y 1 , … … y n − 1 ) (y_0 ,y_1, …… y_{n-1}) y0y1,……yn1通过softmax( ) 函数,
便符合概率分布
∀ P ( X = x ) ∈ [ 0 , 1 ] 且 ∑ x P ( X = x ) = 1 \forall P(X=x)\in [0,1]且\sum_xP(X=x)=1 P(X=x)[0,1]xP(X=x)=1

y = tf.constant ( [1.01, 2.01, -0.66] )
y_pro = tf.nn.softmax(y)
print("After softmax, y_pro is:", y_pro)

运行结果如下:

After softmax, y_pro is: tf.Tensor([0.25598174 0.69583046 0.0481878], shape=(3,), dtype=float32)

7.assign_sub()

赋值操作,更新参数的值并返回。
调用assign_sub前,先用 tf.Variable 定义变量 w 为可训练(可自更新)。

w.assign_sub (w要自减的内容)

w = tf.Variable(4)
w.assign_sub(1)
print(w)

<tf.Variable 'Variable:0' shape=() dtype=int32, numpy=3>

8.tf.argmax()

返回张量沿指定维度最大值的索引

tf.argmax (张量名,axis=操作轴)

import numpy as np
test = np.array([[1, 2, 3], [2, 3, 4], [5, 4, 3], [8, 7, 2]])
print(test)
print( tf.argmax (test, axis=0)) # 返回每一列(经度)最大值的索引
print( tf.argmax (test, axis=1)) # 返回每一行(纬度)最大值的索引

运行结果如下:

[[1 2 3]
[2 3 4]
[5 4 3]
[8 7 2]]
tf.Tensor([3 3 1], shape=(3,), dtype=int64)
tf.Tensor([2 2 0 0], shape=(4,), dtype=int64)

9.tf.where()

tf.where(条件语句,真返回A,假返回B)

a=tf.constant([1,2,3,1,1])
b=tf.constant([0,1,3,4,5])
c=tf.where(tf.greater(a,b), a, b) # 若a>b,返回a对应位置的元素,否则
返回b对应位置的元素
print("c:",c)

运行结果如下:

c: tf.Tensor([1 2 3 4 5], shape=(5,), dtype=int32)

10.np.random.RandomState.rand()

返回一个[0,1)之间的随机数
np.random.RandomState.rand(维度) # 维度为空,返回标量

import numpy as np
rdm=np.random.RandomState(seed=1) #seed=常数每次生成随机数相同
a=rdm.rand() # 返回一个随机标量
b=rdm.rand(2,3) # 返回维度为2行3列随机数矩阵
print("a:",a)
print("b:",b)

运行结果如下:

a: 0.417022004702574
b: [[7.20324493e-01 1.14374817e-04 3.02332573e-01]
[1.46755891e-01 9.23385948e-02 1.86260211e-01]]

11.np.vstack()

将两个数组按垂直方向叠加
np.vstack(数组1,数组2)

import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.vstack((a,b)) 
print("c:\n",c)

运行结果如下:

c:
[[1 2 3]
[4 5 6]]

12.np.mgrid[ ]

np.mgrid[ 起始值 : 结束值 : 步长 ,起始值 : 结束值 : 步长 , … ]
x.ravel( ):将x变为一维数组
np.c_[ 数组1,数组2, … ]:使返回的间隔数值点配对

import numpy as np
x, y = np.mgrid [1:3:1, 2:4:0.5] 
grid = np.c_[x.ravel(), y.ravel()]
print("x:",x)
print("y:",y)
print('grid:\n', grid)

运行结果如下:

x = [[1. 1. 1. 1.]
[2. 2. 2. 2.]]
y = [
[2. 2.5 3. 3.5]
[2. 2.5 3. 3.5]]
grid:
[[1. 2. ]
[1. 2.5]
[1. 3. ]
[1. 3.5]
[2. 2. ]
[2. 2.5]
[2. 3. ]
[2. 3.5]]

你可能感兴趣的:(深度学习,tensorflow,python,深度学习)