如何使用 fn_map 将数组 C 中的每一行映射到数组 B 中的对应行

How to use fn_map to map each row in an array C to its coresponding one in the array B

因为我在使用 TensorFlow,所以我想知道如何将我的行从张量 C 映射到矩阵 B 中相应行的索引。

这是我写的代码:


B= tf.constant([[ 0.,  5.,  2.],[ 0.,  0.,  0.], [ 0.,  0.,  3.],[1.,5.,6.],[2.,5.,7.]])

def embeding_to_index(a_vector):
    return np.where(np.all(a_vector==B,axis=1))[0].tolist()[0]


c = tf.constant([[0.,  0.,  3.],[2.,5.,7.]])
arr =  tf.map_fn(fn=embeding_to_index,elems=c)

我的预期结果是得到一个张量[2 4],其中2指的是向量[0., 0., 3.]在张量B的行中的索引,4指的是索引在张量 B.

的行中向量 [2.,5.,7.]

我收到以下错误:

---------------------------------------------------------------------------
AxisError                                 Traceback (most recent call last)
<ipython-input-8-de82c21bac35> in <module>
     79 
     80 arr=tf.map_fn(fn=embeding_to_index,  # input & output have different dtypes
---> 81                     elems=c)
     82 # arr =  tf.vectorized_map(fn=embeding_to_index_,elems=U)

~\.conda\envs\test\lib\site-packages\tensorflow\python\ops\map_fn.py in map_fn(fn, elems, dtype, parallel_iterations, back_prop, swap_memory, infer_shape, name)
    266         back_prop=back_prop,
    267         swap_memory=swap_memory,
--> 268         maximum_iterations=n)
    269     results_flat = [r.stack() for r in r_a]
    270 

...

AxisError: axis 1 is out of bounds for array of dimension 0

如何使用 TensorFlow 库解决这个问题? TensorFlow 中是否有替代 fn_map 方法的方法?

您不必使用 tf.map_fn。也许尝试这样的事情:

import tensorflow as tf

B = tf.constant([[ 0., 5., 2.], [ 0., 0., 0.], [ 0., 0., 3.],[1.,5.,6.], [2.,5.,7.]])
c = tf.constant([[0., 0., 3.], [2.,5.,7.]])
c_shape = tf.shape(c)
b_shape = tf.shape(B)
c = tf.reshape(tf.tile(c, [1, b_shape[0]]), [c_shape[0], b_shape[0], c_shape[1]])
z = tf.where(tf.reduce_all(tf.equal(B, c), -1))
z = tf.stack([z[i, 1] for i in tf.range(tf.shape(z)[0])], axis=0)
print(z)
tf.Tensor([2 4], shape=(2,), dtype=int64)

使用:

c = tf.constant([[0., 0., 3.], [2.,5.,7.],[2.,5.,7.],[2.,5.,7.],[2.,5.,7.],[2.,5.,7.],[2.,5.,7.],[2.,5.,7.]])

你得到:

tf.Tensor([2 4 4 4 4 4 4 4], shape=(8,), dtype=int64)

更新 1: 如果你想用z中的索引得到B中对应的值,那么就这样做:

z, _ = tf.unique(z)
print(tf.gather(B, z))
tf.Tensor(
[[2. 5. 7.]
 [0. 0. 3.]], shape=(2, 3), dtype=float32)