【问题标题】:how to get a tensorflow tf by index?如何按索引获取张量流 tf?
【发布时间】:2020-08-19 05:07:59
【问题描述】:
object_for_each_prior = tf.constant([1 for i in range(8732)])
-><tf.Tensor: shape=(8732,), dtype=int32, numpy=array([1, 1, 1, ..., 1, 1, 1], dtype=int32)>

那如果我想得到1148,1149的位置

prior_for_each_object = tf.constant([1148,1149])
object_for_each_prior[prior_for_each_object]

然后我收到以下错误

TypeError: Only integers, slices (`:`), ellipsis (`...`), tf.newaxis (`None`) and scalar tf.int32/tf.int64 tensors are valid indices, got <tf.Tensor: shape=(2,), dtype=int32, numpy=array([1148, 1149], dtype=int32)>

如果我想通过索引获取张量的数字,我应该如何处理它?

【问题讨论】:

    标签: numpy tensorflow tensorflow2.0


    【解决方案1】:

    使用tf.gather_nd 函数来索引张量。 示例如下:

    >>> object_for_each_prior = tf.constant([1 for i in range(8732)])
    >>> prior_for_each_object = tf.gather_nd(object_for_each_prior, indices=[[1148], [1149]])
    >>> prior_for_each_object
    <tf.Tensor: shape=(2,), dtype=int32, numpy=array([1, 1])>
    >>> prior_for_each_object.numpy()
    array([1, 1])
    

    请参阅 this 文档以了解有关 tf.gatherr_nd 的更多信息。

    【讨论】:

    • 你好,谢谢,还有一个问题,如果我想在收集后更改值
      像 tf.gather(object_for_each_prior,prior_for_each_object) = tf.constant([i for i in range (len(prior_for_each_object))])。我该怎么做?
    • 将变量声明为tf.Variale 并使用assign 函数重新赋值。例如:a = tf.Variable([1, 2, 3]) 将 a[0] 重新分配给 3 执行 a[0] .assign(3)
    • 检查this
    猜你喜欢
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    • 2019-01-13
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 2018-01-17
    • 2018-07-02
    相关资源
    最近更新 更多