【问题标题】:How can I get specific rows of a tensor in TensorFlow?如何在 TensorFlow 中获取张量的特定行?
【发布时间】:2016-07-19 20:55:34
【问题描述】:

我有几个张量:

logits:这个张量包含最终的预测分数。

tf.Tensor 'MemN2N_1/MatMul_3:0' shape=(?, 18230) dtype=float32

最终预测计算为 predict_op = tf.argmax(logits, 1, name="predict_op")

现在我想将预测限制在某些特定列中。以下两个张量包含我要从中选择的列索引。

self._stories 属于类型

tf.Tensor 'stories:0' shape=(?, 12, 110) dtype=int32

self._queries 的类型是

tf.Tensor 'queries:0' shape=(?, 110) dtype=int32

这里的 110 列是我想限制 logits 的索引号。例如,如果 logits = [[10,20,30,40,50], [10,20,30,40,50]..] 和 self._stories = [[[1,4,...], [1,2,4,...],...], [[0,4,...],[2,4...],...]...] 和 self._queries = [[1,4...],[2,4,...],...] 那么 logits 应该看起来像 [[20,30,50],[10,30,50]...]

如何在 tensorflow 中进行这种索引过滤?

【问题讨论】:

    标签: python numpy tensorflow


    【解决方案1】:

    你试过tf.equal吗?这将比较两个张量并创建一个新的张量,其中包含相等的 True 和不相等的 False。

    使用这个 bool-tensor,您可以输入 tf.select,它会根据您在第一步中创建的 bool-value 从一个或另一个张量中选择元素。

    没有深入研究您提供的特定形状,但是通过这两个操作,您可以创建您要求的那种流。

    【讨论】:

      【解决方案2】:

      试试tf.gather

      row_indices = [1]
      row = tf.gather(tf.constant([[1, 2],[3, 4]]), row_indices)
      tf.Session().run(row)  # returns [[3, 4]]
      

      您可以使用tf.squeeze 删除大小为 1 的前导维度:

      row = tf.squeeze(row, squeeze_dims=0)
      

      【讨论】:

        【解决方案3】:

        你可以使用 tf.slice(input_, begin, size, name=None)。 有关详细信息,请参阅 TensorFlow 文档: https://www.tensorflow.org/api_docs/python/tf/slice

        【讨论】:

        • 嗨,请您提供链接周围的上下文,以防万一它中断?谢谢!
        猜你喜欢
        • 2019-12-18
        • 1970-01-01
        • 2020-02-13
        • 2020-06-22
        • 1970-01-01
        • 2020-02-03
        • 1970-01-01
        • 1970-01-01
        • 2019-01-13
        相关资源
        最近更新 更多