Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 一次求张量流中若干元素的指数_Python_Tensorflow - Fatal编程技术网

Python 一次求张量流中若干元素的指数

Python 一次求张量流中若干元素的指数,python,tensorflow,Python,Tensorflow,我是Tensorflow的新手 我有一个问题 这里有一维数组 value=[101103105109107] 目标_值=[105103] 我想立刻从值中获取有关目标值的索引 下面将显示从上述示例中提取的索引 索引=[2,1] 当我使用tf.map\u fn函数时。 这个问题很容易解决 #如果不将数据类型从int64更改为int32。打字错误会引起误会 值=tf.cast(tf.constant([100101102103104]),tf.int64) 目标值=tf.cast(tf.cons

我是Tensorflow的新手

我有一个问题

这里有一维数组

value=[101103105109107]
目标_值=[105103]
我想立刻从
中获取有关
目标值的索引

下面将显示从上述示例中提取的索引

索引=[2,1]

当我使用
tf.map\u fn
函数时。 这个问题很容易解决

#如果不将数据类型从int64更改为int32。打字错误会引起误会
值=tf.cast(tf.constant([100101102103104]),tf.int64)
目标值=tf.cast(tf.constant([100101]),tf.int64)
指数=tf.map_fn(λx:tf.where(tf.equal(value,x)),目标值)

谢谢大家!

假设
目标值
中的所有值都在
中,这是一种简单的方法(tf2.x,但函数应在1.x中工作):


所以你不想使用map_fn函数?@zihaozhihao谢谢!你的回答是,那是因为我想提高绩效。当
目标值
较大时,会降低性能。是否保证
目标值
中的所有数字都在
中?
import tensorflow as tf

values = [101, 103, 105, 109, 107]
target_values = [105, 103]

# Assumes all values in target_values are in values
def find_in_array(values, target_values):
    values = tf.convert_to_tensor(values)
    target_values = tf.convert_to_tensor(target_values)
    # stable=True if there may be repeated elements in values
    # and you want always first occurrence
    idx_s = tf.argsort(values, stable=True)
    values_s = tf.gather(values, idx_s)
    idx_search = tf.searchsorted(values_s, target_values)
    return tf.gather(idx_s, idx_search)

print(find_in_array(values, target_values).numpy())
# [2 1]