tensorflow2基础知识
# 创建张量
a = tf.constant(,dtype= ) #可指定数值精度如tf.int32
# 读取精度
print(a.dtype)
#类型转换
tf.cast(a,tf.float64)
# 字符串处理
#小写化 #拼接 #长度 #切分
tf.strings.lower tf.strings.join tf.strings.length tf.strings.split
# 待优化张量
tf.variable()
# 从数组、列表中创建张量
tf.convert_to_tensor # numpy默认保存的是float64位,转换后也是,tensor常用的是float32位,必要时需进行转换
# 创建全0/1张量
tf.zeros([]) tf.ones([])
tf.zeros_like(a) tf.ones_like(a) #创建与a矩阵形状相同的矩阵
#创建自定义数值的张量
tf.fill([2,2],9) # 2*2的矩阵用9填充
# 创建已知分布的张量
tf.random.normal(shape,mean=0.0,stddev=1.0) #创建形状为shape,均值为mean,标准差为stddev的正态分布
tf.random.uniform(shape,minval=0,maxval=none,dtype=tf.float32)#创建采样自最大最小值区间的均匀分布张量
tf.range(start,limit,delta) # [start,limit) 步长为delta
tf.random.truncated_normal([784, 512], stddev=0.1) # 标准正态分布
# 索引与切片
x[1,9,2] # 取第2张图片,第10行,第3列的数据
#以[4,32,32,3]的图片为例
x[::,::,::,::] #最一般形式 当然,也可以用...进行忽略 如x[0:2....,1:]
# 纬度变换
tf.reshape(a,b) #改变视图 改变视图一定要记得原始理解的顺序,方便之后进行恢复
tf.expend_dim(x,axix=2) #增加纬度 [28,28]→[28,28,1]
tf.squeeze(x,axix= ) #删除纬度 若不指定纬度,会删除所有长度为1的纬度
# 交换纬度
tf.transpose(x,[0,3,2,1]) # tensor:[b,h,w,c] pytorch:[b,c,h,w]通道数在前
# 复制数据
tf.tile()
# Broadcast
tf.broadcast_to(a,[]) # 判断是否可以,插入新维度,扩展为相同长度 (看教材理解)
# 数学运算
tf.add()
tf.subtract()
tf.multiply()
tf.dvide #也可直接使用+——*/运算符 //整除 %取余
tf.pow(x,2) or x**2 #乘方
tf.exp(x) #e为底的指数运算
tf.math.log() # e为底的对数运算 若要使用非e的,用换底公式 tf.math.log(x)/tf.math.log(10.)
tf.matmul(a,b) or a @ b # 矩阵相乘
tensorflow2进阶知识
# 合并与分割
tf.concat(tensoe,axis) # 拼接 拼接纬度不等,其他纬度相等 指定拼接纬度
tf.stack(tensoe,axis) # 堆叠 2个数据必须完全一样的shape
tf.unstack(x,axix= ) # 打散全部指定纬度
tf.split(x,num_or_size_splits=[4,2,2,2],axis=0) # 打散,灵活性更强 (指定维度+数量) [10,35,8]>>10个班级分成4,2,2,2个展示
# 数据统计
tf.reduce_max(x,axix) # 最大值
tf.reduce_min(x,axix) # 最小值
tf.reduce_mean(x,axix) # 均值
tf.reduce_mum(x,axix) # 和
tf.argmax(x,axix) # 求最大值的索引号
tf.argmin(x,axix) # 求最小值的索引号
# 张量比较
tf.math.equal(a,b) # a=b
tf.math.greater(a,b) # a>b
tf.math.less(a,b) # a<b
tf.math.greater_equal(a,b) # a>=b
tf.math.less_equal(a,b) # a<=b
tf.math.not_equal(a,b) # a!=b
tf.math.is_nan(a,b) # a=nan 返回ture or false
# 可将结果转换为整型进行统计 tf.cast(out,dtype=tf.int32)
# 填充与复制
tf.pad(s,[[a,b]]) # 一行的左右加
tf.pad(s,[[a,b],[c,d]) # 2维 # 看成在相对于行这块竖着的左右加,再在相对于列进行加
# 上下 左右
tf.tile(x,[2,3,3,1]) # 复制 []内代表复制的次数,如本句话通道数不变,长宽各复制3次,再对照片复制2次
# 数据限幅
tf.maximun(x,a) # x∈[a,+∞]
tf.minimun(x,a) # x∈[-∞,a] # 两个组合可以实现relu函数
tf.clip_by_norm() # 不改变向量方向,只改变模的大小 当网络不稳定或者梯度下降出现问题可考虑
# 高级操作
tf.gether(x,id) # 单维指定索引
tf.gether_nd() # 多维指定索引
tf.boolean_mask(a,mask=[true,false,false],axix=3) # [4,28,28,3] 提取R通道的影像
tf.where(cond,a,b) # 满足条件执行a,不满足执行b 即根据坐标有目的的选择
tf.scatter_nd(id,updates,shape) # 根据坐标有目的的更新
tf.meshgrid(x,y) # 生成坐标系
# 激活函数
tf.sifmoid(x) # 数据>>[0,1]区间 概率或者RGB
tf.nn.relu(x) # 数据<0,让其=0,其梯度永远是1
tf.nn.leaky_relu(x) # 数据小于0的时候设置为较小的某个值而不是0
tf.math.tanh(x) # 数据>>[-1,1]区间
知识扩展(CPU,GPU运算及梯度运算)
# 去除tensorflow运行时出来的无关信息提示
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
# 在CUP/GPU上运行
def cpu_run():
with tf.device('/cpu:0'):
c = tf.matmul(cpu_a, cpu_b)
return c
def gpu_run():
with tf.device('/gpu:0'):
c = tf.matmul(gpu_a, gpu_b)
return c
# 创建梯度计算环境
with tf.GradientTape() as tape:# 构建梯度环境
tape.watch([w]) # 将w加入梯度跟踪列表 注:在tensorflow中若未用tf.variable
# 构建计算过程 进行声明就需要将带训练放到追踪列表中
y = a * w**2 + b * w + c
# 求导
[dy_dw] = tape.gradient(y, [w]) # y对w求偏导
print(dy_dw)
# 实现梯度计算及其实例更新
# with tf.GradientTape() as tape:
# # 第一层计算, [b, 784]@[784, 256] + [256] => [b, 256] + [256] => [b,256] + [b, 256]
# h1 = x @ w1 + tf.broadcast_to(b1, (x.shape[0], 256))
# h1 = tf.nn.relu(h1) # 通过激活函数
# # 第二层计算, [b, 256] => [b, 128]
# h2 = h1 @ w2 + b2
# h2 = tf.nn.relu(h2)
# # 输出层计算, [b, 128] => [b, 10]
# out = h2 @ w3 + b3
# # 计算网络输出与标签之间的均方差, mse = mean(sum(y-out)^2)
# # [b, 10]
# loss = tf.square(y - out)
# # 误差标量, mean: scalar
# loss = tf.reduce_mean(loss)
# # 自动梯度,需要求梯度的张量有[w1, b1, w2, b2, w3, b3]
# grads = tape.gradient(loss, [w1, b1, w2, b2, w3, b3])
# # 梯度更新, assign_sub 将当前值减去参数值,原地更新
# w1.assign_sub(lr * grads[0])
# b1.assign_sub(lr * grads[1])
# w2.assign_sub(lr * grads[2])
# b2.assign_sub(lr * grads[3])
# w3.assign_sub(lr * grads[4])
# b3.assign_sub(lr * grads[5])