python - TensorFlow:使用一个张量来索引另一个张量

标签 python numpy tensorflow

我有一个关于如何在 TensorFlow 中进行索引的基本问题。

在 numpy 中:

x = np.asarray([1,2,3,3,2,5,6,7,1,3])
e = np.asarray([0,1,0,1,1,1,0,1])
#numpy 
print x * e[x]

我可以得到

[1 0 3 3 0 5 0 7 1 3]

如何在 TensorFlow 中做到这一点?

x = np.asarray([1,2,3,3,2,5,6,7,1,3])
e = np.asarray([0,1,0,1,1,1,0,1])
x_t = tf.constant(x)
e_t = tf.constant(e)
with tf.Session():
    ????

谢谢!

最佳答案

幸运的是,tf.gather() 支持 TensorFlow 中的确切情况。 :

result = x_t * tf.gather(e_t, x_t)

with tf.Session() as sess:
    print sess.run(result)  # ==> 'array([1, 0, 3, 3, 0, 5, 0, 7, 1, 3])'

tf.gather() 操作不如 NumPy's advanced indexing 强大:它仅支持在其第 0 维提取张量的完整切片。已请求支持更通用的索引,并在 this GitHub issue 中进行跟踪.

关于python - TensorFlow:使用一个张量来索引另一个张量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35842598/

相关文章:

python - 如何同时使用字典和数组的 for 循环

python - 计算二维 numpy 数组中的零行

python - 如何在 tf.data.Dataset 中输入不同大小的列表列表

python - 同时恢复和使用多个 tensorflow 模型

python - Scrapy:将参数传递给 cmdline.execute()

Python写unicode字符错误

python - Setupterm 找不到终端,在 Python 程序中使用 curses

python - 如何使用 nditer 迭代每个操作数的第一个维度?

python - 'tensorboard' 不被识别为内部或外部命令,

Python asyncio 简单示例