简体   繁体   English

如何从Tensorflow中的其他张量中找到张量值

[英]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] . 在上图中, s_idx [1]的值等于label_s_idx [2] ,而e_idx [1]的值等于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. 换句话说, 问题是如果条件s_idx [i] == label_s_idx [i]e_idx [i] == label_s_idx [j]在长度范围内的某个j, 则将 output [i]的值设置为1 label_s_idx(== label_e_idx的长度)被满足。

Thus, in the above example, the output tensor is 因此,在上面的示例中,输出张量为

output = ( 0, 1, 0, 0)

How do I code like this on Tensorflow in Python? 如何在Python的Tensorflow上这样编码?

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.]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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