什么是这个numpy数组排列的TensorFlow等价物?

时间:2017-03-20 23:19:50

标签: python numpy tensorflow

我需要根据给定的索引来置换TF中张量的元素。从2个数组a和b(索引),我需要计算一个新的数组,根据b中的索引来置换a中的元素。对于空的索引,它应该填充NA(或等效的)。

例如,

a = [10, 20, 30]  
b = [-1,  0,  3]  
output = [ 10,  20,   NA,   NA,  30] 

我需要编写与以下numpy数组相同的代码,但是对于TF张量。

a = np.array([10,20,30])
b = np.array([-1,0,3])
mini = abs(np.min(b))
maxi = abs(np.max(b))
output = np.zeros(maxi+mini+1)
for ai,bi in zip(a,b):
    output[bi+mini]= ai

如何使用TensorFlow张量进行此操作?

2 个答案:

答案 0 :(得分:2)

非洲人还是欧洲人?

  1. 如果您知道指数严格增加,tf.sparse_to_dense可以满足您的需求。

  2. 如果索引不同但按升序排列,您可以使用tf.sparse_reorder来修正订单,然后使用tf.sparse_tensor_to_dense

  3. 如果有重复项并且您想要添加匹配值,请使用tf.unsorted_segment_sum

  4. 如果有重复项并且您希望最后一个条目获胜(完全对应于您的Python循环),请使用tf.dynamic_stitch

  5. 为动物园选择道歉。由于各种原因,所有操作都被添加,因此整体设计并不是特别干净。

答案 1 :(得分:2)

我找到了实现这一目标的方法,我在这里发布我的答案,以防其他人帮助 在这种情况下,TensorFlow中的scatter_nd函数非常方便。 下面的代码根据张量T中给出的变换来置换输入张量I中的元素.scatter_nd用于根据此排列创建新的张量。

sess = tf.InteractiveSession()
I = tf.constant([10,20,30])
T = tf.constant([-1,0,3])
T = T - tf.reduce_min(T)
T_shape = int(T.get_shape()[0])
T = tf.reshape(T, [T_shape,1])
O_shape = tf.reduce_max(T)+1
O = tf.scatter_nd(T, I, [O_shape])
print(sess.run([I,T,O]))
sess.close()

此代码执行以下任务:
鉴于

Input = [10, 20, 30]
Transformation = [-1, 0, 3]

计算

Output = [10, 20,  0,  0, 30]