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

TensorFlow2.1基本概念与常用函数_第1张图片

基本概念

  TensorFlow中的Tensor表示张量,是多维数组、多维列表,用表示张量的维数。张量的阶数与方括号的数量相同。张量可以表示0阶到n阶的数组。
TensorFlow2.1基本概念与常用函数_第2张图片

  TensorFlow中数据类型包括32位整型(tf.int32)、32位浮点(tf.float32)、64位浮点(tf.float64)、布尔型(tf.bool)、字符串型(tf.string)。

创建张量的方法

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

import tensorflowas tfa=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,)

注:去掉dtype项,不同电脑环境不同导致默认值不同,可能导致后续程序bug

2. 将numpy的数据类型转换为Tensor数据类型

  很多时候数据是由numpy格式给出的,此时可以通过如下函数将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)

3. 采用不同函数创建不同值的张量

  • tf. zeros(维度):创建全为0的张量;
  • tf.ones(维度):创建全为1的张量;
  • tf. fill(维度,指定值):创建全为指定值的张量。

其中维度参数部分,如一维则直接写个数,二维用[行,列]表示,多维用[n,m,j…]表示。

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)

4. 采用不同函数创建符合不同分布的张量

  • tf. random.normal (维度,mean=均值,stddev=标准差):生成正态分布的随机数,默认均值为0,标准差为1;
  • tf. random.truncated_normal (维度,mean=均值,stddev=标准差):生成截断式正态分布的随机数,能使生成的这些随机数更集中一些,如果随机生成数据的取值在 ( μ − 2 σ , μ + 2 σ ) (\mu-2\sigma,\mu+2\sigma) (μ2σ,μ+2σ)之外,则重新进行生成,保证了生成值在均值附近;
    σ = ∑ i = 1 n ( x i − x ˉ ) 2 n \sigma=\sqrt{\frac{\sum_{i=1}^n(x_i-\bar{x})^2}{n}} σ=ni=1n(xixˉ)2
  • tf. random. uniform(维度,minval=最小值,maxval=最大值):生成指定维度的均匀分布随机数,用minval给定随机数的最小值,用maxval给定随机数的最大值,最小、最大值是前闭后开区间。
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)
f = tf.random.uniform([2, 2], minval=0, maxval=1)
print(f)

运行结果:

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)
tf.Tensor([[0.28219545 0.15581512]
[0.77972126 0.47817433]], shape=(2, 2), dtype=float32)

TensorFlow常用函数

tf.cast

  • tf.cast (张量名,dtype=数据类型):强制tensor转换为该数据类型
x1 = tf.constant ([1., 2., 3.], dtype=tf.float64)
print(x1)
x2 = tf.cast (x1, tf.int32)
print(x2)

运行结果:

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

计算张量沿指定维度的最大值/最小值/平均值/和

  • tf.reduce_min (张量名):计算张量维度上元素的最小值;
  • tf.reduce_max (张量名):计算张量维度上元素的最大值;
  • tf.reduce_mean (张量名,axis=操作轴):计算张量沿着指定维度的平均值;
  • tf.reduce_sum (张量名,axis=操作轴):计算张量沿着指定维度的和。
print (tf.reduce_min(x2), tf.reduce_max(x2))

运行结果:

tf.Tensor(1, shape=(), dtype=int32)
tf.Tensor(3, shape=(), dtype=intt32)

维度理解:对于一个二维张量,如果axis=0表示纵向操作(沿经度方向) ,axis=1 表示横向操作(沿纬度方向)。如果不指定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) #横向求和,两行分别为6和7

标记“可训练”的变量

  利用tf.Variable(initial_value,trainable,validate_shape,name)函数可以将变量标记为“可训练”的,被它标记了的变量,会在反向传播中记录自己的梯度信息。

  • initial_value:默认为None,可以搭配tensorflow随机生成函数来初始化参数;
  • trainable:默认为True,表示可以后期被算法优化的,如果不想该变量被优化,即改为False;
  • validate_shape:默认为True,形状不接受更改,如果需要更改,validate_shape=False;
  • name:默认为None,给变量确定名称。
