Python 一次求张量流中若干元素的指数
我是Tensorflow的新手 我有一个问题 这里有一维数组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
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]