【问题标题】:Indexing Matrix in TensorFlowTensorFlow 中的索引矩阵
【发布时间】:2016-08-27 14:41:29
【问题描述】:

例如,在 Numpy 中,我可以得到一些这样的值。

d = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
# array([[0, 1, 2],
#        [3, 4, 5],
#        [6, 7, 8]])

d[[0, 1, 2], [2, 1, 0]]
# array([2, 4, 6])

所以我可以检索 [2, 4, 6]。

如何在 TensorFlow 中做同样的事情?

x = tf.Variable([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
init_op = tf.initialize_all_variables()
with tf.Session() as sess:
    sess.run(init_op)

print sess.run([x[[0, 1, 2], [2,1,0]]])[0]

它引发类型错误

TypeError: Bad slice index [0, 1, 2] of type <type 'list'>

我的问题是如何通过 TensorFlow 获得相同的值?

print sess.run([x[[0, 1, 2], [2,1,0]]])[0]

【问题讨论】:

    标签: python numpy neural-network tensorflow


    【解决方案1】:

    我找到的一个解决方案是使用gather_nd 函数。

    sess.run([tf.gather_nd(x, [[0, 2], [1, 1], [2, 0]])])
    # [3 5 7]
    

    还有其他功能吗?一个更类似于 TensorFlow 中的 Numpy 的函数?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-19
      • 1970-01-01
      • 1970-01-01
      • 2012-11-06
      • 1970-01-01
      • 1970-01-01
      • 2016-02-05
      • 1970-01-01
      相关资源
      最近更新 更多