我需要使用我拥有的另一个索引列表访问张量的元素,但目前使用简单的语法似乎不可能。我不确定它是否是一个错误,所以我把它贴在这里希望能修复我的语法。我的代码是:
import tensorflow as tf
import numpy as np
sess = tf.Session()
input = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
idx_list = np.array([0,2])
output = input[:, idx_list]
print(sess.run(output))
但我收到错误:
ValueError:形状必须具有相同的等级,但是 0 和 1 来自将形状 0 与其他形状合并。对于具有输入形状的“strided_slice/stack_1”(操作:“Pack”):[], [2]。
我安装的 tensorflow 版本是 tensorflow-1.1.0-cp35(pip 安装)。
更新:
我通过 tf.fn_map 执行此操作,但我真的怀疑这是进行索引的正确方法:
output = tf.transpose(tf.map_fn(lambda x: input[:,x], idx_list),perm=[1,0])
更新:
在最新的评论中有一个很好的片段注册了一个特定的问题,这可能会有所帮助。同时这个操作并不像 numpy 那样简单......
您可以使用tf.gather
和 执行tf.transpose
以下操作:
import tensorflow as tf
import numpy as np
sess = tf.Session()
input = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
idx_list = np.array([0,2])
output = tf.transpose(tf.gather(tf.transpose(input),idx_list))
output.eval(session=sess)
这打印
array([[1, 3],
[4, 6],
[7, 9]])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句