假设我有这两个张量:
valueMatrix
,形状为(?, 3)
,其中?
是批量大小indexMatrix
,形如(?, 1)
我想从 valueMatrix
中包含在 indexMatrix
中的索引处检索值。
示例(伪代码):
valueMatrix = [[7,15,5],[4,6,8]] -- shape=(2,3) -- type=float
indexMatrix = [[1],[0]] -- shape = (2,1) -- type=int
我想从这个例子中做类似的事情:
valueMatrix[indexMatrix] --> returns --> [[15],[4]]
与其他后端相比,我更喜欢 Tensorflow,但答案必须与使用 Lambda 层或其他适合任务的层的 Keras 模型兼容。
最佳答案
import tensorflow as tf
valueMatrix = tf.constant([[7,15,5],[4,6,8]])
indexMatrix = tf.constant([[1],[0]])
# create the row index with tf.range
row_idx = tf.reshape(tf.range(indexMatrix.shape[0]), (-1,1))
# stack with column index
idx = tf.stack([row_idx, indexMatrix], axis=-1)
# extract the elements with gather_nd
values = tf.gather_nd(valueMatrix, idx)
with tf.Session() as sess:
print(sess.run(values))
#[[15]
# [ 4]]
关于python-3.x - Keras 张量 - 使用来自另一个张量的索引获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46526869/