Tensorflow(十) —— Tensor的排序

1. 主要方法

  • 1、sort / argsort
  • 2、top_k :tf.math.top_k
  • 3、top5 用于ACC

2. sort与argsort

import numpy as np
import pandas as pd
import tensorflow as tf
# **************** sort argsort

# 1print("*"*8,"一维","*"*8)
a = tf.random.shuffle(tf.range(10))
print("a:",a)
b = tf.sort(a,direction = "DESCENDING")
b1 = tf.argsort(a,direction="DESCENDING")
print("b:",b)
print("b1:",b1)
c = tf.sort(a,direction="ASCENDING")
c1 = tf.argsort(a,direction="ASCENDING")
print("c:",c)
print("c1:",c1)
b2 = tf.gather(a,b1)
c2 = tf.gather(a,c1)
print("b2:",b2)
print("c2:",c2)

# 高维
d = tf.random.uniform([3,4],maxval = 100,minval=10,dtype=tf.int32)
print("d:",d)
d1 = tf.sort(d) # 默认对最后一个维度进行ASCENDING
print("d1:",d1)
d2 = tf.argsort(d,axis = 0,direction = "DESCENDING") # 可通过axis轴调整排序依据的轴
print("d2:",d2)

3. top_k

only return top_k values and indices

# *************** top_k
"""
only return top_k values and indices 
"""
a = tf.random.normal([4,3],mean = 50, stddev=16)
a = tf.cast(a,dtype=tf.int32)
print("a:",a)

result = tf.math.top_k(a,2) # 默认为取出按最后个轴排序的前k个值和索引
print("result:",result) # 返回结果为元组
print(result.indices)
print(result.values)

4. Top_k用于Accuracy

"""
prob = [0.1 0.2 0.3 0.4]
label = [2]
only consider top_1 prediction: [3] 0%
only consider top_2 prediction [3 2] 100%
only consider top_3 prediction [3 2 1] 100% 
"""
# 实例 计算top_k的accuracy
prob = tf.convert_to_tensor([[0.1,0.2,0.7],[0.2,0.7,0.1]])
target = tf.constant([2,0])
predict = tf.math.top_k(prob,k = 3).indices # 取出排名前三的概率值的编号
print("predict",predict.numpy())
predict = tf.transpose(predict,[1,0]) # 每列代表一条预测结果
print("predict:",predict.numpy())
target = tf.broadcast_to(target,[3,2])
print("target:",target.numpy())

5. top_k 用于accuracy 的完整案例

def topk_accuracy(output,target,topk = (1,)):
    """
    output:[b,n] b条数据的n个概率值
    target:[b]  b条数据的b个真实值
    topk:元组 可计算多个topk的准确值
    """
    output = tf.constant(output)
    target = tf.constant(target)
    output_ = tf.transpose(tf.math.top_k(output,k = max(topk)).indices,[1,0])
    target_ = tf.broadcast_to(target,output_.shape)
    compare = tf.equal(target_,output_)
    result = []
    for k in topk:
        acc = tf.reduce_sum(tf.cast(compare[:k,:],dtype=tf.float32))/output.shape[0]
        result.append(float(acc))
    return result
output = tf.math.softmax(tf.random.normal([100,10]))
# print("output:",output.numpy())
target = tf.random.uniform([100],maxval=10,minval=0,dtype=tf.int32)
print("target:",target)
acc = topk_accuracy(output,target,[1,2,3,4,5,6,7,8,9,10])
print("Accuracy:",acc)

本文为参考龙龙老师的“深度学习与TensorFlow 2入门实战“课程书写的学习笔记

by CyrusMay 2022 04 16

### 使用TensorFlow实现NDCG@K评估 在机器学习和推荐系统的性能评估中,Normalized Discounted Cumulative Gain (NDCG) 是一种常用的指标,用于衡量排名列表的质量。特别是在Top-K推荐场景下,NDCG@K可以有效反映模型预测的相关性和准确性。 #### 什么是NDCG@K? NDCG是一种加权累积增益的标准化版本,它考虑了不同位置上相关性的权重衰减效应。具体来说,NDCG@K通过以下公式定义: \[ \text{DGC}_k = \sum_{i=1}^{k} \frac{rel_i}{\log_2(i+1)} \] 其中 \( rel_i \) 表示第 \( i \) 位项目的相关性得分。为了使 DCG 的值具有可比性,通常将其除以理想情况下的最大累计增益(IDCG),从而得到 NDCG 值[^6]。 #### TensorFlow中的NDCG@K实现 TensorFlow 提供了一个内置方法来计算 NDCG@K,位于 `tf.metrics` 或者更现代的 API 中可以通过 `tfr.keras.metrics.NDCGMetric` 实现。以下是具体的代码示例: ```python import tensorflow as tf # 定义真实标签和预测分数 true_relevance = [[10, 3, 2], [4, 1, 3]] predicted_scores = [[0.4, 0.8, 0.7], [0.9, 0.5, 0.6]] # 创建NDCG度量对象并设置top_k参数 ndcg_metric = tf.keras.metrics.TopKCategoricalAccuracy(k=2) # 转换数据格式以便于计算 y_true = tf.convert_to_tensor(true_relevance, dtype=tf.float32) y_pred = tf.convert_to_tensor(predicted_scores, dtype=tf.float32) # 更新状态并获取结果 result = ndcg_metric(y_true, y_pred).numpy() print(f"NDCG@2: {result}") ``` 需要注意的是,在实际应用中可以根据需求调整 top-k 参数以及输入张量的形式。如果需要更加灵活或者自定义化的解决方案,则可以直接调用底层操作构建自己的逻辑[^7]。 另外值得注意的一点是在某些复杂网络结构比如涉及图卷积神经网络(GCNs)[^4]的应用场合里,由于存在隐含特征交互等因素的影响,因此对于最终输出层的设计也需要特别注意其适配性问题。 #### 结论 综上所述,利用 TensorFlow 可方便快捷地完成针对 Top-K 排序效果评价的任务——只需简单几步即可获得精确可靠的 NDCG 数值反馈信息作为优化依据之一。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值