gpt4 book ai didi

python - TensorFlow python : Accessing individual elements in a tensor

转载 作者:IT老高 更新时间:2023-10-28 21:35:29 26 4
gpt4 key购买 nike

这个问题与访问张量中的单个元素有关,例如 [[1,2,3]]。我需要访问内部元素 [1,2,3](这可以使用 .eval() 或 sess.run() 执行),但是当张量的大小很大时需要更长的时间)

有什么方法可以更快地做到这一点吗?

提前致谢。

最佳答案

访问张量中元素子集的主要方法有两种,其中任何一种都适用于您的示例。

  1. 使用索引运算符(基于 tf.slice())从张量中提取连续切片。

    input = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

    output = input[0, :]
    print sess.run(output) # ==> [1 2 3]

    索引运算符支持许多与 NumPy 相同的切片规范。

  2. 使用 tf.gather() op 从张量中选择一个不连续的切片。

    input = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

    output = tf.gather(input, 0)
    print sess.run(output) # ==> [1 2 3]

    output = tf.gather(input, [0, 2])
    print sess.run(output) # ==> [[1 2 3] [7 8 9]]

    请注意,tf.gather() 仅允许您选择第 0 维的整个切片(矩阵示例中的整行),因此您可能需要 tf.reshape()tf.transpose()您的输入以获得适当的元素。

关于python - TensorFlow python : Accessing individual elements in a tensor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35146444/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com