本篇记录一下TensorFlow中张量的排序方法

tf.sort和tf.argsort

# 声明tensor a是由1到5打乱顺序组成的
a = tf.random.shuffle(tf.range(5))
# 打印排序后的tensor
print(tf.sort(a,direction='DESCENDING').numpy())
# 打印从大到小排序后,数字对应原来的索引
print(tf.argsort(a,direction='DESCENDING').numpy())
index = tf.argsort(a,direction='DESCENDING')
# 按照索引序列取值
print(tf.gather(a,index)) # 返回最大的两个值信息
res = tf.math.top_k(a,2)
# indices返回索引
print(res.indices)
# values返回值
print(res.values)

计算准确率实例:

# 定义模型输出预测概率
prob = tf.constant([[0.1,0.2,0.7],[0.2,0.7,0.1]])
# 定义y标签
target = tf.constant([2,0])
# 求top3的索引
k_b = tf.math.top_k(prob,3).indices
# 将矩阵进行转置,即把top-1,top-2,top-3分组
print(tf.transpose(k_b,[1,0]))
# 将y标签扩展成与top矩阵相同维度的tensor,方便比较
target = tf.broadcast_to(target,[3,2]) # 实现求准确率的方法
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
import  tensorflow as tf
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = ''
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)

tensorflow张量排序的更多相关文章

  1. AI - TensorFlow - 张量(Tensor)

    张量(Tensor) 在Tensorflow中,变量统一称作张量(Tensor). 张量(Tensor)是任意维度的数组. 0阶张量:纯量或标量 (scalar), 也就是一个数值,例如,\'Howd ...

  2. Tensorflow张量

    张量常规解释 张量(tensor)理论是数学的一个分支学科,在力学中有重要应用.张量这一术语起源于力学,它最初是用来表示弹性介质中各点应力状态的,后来张量理论发展成为力学和物理学的一个有力的数学工具. ...

  3. tensorflow 张量的阶、形状、数据类型及None在tensor中表示的意思。

    x = tf.placeholder(tf.float32, [None, 784]) x isn't a specific value. It's a placeholder, a value th ...

  4. TensorFlow—张量运算仿真神经网络的运行

    import tensorflow as tf import numpy as np ts_norm=tf.random_normal([]) with tf.Session() as sess: n ...

  5. Tensorflow张量的形状表示方法

    对输入或输出而言: 一个张量的形状为a x b x c x d,实际写出这个张量时: 最外层括号[…]表示这个是一个张量,无别的意义! 次外层括号有a个,表示这个张量里有a个样本 再往内的括号有b个, ...

  6. 121、TensorFlow张量命名

    # tf.Graph对象定义了一个命名空间对于它自身包含的tf.Operation对象 # TensorFlow自动选择一个独一无二的名字,对于数据流图中的每一个操作 # 但是给操作添加一个描述性的名 ...

  7. tensorflow张量限幅

    本篇内容有clip_by_value.clip_by_norm.gradient clipping 1.tf.clip_by_value a = tf.range(10) print(a) # if ...

  8. 吴裕雄--天生自然TensorFlow2教程:张量排序

    import tensorflow as tf a = tf.random.shuffle(tf.range(5)) a tf.sort(a, direction='DESCENDING') # 返回 ...

  9. Tensorflow Lite从入门到精通

    TensorFlow Lite 是 TensorFlow 在移动和 IoT 等边缘设备端的解决方案,提供了 Java.Python 和 C++ API 库,可以运行在 Android.iOS 和 Ra ...

随机推荐

  1. JDK11和JDK8类加载器的区别

    如下代码: public class Test07 { public static void main(String[] args) throws ClassNotFoundException { / ...

  2. Educational Codeforces Round 39 Editorial B(Euclid算法,连续-=与%=的效率)

    You have two variables a and b. Consider the following sequence of actions performed with these vari ...

  3. SpringBoot笔记一----配置文件

    1.父类指定了相应的依赖的版本,之后子工程只需要添加该依赖即可,无需指定版本,实现版本管理. 2.SpringBootApplication注解创建一个application,并且会将同包之下的文件都 ...

  4. LeetCode 343.整数拆分 - JavaScript

    题目描述:给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化. 返回你可以获得的最大乘积. 题目分析 题目中"n 至少可以拆分为两个正整数的和",这个条件说 ...

  5. 搭建grafana+telegraf+influxdb服务器性能监控平台

    最近在学习性能测试,了解到一套系统资源使用率低的监控环境,也就是grafana+telegraf+influxdb. InfluxDB是一款优秀的时间序列数据库,适合存储设备性能.日志.物联网传感器等 ...

  6. windows下python3使用pip安装scrapy提示安装失败

    我的环境:     python3.6,     win10,      原因:不能成功安装twisted,因为twisted与高版本的python有兼容问题. 解决:1,先下载twisted二进制文 ...

  7. 联合索引在B+树上的存储结构及数据查找方式

    能坚持别人不能坚持的,才能拥有别人未曾拥有的.关注编程大道公众号,让我们一同坚持心中所想,一起成长!! 引言 上一篇文章<MySQL索引那些事>主要讲了MySQL索引的底层原理,且对比了B ...

  8. git系列之---工作中项目的常用git操作

    0.本地git的安装 官网下载 1.git 配置 git config user.name  查看 用户名 git config user.email   查看 邮箱 git config --glo ...

  9. Python爬虫连载10-Requests模块、Proxy代理

    一.Request模块 1.HTTP for Humans,更简洁更友好 2.继承了urllib所有的特征 3.底层使用的是urllib3 4.​开源地址:https://github.com/req ...

  10. 异常 lock buffer failed for format 0x23

    02-11 21:21:45.669625 14804 14815 W Monkey : // java.lang.RuntimeException: lock buffer failed for f ...