在张量流中查找值张量到另一个张量的索引

拉胡尔

我有2个向量

a = [0 0 37 7 8 0 0] b = [0 0 4 37 8]

我想找到b的值到a的索引,所以输出看起来像

c = [0 0 -1 2 4]

我如何在Tensorflow操作中执行此操作

弗拉德

解决方案:

import tensorflow as tf

a = tf.constant([0, 0, 37, 7, 8, 0, 0])
b = tf.constant([0, 0, 4, 37, 8])

expanded_b = b[..., None]
tiled_a = tf.tile(a[None, ...], [tf.shape(b)[0], 1])
mult = tf.cast(tf.equal(expanded_b, tiled_a), tf.float32)
sub = tf.cast(tf.math.equal(tf.reduce_sum(mult, -1), 0), tf.int64)
res = tf.argmax(mult, axis=-1) - sub

with tf.Session() as sess:
    print(res.eval()) # [ 0  0 -1  2  4]

说明:

a = tf.constant([0, 0, 37, 7, 8, 0, 0])
b = tf.constant([0, 0, 4, 37, 8])

expanded_b = b[..., None]
# expanded_b:
# [[ 0]
#  [ 0]
#  [ 4]
#  [37]
#  [ 8]]
tiled_a = tf.tile(a[None, ...], [tf.shape(b)[0], 1])
# tiled_a
# [[ 0  0 37  7  8  0  0]
#  [ 0  0 37  7  8  0  0]
#  [ 0  0 37  7  8  0  0]
#  [ 0  0 37  7  8  0  0]
#  [ 0  0 37  7  8  0  0]]

# Now expanded_b and tiled_a are broadcastable so we can compare
# each element of b to all elements in a in parallel
mult = tf.cast(tf.equal(expanded_b, tiled_a), tf.float32)
# mult
# [[1. 1. 0. 0. 0. 1. 1.]
#  [1. 1. 0. 0. 0. 1. 1.]
#  [0. 0. 0. 0. 0. 0. 0.]
#  [0. 0. 1. 0. 0. 0. 0.]
#  [0. 0. 0. 0. 1. 0. 0.]]

# from mult we need first index from axis -1 that is != 0 (using argmax)
# sub shows which rows have all zeros (no element of b in a)
# for such rows we put value 1
sub = tf.cast(tf.math.equal(tf.reduce_sum(mult, -1), 0), tf.int64) 
# sub
# [0 0 1 0 0]
# result
res = tf.argmax(mult, axis=-1) - sub

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用张量流中的另一个索引列表访问张量的元素

TensorFlow:使用张量索引另一个张量

用另一个张量索引张量

如何使用另一个数组的元素作为索引来切片张量流中的张量?

PyTorch - 另一个张量中相应值的索引

将索引选定的张量添加到另一个在pytorch中具有重叠索引的张量

在张量流中索引一维张量

根据来自另一个张量的索引创建新张量并使用它的值进行分配

以另一个张量为种子在张量流中生成随机序列

从另一个张量创建特定张量

基于另一个张量求和 Torch 张量

在Tensorflow 2.0中用另一个张量索引张量的第k个维度

Keras张量-使用来自另一个张量的索引获取值

用另一个多维张量索引多维火炬张量

使用张量的值作为另一个的形状?

根据来自另一个张量的值为张量赋值

如何根据pytorch中另一个张量的值将张量的某个值更改为零?

如何将张量插入到 pytorch 中的另一个张量中

从Tensorflow中的另一个张量中选择随机张量

计算张量中每个元素相对于另一个张量的最小距离

如何将张量连接到 pytorch 中的另一个张量列表?

Pytorch从最后一个张量维中选择值,并从另一个张量较小的维中选择索引

将多维张量中的值映射到另一个值

Tensorflow:时间流中索引的查找张量

取一个在另一个张量内的张量元素

根据另一个张量排列一个张量的每个像素

如何将一个张量的值插入另一个?

如何在张量流图中使用另一个库?

使用张量流使用另一个变量初始化变量