TensorFlow:张量排序,填充和复制

一、张量排序
在这里插入图片描述
1.Sort, argsort

1.1一维

a=tf.random.shuffle(tf.range(5))    #numpy = array([2,0,3,4,1])
tf.sort(a,direction='DESCENDING')     #numpy = array([4,3,2,1,0])
tf.argsort(a,direction='DESCENDING')     #numpy = array([3,2,0,4,1])
idx=tf.argsort(a,direction='DESCENDING') 
tf.garther(a,idx)      #numpy = array([4,3,2,1,0])

1.2二维

a=tf.random.uniform([3,3],maxval=10,dtype=tf.int32)   #array([[4,6,8],[9,4,7],[4,5,1]])
tf.sort(a)    #array([[4,6,8],[4,7,9],[5,4,1]])
tf.argsort(a)    #array([[0,1,2],[1,2,0],[2,0,1]])

2.Top_k
Only return top-k values and indices

a=tf.random.uniform([3,3],maxval=10,dtype=tf.int32)   #array([[4,6,8],[9,4,7],[4,5,1]])
res = tf.math.top_k(a,2)
res.indices   #array([[2,1],[0,2],[1,0]])
res.values   #array([[8,6],[9,7],[5,4]])

Top-k Accuracy

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)
	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/batch_size)
		res.append(acc)

	return res

二、填充和复制
在这里插入图片描述
1.pad

a=tf.reshape(tf.range(9),[3,3])
tf.pad(a,[[1,2],[3,4]]) #上1,下2,左3,右4

2.Image padding

a=tf.random.normal([4,28,28,3])
b=tf.pad(a,[[0,0],[2,2],[2,2],[0,0]])
b.shape    #TensorShape([4,32,32,3])

3.tile

a=tf.reshape(tf.range(9),[3,3])  #array([[0,1,2],[3,4,5],[6,7,8]])
tf.tile(a,[1,2])
tf.tile(a,[2,1])
tf.tile(a,[2,2])

4.tile VS broadcast_to

aa=tf.expand_dims(a,axis=0)   #TensorShape([1,3,3])
tf.tile(aa,[2,1,1])   #TensorShape([2,3,3])
tf.broadcast_to(aa,[2,3,3])   #TensorShape([2,3,3])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值