tensorflow 高阶操作
1、合并与分割
- tf.concat
- tf.split
- tf.stack
- tf.unstack
tf.concat
c=tf.concat([a,b],axis=0) #竖着拼
d=tf.concat([a,b],axis=1) #横着拼
- axis=0,沿着列方向拼接
- axis=1,沿着行方向拼接
合并后不会增加维度
stack, 会增加新的维度
axis指定新维度的位置
大维度放在前面更容易理解
dim mismatch
- concat,除了拼接的维度都要相等
- stack:每个维度都必须相等
unstack
不一定要在原来stack的轴上做分割
split 指定打散的数量
指定维度,指定分割数量。
2、数据统计
- tf.norm
- tf.reduce_min/max
- tf.argmax/argmin
- tf.equal
- tf.unique
tf.norm
只讨论向量的范数
也可以指定维度求解
reduce_min/max/mean
- axis=1,对每一行求解
- axis=0,对每一列求解
- 不指定求全局的最大/最小/平均值
argmax/argmin
返回最大值或者最小值的索引
默认axis=0
index为整型
tf.equal
每一个位置返回布尔值
res=tf.equal(a,b)
tf.reduce_sum(tf.cast(res,dtype=int32))#将bool转为int值,统计为true的个数
求解accuracy
- 对于每一个结果用argmax找到最大概率的索引
- 使用tf.equal对比预测值和真实值
- 将bool类型转为int类型,再求和c
- 将预测对的除以所有预测的得到accuracy
tf.unique 去除重复
返回两个部分,前一个是不重复的值得array,后一个是原tensor里每一个值对应的载不前一个array中的index
3、张量排序
- sort/argsort
- topk
- top-5Acc.
sort ,argsort
对于高维得tensor
默认为axis=1,即最后得tensor
Top_k
only return top_k values and indices
top-k accuracy
不止考虑概率最大的预测值,
top-1得accuracy是要求最严格的。
有时会使用top-5得预测,即在1000个分类问题中,取前五个概率最大的看预测是否正确
如何计算top accuracy
- 将top-1.-2.-3得预测值按预测个数分开分别与真实值做对比
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
tf.random.set_seed(2467)
def accuracy(output, target, topk=(1,)):
maxk = max(topk)
batch_size = target.shape[0]
pred = tf.math.top_k(output, maxk).indices
pred = tf.transpose(pred, perm=[1, 0])
target_ = tf.broadcast_to(target, pred.shape)
# [10, b]
correct = tf.equal(pred, target_)
res = []
for k in topk:
correct_k = tf.cast(tf.reshape(correct[:k], [-1]), dtype=tf.float32)
correct_k = tf.reduce_sum(correct_k)
acc = float(correct_k* (100.0 / batch_size) )
res.append(acc)
return res
output = tf.random.normal([10, 6])
output = tf.math.softmax(output, axis=1)
target = tf.random.uniform([10], maxval=6, dtype=tf.int32)
print('prob:', output.numpy())
pred = tf.argmax(output, axis=1)
print('pred:', pred.numpy())
print('label:', target.numpy())
acc = accuracy(output, target, topk=(1,2,3,4,5,6))
print('top-1-6 acc:', acc)
4、填充与复制
- pad
- tile
- broadcast_to