python - Tensorflow 获取张量中值的索引

标签 python matrix tensorflow

给定一个矩阵和向量,我想找到矩阵对应行中的值的索引。

m = tf.constant([[0, 2, 1],[2, 0, 1]])  # matrix
y = tf.constant([1,2])  # values whose indices should be found

理想的输出是 [2,0],因为 y 的第一个值 1 位于 m 的第一个向量的索引 2 处。 y 的第二个值 2 位于 m 的第二个向量的索引 0 处。

最佳答案

我只找到一个解决方案。但是不知道有没有更好的。

m = tf.constant([[0, 2, 1],[2, 0, 1]])  # matrix
y = tf.constant([1,2])  # values whose indices should be found
y = tf.reshape(y, (y.shape[0], 1))  # [[1], [2]]
cols = tf.where(tf.equal(m, y))[:,-1]  # [2,0]

init = tf.global_variables_initializer()
with tf.Session() as sess:
    init.run()
    print(sess.run(cols))

以上输出:[2, 0]

关于python - Tensorflow 获取张量中值的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47759777/

相关文章:

python - 将 numpy 数组转换为图像

python - 混合使用 UTF-8 和 ASCII 编码?

Python 和 Pandas : a proper way to fetch data from a dataframe and create a new one

python - Tensorflow 的教程 GAN 不适用于 CIFAR-10

machine-learning - 用于读取图像的tensorflow cifar10代码修改

javascript - 如何在 Tensorflow.js 中获取预测值

python - 运行 func(df) 创建新的数据帧并重命名它们

java - 如何逐列而不是逐行填充二维数组

java - 如何在java中转置矩阵(并行/多线程)

C - 将矩阵拆分为均分