我很抱歉这个冗长乏味的问题很难理解。基本上,我想在tensorflow中实现一个函数:
e.g。 对于具有维度[10,10,7,1]的张量A,以及索引矩阵B = array([[1,3,5],[2,4,6]])。我想根据B的每一行中的索引,提取A中的元素和轴= 2(遵循Python约定,A有0,1,2,3四个轴)。
因此,示例的结果应该是具有维度[10,10,3,2]的张量C,其中第三维是由于根据索引[1,3,5]选择A中的元素沿轴= 2 ]或[2,4,6],第四个维度等于B的第一个维度(即B的行数),因为我们在这个维度上做了两个选择。
任何"张力青睐"在tensorflow中实现这一点的线索,而不是分两步完成?我没有看到使用tf.gather_nd()或tf.gather()的方法。任何的想法?非常感谢!
另一个例子:
A = [[[1], # A is (3, 5, 1)
[2],
[3],
[4],
[5]]],
[[[10],
[20],
[30],
[40],
[50]]],
[[[100],
[200],
[300],
[400],
[500]]]
B = [[1,4,3], # B is (2,3)
[2,3,5]]
C = [[[1, 2], # C is (3, 3, 2)
[4, 3],
[3, 5]]],
[[[10, 20],
[40, 30],
[30, 50]]],
[[[100, 200],
[400, 300],
[300, 500]]]
答案 0 :(得分:1)
B
张量的形状看起来不对,你的问题难以解析。但无论如何,TF在这个问题上并不是很优雅。它需要一个非常特殊的形状B.尝试类似于
import tensorflow as tf
import numpy as np
A = np.random.randn(10, 10, 7, 1).astype(np.float32)
A[0, 0, 1, 0] = 100001
A[0, 0, 3, 0] = 100002
A[0, 0, 5, 0] = 100003
A[0, 0, 2, 0] = 100004
A[0, 0, 4, 0] = 100005
A[0, 0, 6, 0] = 100006
A = tf.convert_to_tensor(A)
sess = tf.InteractiveSession()
B = np.array([
[1, 3, 5],
[2, 4, 6]
])
B = tf.convert_to_tensor(B)
B = tf.reshape(B, [-1])
B = tf.concat([tf.zeros_like(B), tf.zeros_like(B), B, tf.zeros_like(B)], axis=-1)
B = tf.reshape(B, [4, -1])
B = tf.transpose(B, [1, 0])
B = tf.reshape(B, [1, 2, 3, -1])
C = tf.gather_nd(A, B)
C = sess.run(C)
print C.shape
print C
输出
[[[100001. 100002. 100003.]
[100004. 100005. 100006.]]]