w = tf.Variable(tf.random.normal([2, 2], mean=0, stddev=1))

  该语句表示首先随机生成正态分布随机数,再给生成的随机数标记为可训练,这样在反向传播中就可以通过梯度下降更新参数w了。

TensorFlow中的数学运算

对应元素的四则运算

  • tf.add (张量1,张量2):实现两个张量的对应元素相加;
  • tf.subtract (张量1,张量2):实现两个张量的对应元素相减;
  • tf.multiply (张量1,张量2):实现两个张量的对应元素相乘;
  • 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)

幂次运算

  • tf.square (张量名):计算某个张量的平方;
  • tf.pow (张量名,n次方数):计算某个张量的n次方;
  • 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)

tf.matmul矩阵相乘

  • 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)

tf.data.Dataset.from_tensor_slices生成输入特征/标签对

  tf.data.Dataset.from_tensor_slices((输入特征, 标签))切分传入张量的第一维度,生成输入特征/标签对,构建数据集,此函数对Tensor格式与Numpy格式均适用,其切分的是第一维度,表征数据集中数据的数量,之后切分batch等操作都以第一维为基础。

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>)

tf.GradientTape( )函数搭配with结构计算损失函数在某一张量处的梯度

  with结构记录计算过程,gradient求出张量的梯度:
在这里插入图片描述

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

运行结果:

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

tf.one_hot独热编码

独热编码(one-hot encoding):在分类问题中,常用独热码做标签,标记类别:1表示是,0表示非。
TensorFlow2.1基本概念与常用函数_第3张图片

  tf.one_hot(待转换数据,depth=几分类)将待转换数据,转换为one-hot形式的数据输出。

classes = 3
labels = tf.constant([1,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)

  索引从0开始,待转换数据中各元素值应小于depth,若带转换元素值大于等于depth,则该元素输出编码为[0, 0 … 0, 0]。即depth确定列数,待转换元素的个数确定行数

classes = 3
labels = tf.constant([1,4,2]) # 输入的元素值4超出depth-1
output = tf.one_hot(labels,depth=classes)
print(output)

运行结果:

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

tf.nn.softmax

  tf.nn.softmax( )函数使前向传播的输出值符合概率分布,进而与独热码形式的标签作比较,其中 y i y_i yi是前向传播的输出。
s o f t m a x ( y i ) = e y i ∑ j = 0 n e y i softmax(y_i)=\frac{e^{y_i}}{\sum_{j=0}^ne^{y_i}} softmax(yi)=j=0neyieyi

TensorFlow2.1基本概念与常用函数_第4张图片

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

运行结果:

After softmax, y_prois: tf.Tensor([0.255981740.695830460.0481878], shape=(3,), dtype=float32)

assign_sub参数自更新

  • w.assign_sub(w要自减的内容):赋值操作,更新参数的值并返回。
  • 调用assign_sub前,先用tf.Variable定义变量w为可训练(可自更新)。
w = tf.Variable(4)
w.assign_sub(1)
print(w)

运行结果:

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

tf.argmax

  tf.argmax (张量名,axis=操作轴)返回张量沿指定维度最大值的索引。

import numpyas 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)

tf.where

  tf.where(条件语句,真返回A,假返回B):条件语句为真返回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)

Python、Numpy常用函数

enumerate

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

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

运行结果:

0 one
1 two
2 three

np.random.RandomState.rand()

  • np.random.RandomState.rand(维度):返回一个[0,1)之间的随机数。维度为空,返回标量。
import numpyas 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]]

np.vstack()

  • np.vstack(数组1,数组2):将两个数组按垂直方向叠加。
import numpyas 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]]

np.mgrid[ ] 、np.ravel( )、 np.c_[ ]

  • np.mgrid[ 起始值: 结束值: 步长,起始值: 结束值: 步长, … ]:[起始值结束值);
  • x.ravel( ) :将x变为一维数组,“把.前变量拉直”;
  • np.c_[ 数组1,数组2,… ]:使返回的间隔数值点配对。
import numpyas 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笔记

你可能感兴趣的:(深度学习框架)