Tensorflow python:访问张量中的单个元素 [英] Tensorflow python : Accessing individual elements in a tensor

查看:35
本文介绍了Tensorflow python:访问张量中的单个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This question is with respect to accessing individual elements in a tensor, say [[1,2,3]]. I need to access the inner element [1,2,3] (This can be performed using .eval() or sess.run()) but it takes longer when the size of the tensor is huge)

有没有什么方法可以更快地做同样的事情?

Is there any method to do the same faster?

提前致谢.

推荐答案

有两种主要方法可以访问张量中元素的子集,这两种方法都适用于您的示例.

There are two main ways to access subsets of the elements in a tensor, either of which should work for your example.

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

  1. Use the indexing operator (based on tf.slice()) to extract a contiguous slice from the tensor.

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

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

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

The indexing operator supports many of the same slice specifications as NumPy does.

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

Use the tf.gather() op to select a non-contiguous slice from the tensor.

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() 您的输入以获得适当的元素.

Note that tf.gather() only allows you to select whole slices in the 0th dimension (whole rows in the example of a matrix), so you may need to tf.reshape() or tf.transpose() your input to obtain the appropriate elements.

这篇关于Tensorflow python:访问张量中的单个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