python - 对未知秩的张量应用函数(平均倒数秩)

标签 python python-3.x tensorflow

我想为我的模型创建一个新的评估指标(平均倒数排名)。
假设我有:

  • logits形状张量 (None, n_class)
  • y_target形状张量 (None, )包含int值来自0n_class-1 .
  • None将是批量大小。

我希望我的输出是形状为 (None, ) 的张量,相应的 y_target 的倒数排名。 首先,我需要对 logits 中的元素进行排名,然后获取索引 y_target 中元素的排名,最后求其倒数(或 x+1 的倒数,具体取决于排名过程)。

一个简单的例子(针对单个观察):
如果我的y_target=1logits=[0.5, -2.0, 1.1, 3.5] ,
那么排名是logits_rank=[3, 4, 2, 1]
倒数为 1.0 / logits_rank[y_target] = 0.25

这里的挑战是跨轴应用函数,因为排名未知(在图表级别)。 我设法使用 tf.nn.top_k(logits, k=n_class, sorted=True).indices 获得一些结果,但仅限于session.run(sess, feed_dict)内。

任何帮助将不胜感激!

最佳答案

Solved!

 def tf_get_rank_order(input, reciprocal):
    """
    Returns a tensor of the rank of the input tensor's elements.
    rank(highest element) = 1.
    """
    assert isinstance(reciprocal, bool), 'reciprocal has to be bool'
    size = tf.size(input)
    indices_of_ranks = tf.nn.top_k(-input, k=size)[1]
    indices_of_ranks = size - tf.nn.top_k(-indices_of_ranks, k=size)[1]
    if reciprocal:
        indices_of_ranks = tf.cast(indices_of_ranks, tf.float32)
        indices_of_ranks = tf.map_fn(
            lambda x: tf.reciprocal(x), indices_of_ranks, 
            dtype=tf.float32)
        return indices_of_ranks
    else:
        return indices_of_ranks


def get_reciprocal_rank(logits, targets, reciprocal=True):
    """
    Returns a tensor containing the (reciprocal) ranks
    of the logits tensor (wrt the targets tensor).
    The targets tensor should be a 'one hot' vector 
    (otherwise apply one_hot on targets, such that index_mask is a one_hot).
    """
    function_to_map = lambda x: tf_get_rank_order(x, reciprocal=reciprocal)
    ordered_array_dtype = tf.float32 if reciprocal is not None else tf.int32
    ordered_array = tf.map_fn(function_to_map, logits, 
                              dtype=ordered_array_dtype)

    size = int(logits.shape[1])
    index_mask = tf.reshape(
            targets, [-1,size])
    if reciprocal:
        index_mask = tf.cast(index_mask, tf.float32)

    return tf.reduce_sum(ordered_array * index_mask,1)

# use:
recip_rank = tf.reduce_mean(
                 get_reciprocal_rank(logits[-1], 
                                     y_, 
                                     True)

关于python - 对未知秩的张量应用函数(平均倒数秩),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43237262/

相关文章:

python - 按键值查找列表中字典的索引

python - 导入错误: No module named app. core.admin.login

python - 如何使用 sympy.lambdify 和 Max 函数来替换 numpy.maximum 而不是 numpy.amax?

python - 何时在 Python 中使用 io.BytesIO() 修改字符串

Python 数学运算顺序

python - mypy "Optional[Dict[Any, Any]]"在标准过滤器、映射中不可索引

python - 如何从大量数字中生成有偏随机数

python - 如何修复 Tensorflow 中的 "ValueError: Operands could not be broadcast together with shapes (2592,) (4,)"?

TensorFlow:在部分加载预训练权重后使用 tf.global_variables_initializer()

python - 使用tensorflow求解代数时,训练后所有变量都变成了nan