深度学习-tensorflow-基础(1)误差计算
自动梯度
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
# 创建4 个张量
a = tf.constant(1.)
b = tf.constant(2.)
c = tf.constant(3.)
w = tf.constant(4.)
with tf.GradientTape() as tape:# 构建梯度环境
tape.watch([w]) # 将w 加入梯度跟踪列表
# 构建计算过程
y = a * w**2 + b * w + c
# 求导
[dy_dw] = tape.gradient(y, [w])
print(dy_dw) # 打印出导数
输出
tf.Tensor(10.0, shape=(), dtype=float32)
数据类型
1、标量 x= tf.constant(1.2)
2、张量 x = tf.constant([1,2.,3.3])
3、3维张量 x = tf.constant([[[1,2],[3,4]],[[5,6],[7,8]]]) shape=(2, 2, 2),
4、字符串 x = tf.constant('Hello, Deep Learning.') tf.strings.lower(a)
5、布尔类型 x = tf.constant(True)
6、数值精度 x = tf.constant(123456789, dtype=tf.int16)
7、类型转换 x = tf.cast(x, tf.float32)
8、待优化张量 x = tf.Variable([3, 4])
9、创建张量 Python List, Numpy等
(1) tf.convert_to_tensor([1,2.])
(2)tf.convert_to_tensor(np.array([[1,2.],[3,4]]))
(3)全0 : tf.zeros([]) 全1:tf.ones([]) tf.zeros([1]),tf.ones([1])
(4)自定义数值: tf.fill(shape, value)
(5) 创建已知分布 tf.random.normal(shape, mean=0.0, stddev=1.0)可以创建形状为shape,均值为mean,标准差为stddev 的正态分布𝒩(𝑚𝑒𝑎𝑛, 𝑠𝑡𝑑𝑑𝑒𝑣2)
(6) tf.random.uniform(shape, minval=0, maxval=None, dtype=tf.float32)可以创建采样自[𝑚𝑖𝑛𝑣𝑎𝑙, 𝑚𝑎𝑥𝑣𝑎𝑙]区间的均匀分布的张量 tf.random.uniform([2,2]) 默认[0-1] ,tf.random.uniform([2,2],maxval=10)
10、创建序列 tf.range(1,10,delta=2) <tf.Tensor: id=190, shape=(5,), dtype=int32, numpy=array([1, 3, 5, 7, 9])>
11、4维张量[b,h,w,c] 可以是图片数,高,宽,通道数
12、索引和切片
索引:x = tf.random.normal([4,32,32,3]) x[0]第一张图片数据 x[0][1]第一张的第二行 x[0][1][2], x[0,1,2]第一张第二行第三列
切片:x[1:3]第2,3张,x[0,::],x[:,0:28:2,0:28:2,:]
特别地,step 可以为负数,考虑最特殊的一种例子,step = −1时,start: end: −1表示从start 开始,逆序读取至end 结束(不包含end),索引号𝑒𝑛𝑑 ≤ 𝑠𝑡𝑎𝑟𝑡。
13、维度变换
改变:
x=tf.range(96) x=tf.reshape(x,[2,4,4,3])
在 TensorFlow 中,可以通过张量的ndim 和shape 成员属性获得张量的维度数和形状:In [68]: x.ndim,x.shape
增维度:x = tf.random.uniform([28,28],maxval=10,dtype=tf.int32) x = tf.expand_dims(x,axis=2)
删维度:x = tf.random.uniform([28,28],maxval=10,dtype=tf.int32) x = tf.squeeze(x, axis=0)
交换维度:x = tf.random.normal([2,32,32,3]) tf.transpose(x,perm=[0,3,1,2]) perm表示新的维度List
数据复制:b = tf.constant([1,2]) b = tf.expand_dims(b, axis=0) b = tf.tile(b, multiples=[2,1])
14、加减乘除 整除和余除也是常见的运算之一,分别通过//和%运算符实现 + - * /
15、其他运算 tf.pow(x, a), tf.exp(3.), tf.math.log(x)
16、合并与分割
合并是指将多个张量在某个维度上合并为一个张量
张量的合并可以使用拼接(Concatenate)和堆叠(Stack)操作实现,拼接并不会产生新的维度,而堆叠会创建新维度。
拼接 在TensorFlow 中,可以通过tf.concat(tensors, axis)
a = tf.random.normal([4,35,8])
b = tf.random.normal([6,35,8])
tf.concat([a,b],axis=0)
< shape=(10, 35, 8)> 合并操作可以在任意的维度上进行,唯一的约束是非合并维度的长度必须一致
a = tf.random.normal([35,8])
b = tf.random.normal([35,8])
tf.stack([a,b],axis=0)
<shape=(2, 35, 8)> tf.stack 也需要满足张量堆叠合并条件,它需要所有合并的张量shape 完全一致才可合并
分割
通过 tf.split(x, axis, num_or_size_splits)可以完成张量的分割操作,其中
❑ x:待分割张量
❑ axis:分割的维度索引号
❑ num_or_size_splits:切割方案。当num_or_size_splits 为单个数值时,如10,表示切割为10 份;当num_or_size_splits 为List 时,每个元素表示每份的长度,如[2,4,2,2]表示切割为4 份,每份的 长度分别为2,4,2,2
17、数据统计
(1)范数 L1范数:绝对值的和 L2范数:平方和开根号 无穷范数:元素中绝对值的最大值
可以通过tf.norm(x, ord)求解张量的L1, L2, ∞等范数,其中参数ord指定为1,2 时计算L1, L2 范数,指定为np.inf 时计算∞ −范数
(2)最大最小值、均值、和
通过 tf.reduce_max, tf.reduce_min, tf.reduce_mean, tf.reduce_sum 可以求解张量在某个维度上的最大、最小、均值、和,也可以求全局最大、最小、均值、和信息。
x = tf.random.normal([4,10])
tf.reduce_max(x,axis=1) # 统计概率维度上的最大值,维度1上输出4个最大值
通过 tf.argmax(x, axis),tf.argmin(x, axis)可以求解在axis 轴上,x 的最大值、最小值所在的索引号
18、数据限幅 tf.maximum(x,a) # 上限幅a tf.minimum(x,a) #下限幅a tf.clip_by_value(x,a,b) #上下限幅
19、tf.gather(x, [1,2,4], axis =1) 在axis=1的维度上收集1,2,4属性的值
通过 tf.gather_nd,可以通过指定每次采样的坐标来实现采样多个点的目的,tf.gather_nd(x,[[1,1],[2,2],[3,3]])
20.tf.where
通过 tf.where(𝑐𝑜𝑛𝑑𝑖, 𝑎𝑖 , 𝑏𝑖 )操作可以根据cond 条件的真假从a 或b 中读取数据,条件判定规则如下:
𝑜𝑖 = 𝑎𝑖 𝑐𝑜𝑛𝑑𝑖为𝑇𝑟𝑢𝑒 or 𝑏𝑖 𝑐𝑜𝑛𝑑𝑖为𝐹𝑎𝑙𝑠𝑒
tf.where(cond)来获取索引坐标
21、
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import datasets # 导入经典数据集加载模块
# 加载MNIST 数据集
(x, y), (x_test, y_test) = datasets.mnist.load_data()
print('x:', x.shape, 'y:', y.shape, 'x test:', x_test.shape, 'y test:',y_test)
train_db = tf.data.Dataset.from_tensor_slices((x, y)) #转换成Dataset 对象
文章是摘抄《Tensorflow 深度学习》龙龙老师的书,纯属为了学习做笔记用。