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)
Solution 1:
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.]
Post a Comment for "How To Find A Value In Tensor From Other Tensor In Tensorflow"