【问题标题】:Tensorflow access elements in tensor using tenors on indicesTensorflow 使用索引上的 Tenor 访问张量中的元素
【发布时间】:2018-07-04 15:39:41
【问题描述】:

如何使用张量索引访问 tensorflow Tensor 中的 Tenor 元素,如下所示:

import tensorflow as tf
import numpy as np

# indexing in numpy [Working]
matrix = np.random.randint(0, 10, [100, 100])
indices = np.random.randint(0, 100, [1000, 100])
elements = matrix[indices[:, 0], indices[:, 1]]

# indexing in tensorflow [Not working]
tf_matrix = tf.constant(matrix, dtype=tf.int32)
tf_indices = tf.constant(indices, dtype=tf.int32)
tf_elements = tf_matrix[tf_indices[:, 0], tf_indices[:, 1]]  # Error

session = tf.Session()
session.run(tf_elements)

我收到以下错误:

tensorflow.python.framework.errors_impl.InvalidArgumentError:形状 必须是 1 级,但对于 'strided_slice_2' 是 2 级(操作: 'StridedSlice') 输入形状:[100,100]、[2,1000]、[2,1000]、[2]。

ValueError:形状必须为 1 级,但对于“strided_slice_2”为 2 级 (op: 'StridedSlice') 输入形状:[100,100], [2,1000], [2,1000], [2]。

【问题讨论】:

    标签: python numpy tensorflow indexing


    【解决方案1】:
    tf_elements = tf.gather_nd(tf_matrix, tf_indices[:, 0:2])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-02
      • 2021-01-05
      • 1970-01-01
      • 2021-09-14
      相关资源
      最近更新 更多