文章目录
tensorflow张量排序实例
output = tf.random.normal([10,6])# 随机生成一个正态分布
output
output = tf.math.softmax(output, axis = 1)# 使这六类的概率和为1
output
print('prob:',output.numpy())
target = tf.random.uniform([10],maxval = 6,dtype = tf.int32)# 生成一个随机的lable
target
pred = tf.argmax(output,axis = 1)
print('pred:',pred.numpy())
print('lable:',target.numpy())
计算准确度
topk = (1,2,3,4,5,6)
maxk = max(topk)
batch_size = target.shape[0]
print(batch_size)
结果:10
pred = tf.math.top_k(output,maxk).indices
print(pred.numpy())
pred = tf.transpose(pred,perm = [1,0])
target_ = tf.broadcast_to(target, pred.shape)
print(target_.numpy())
correct = tf.equal(pred,target_)
print(correct.numpy())
res = []
print(correct[:1])
#tf.reshape() -1所代表的含义是我们不用亲自去指定这一维的大小,
#函数会自动进行计算,但是列表中只能存在一个-1。
#(如果存在多个-1,就是一个存在多解的方程)
correct_1 = tf.cast(tf.reshape(correct[:1],[-1]),dtype = tf.float32)
print(correct_1.numpy())
correct_1 = tf.reduce_sum(correct_1)
print(correct_1.numpy())
acc = float(correct_1*(100.0/batch_size))
print(acc)
res.append(acc)
print(res)
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)
print(res)