我在从其他张量中查找值时遇到问题。
此问题的描述如下。 例如,
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)
在上图中, s_idx [1] 的值等于 label_s_idx [2] 和 e_idx [1] 的值>等于 label_e_idx [2] 。
换句话说,问题是如果条件 s_idx [i] == label_s_idx [i] , output [i] 的值为1和 e_idx [i] == label_s_idx [j] 满足在label_s_idx的长度(== label_e_idx的长度)范围内的某个j。
因此,在上面的示例中,输出张量为
output = ( 0, 1, 0, 0)
如何在Python的Tensorflow上这样编码?
答案 0 :(得分:1)
我找不到为此操作设计的功能。您可以使用如下矩阵操作来实现它。
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.]