gpt4 book ai didi

python - 如何在 Tensorflow 中计算 Spearman 相关性

转载 作者:行者123 更新时间:2023-11-28 19:00:17 25 4
gpt4 key购买 nike

问题

我需要计算 Pearson 和 Spearman 相关性,并将其用作 tensorflow 中的指标。

对于 Pearson,这是微不足道的:

tf.contrib.metrics.streaming_pearson_correlation(y_pred, y_true)

但对于斯 PIL 曼,我一无所知!

我试过的:

来自 this answer :

    samples = 1
predictions_rank = tf.nn.top_k(y_pred, k=samples, sorted=True, name='prediction_rank').indices
real_rank = tf.nn.top_k(y_true, k=samples, sorted=True, name='real_rank').indices
rank_diffs = predictions_rank - real_rank
rank_diffs_squared_sum = tf.reduce_sum(rank_diffs * rank_diffs)
six = tf.constant(6)
one = tf.constant(1.0)
numerator = tf.cast(six * rank_diffs_squared_sum, dtype=tf.float32)
divider = tf.cast(samples * samples * samples - samples, dtype=tf.float32)
spearman_batch = one - numerator / divider

但是这个返回 NaN...


definition of Wikipedia 之后: enter image description here

我试过了:

size = tf.size(y_pred)
indice_of_ranks_pred = tf.nn.top_k(y_pred, k=size)[1]
indice_of_ranks_label = tf.nn.top_k(y_true, k=size)[1]
rank_pred = tf.nn.top_k(-indice_of_ranks_pred, k=size)[1]
rank_label = tf.nn.top_k(-indice_of_ranks_label, k=size)[1]
rank_pred = tf.to_float(rank_pred)
rank_label = tf.to_float(rank_label)
spearman = tf.contrib.metrics.streaming_pearson_correlation(rank_pred, rank_label)

但是运行这个我得到了以下错误:

tensorflow.python.framework.errors_impl.InvalidArgumentError: input must have at least k columns. Had 1, needed 32

[[{{node metrics/spearman/TopKV2}} = TopKV2[T=DT_FLOAT, sorted=true, _device="/job:localhost/replica:0/task:0/device:CPU:0"](lambda_1/add, metrics/pearson/pearson_r/variance_predictions/Size)]]

最佳答案

您可以做的一件事是使用 Tensorflow 的函数 tf.py_functionscipy.stats.spearmanr 并像这样定义输入和输出:

from scipy.stats import spearmanr
def get_spearman_rankcor(y_true, y_pred):
return ( tf.py_function(spearmanr, [tf.cast(y_pred, tf.float32),
tf.cast(y_true, tf.float32)], Tout = tf.float32) )

关于python - 如何在 Tensorflow 中计算 Spearman 相关性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53404301/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com