1 合并与分割
#concat
a=tf.ones([4, 35, 8])
b=tf.ones([2, 35, 8])
c=tf.concat([a, b], axis=0)
#stack:create new dim
d=tf.ones([4, 35, 8])
e=tf.stack([a, d], axis=0) # [2, 4, 35, 8]), 两者维度必须相等
#unstack:在指定维度上进行拆分,将其拆分为指定维度个list
aa, dd=tf.unstack(e, axis=0)
aa.shape, dd.shape # [4, 35, 8] [4, 35, 8]
res=tf.unstack(e, axis=3) # res是一个list, 长度为8
res[0].shape, res[7].shape # [2, 4, 35] [2, 4, 35]
#split:指定打散的长度
res=tf.split(e, axis=3, num_or_size_splits=2)
res[0].shape, res[1].shape # [2, 4, 35, 4] [2, 4, 35, 4]
res=tf.split(e, axis=3, num_or_size_splits=[2, 2, 4]
res[0].shape, res[2].shape # [2, 4, 35, 2] [2, 4, 35, 4]
2 数据统计
#norm
a=tf.ones([2, 2])
tf.norm(a) # L2范数
tf.norm(a, ord=1) # L1范数
tf.norm(a, ord=1, axis=1) # 指定轴上求解 [1.414, 1.414]
#reduce_min/max/mean
a=tf.random.normal([4, 10])
tf.reduce_min(a) # 全局最小值,shape=()
tf.reduce_min(a, axis=1) # shape=(4, )
#argmax/argmin
tf.argmax(a, axis=0) # shape=(10, )
#tf.equal: 逐元素的比较
a=tf.constant([1, 2, 3, 2, 5])
b=tf.range(5)
res=tf.equal(a, b) # dtype=bool, [False, False, False, False, False]
tf.reduce_sum(tf.cast(res, dtype=tf.int32))
#accuracy
pred=tf.cast(tf.argmax(a, axis=1), dtype=tf.int32)
correct=tf.reduce_sum(tf.cast(tf.equal(a, pred), dtype=tf.int32))
#tf.unique
a=tf.constant([4, 2, 2, 4, 3])
y, idx=tf,unique(a) # y:[4, 2, 3] idx:[0, 1, 1, 0, 2] 原始元素在unique后的索引
tf.gather(y, idx) # 还原到a
3 张量排序
#sort/argsort
a=tf.random.shuffle(tf.range(5))
tf.sort(a, direction='DECENDING')
idx=tf.argsort(a, direction='DECENDING')
tf.gather(a, idx)
a=tf.random.uniform([3, 3], maxval=10, dtype=tf.int32)
idx=tf.argsort(a, axis=0, direction='DECENDING')
#top_k: only return top_k values and indices
res=tf.math.top_k(a, 2)
res.values, res.indices # shape=(3, 2)
#top_k accuracy: 前k个最大概率中有一个预测对了,就认为预测正确
def accuracy(output, target, top_k=(1, ))
maxk=max(top_k)
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)
correct=tf.equal(pred, target)
res=[]
for k in top_k:
correct_k=tf.cast(tf.reshape(correct[:k], [-1]), tf.float32)
correct_k=tf.reduce_sum(correct_k)
acc=float(correct_k/batch_size)
res.append(acc)
return res
4 填充与复制
#pad
a=tf.reshape(tf.range(8), [3, 3])
tf.pad(a, [[1, 0], [0, 1]]) # 第一个维度为行,第二个维度为列,在第一行上方补0,在最后一列右方补0
#iimage padding
a=tf.random.normal([4, 28, 28, 3])
b=tf.pad(a, [[0, 0], [2, 2], [2, 2], [0, 0]])
#tile:repeat data along dim n times
tf.tile(a, [1, 2]) # 第一个维度不复制,第二个维度复制两次 shape=(3, 6)
tf.tile(a, [2, 2]) # shape=(6, 6) 先复制小维度,再复制大维度
5 张量限幅
#clip_by_value, clip_by_norm, gradient clipping, relu
#clip_by_value:在区间限幅
a=tf.range(10)
tf.maximun(a, 2) # 单边限制,将最小值限制在2
tf.minimun(a, 8)
tf.clip_by_value(a, 2, 8) # 限制在2-8之间
#relu
tf.nn.relu(a) # 等价于 tf.maximun(a, 0)
#clip_by_norm: 不改变tensor方向,大小减小了
a=tf.random.norm([2, 2], mean=10)
n=tf.norm(a) # 22.14
aa=tf.clip_by_norm(a, 15)
#gradient clipping
new_grads, total_norm=tf.clip_by_global_norm(grads, 25) # total_norm 为为裁剪前的梯度范数
6高级特性
#where
a=tf.random.normal([3, 3])
mask=a>0
tf.boolean_mask(a, mask) # shape=(5, ) 为大于0的元素
indices=tf.where(a) # shape=(5, 2) 为大于0元素坐标
tf.gather_nd(a, indices) # shape=(5, ) 为大于0的元素
#where(cond, A, B)
A=tf.ones([3, 3])
B=tf.zeros([3, 3])
tf.where(mask, A, B) # if True, 取A中的值,if False, 取B中的值
#scatter_nd: 在全零的底板上更新值
#tf.scatter_nd(indices, updates, shape)
indices=tf.constant([[4], [3], [1], [7]]) # 更新的坐标
updates=tf.constant([9, 10, 11, 12]) # 更新的内容
shape=tf.constant([8]) # 底板
tf.scatter_nd(indices, updates, shape) # [0, 11, 0, 10, 9, 0, 0, 12]
#n_d
indices=tf.constant([[0], [2]])
updates=tf.ones([2, 4, 4])
shape=tf.constant([4, 4, 4])
tf.scatter_nd(indices, updates, shape)
#meshgrid
#生成点坐标:x:[-2, 2] y:[-2, 2] points:[N, 2]
x=tf.linspace(-2., 2, 5)
y=tf.linspace(-2., 2, 5)
points_x, points_y=tf.meshgrid(x, y) # shape=(5, 5) 将每个点的坐标分开了,分别为x坐标和y坐标
points=tf.stack([points_x, points_y], axis=2) # shape=(5, 5, 2)
#画等高线:z=sin(x)+sin(y)
def func(x):
z=tf.math.sin(x[..., 0])+tf.math.sin(x[..., 1])
return z
x=tf.linspace(0, 2*3.14, 500)
y=tf.linspace(0, 2*3.14, 500)
points_x, points_y=tf.meshgrid(x, y)
points=tf.stack([points_x, points_y], axis=2)
z=func(points)
plt.contour(points_x, points_y, z)
plt.show()