简体   繁体   中英

How to find a value in tensor from other tensor in Tensorflow

I have a problem about finding a value in from other tensor.

The description of this problem is as follows. For example,

Input Tensor
s_idx = ( 1, 3, 5, 7)
e_idx = ( 3, 4, 5, 8)


label_s_idx = (2, 2, 3, 6)
label_e_idx = (2, 3, 4, 8)

In the figure above, the value of s_idx[1] is equal to label_s_idx[2] and the value of e_idx[1] is equal to label_e_idx[2] .

In other words, the problem is to give output[i] a value of 1 if the conditions s_idx[i] == label_s_idx[i] and e_idx[i] == label_s_idx[j] for some j in range of the length of label_s_idx (== length of label_e_idx) are satisfied.

Thus, in the above example, the output tensor is

output = ( 0, 1, 0, 0)

How do I code like this on Tensorflow in Python?

I could not find a function designed for this operation. You can implement it using matrix operations as below.

import tensorflow as tf

s_idx = [1, 3, 5, 7]
e_idx = [3, 4, 5, 8]
label_s_idx = [2, 2, 3, 6]
label_e_idx = [2, 3, 4, 8]

# convert the variables to one-hot encoding
# s_oh[i,j] = 1 if and only if s_idx[i] == j
# analogous for e_oh
s_depth = tf.reduce_max([s_idx, label_s_idx])
s_oh = tf.one_hot(s_idx, s_depth)
label_s_oh = tf.one_hot(label_s_idx, s_depth)

e_depth = tf.reduce_max([e_idx, label_e_idx])
e_oh = tf.one_hot(e_idx, e_depth)
label_e_oh = tf.one_hot(label_e_idx, e_depth)

# s_mult[i,j] == 1 if and only if s_idx[i] == label_s_idx[j]
# analogous for e_mult
s_mult = tf.matmul(s_oh, label_s_oh, transpose_b=True)
e_mult = tf.matmul(e_oh, label_e_oh, transpose_b=True)

# s_included[i] == 1 if and only if s_idx[i] is included in label_s_idx
# analogous for e_included
s_included = tf.reduce_max(s_mult, axis=1)
e_included = tf.reduce_max(e_mult, axis=1)

# output[i] == 1 if and only if s_idx[i] is included in label_s_idx
# and e_idx[i] is included in label_e_idx
output = tf.multiply(s_included, e_included)

with tf.Session() as sess:
    print(sess.run(output))
# [0. 1. 0. 0.]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM