如何在张量流中沿轴排列二维张量?

2024-06-28 19:43:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图得到张量流中二维张量的秩。我可以在numpy中使用类似的方法:

import numpy as np
from scipy.stats import rankdata

a = np.array([[0,3,2], [6,5,4]])
ranks = np.apply_along_axis(rankdata, 1, a)

ranks是:

^{pr2}$

我的问题是如何在tensorflow中做到这一点?在

import tensorflow as tf
a = tf.constant([[0,3,2], [6,5,4]])
sess = tf.InteractiveSession()
ranks = magic_function(a)
ranks.eval()

Tags: 方法fromimportnumpytftensorflowasstats
1条回答
网友
1楼 · 发布于 2024-06-28 19:43:48

^{}将适合您,尽管它的语义略有不同。请阅读文档以了解如何将其用于您的案例。但下面是一个片段来解决您的示例:

sess = tf.InteractiveSession()
a = tf.constant(np.array([[0,3,2], [6,5,4]]))
# tf.nn.top_k sorts in ascending order, so negate to switch the sense
_, ranks = tf.nn.top_k(-a, 3)
# top_k outputs 0 based indices, so add 1 to get the same
# effect as rankdata
ranks = ranks + 1
sess.run(ranks)

# output :
# array([[1, 3, 2],
#        [3, 2, 1]], dtype=int32)

相关问题 更多 >