tensorflow基本操作

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)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值