相关疑难解决方法(0)

在numpy数组中查找值列表的索引

我有一个numpy主数组.给定另一个具有重复元素的搜索值数组,我想在主数组中生成这些搜索值的索引.

例如:主数组是[1,2,3,4,5],搜索数组是[4,2,2,3]

解决方案:[3,1,1,2]

是否存在"本地"numpy函数可以有效地执行此操作(意味着以C速度而不是python速度)?

我知道以下解决方案,但是,首先,它是一个python列表理解,其次,它将搜索2的索引两次.

ma = np.array([1,2,3,4,5])
sl = np.array([4,2,2,3])
ans = [np.where(ma==i) for i in sl]
Run Code Online (Sandbox Code Playgroud)

此外,如果我不得不求助于排序和二进制搜索,我将作为最后的手段(不是各种级别的双关语).我有兴趣发现我是否遗漏了numpy库中的基本内容.这些列表非常大,因此性能至关重要.

谢谢.

编辑:发布之前我尝试了以下结果:

[np.searchsorted(ma,x) for x in sl]
Run Code Online (Sandbox Code Playgroud)

@pierre发布的解决方案性能更高,正是我所寻求的.

numpy

8
推荐指数
1
解决办法
6416
查看次数

循环张量并将函数应用于每个元素

我想遍历一个包含 的张量Int,并将一个函数应用于每个元素。在函数中,每个元素都将从 python 的字典中获取值。我已经尝试了简单的方法 with tf.map_fn,它可以处理add函数,例如以下代码:

import tensorflow as tf

def trans_1(x):
    return x+10

a = tf.constant([1, 2, 3])
b = tf.map_fn(trans_1, a)
with tf.Session() as sess:
    res = sess.run(b)
    print(str(res))
# output: [11 12 13]
Run Code Online (Sandbox Code Playgroud)

但以下代码抛出KeyError: tf.Tensor'map_8/while/TensorArrayReadV3:0' shape=() dtype=int32异常:

import tensorflow as tf

kv_dict = {1:11, 2:12, 3:13}

def trans_2(x):
    return kv_dict[x]

a = tf.constant([1, 2, 3])
b = tf.map_fn(trans_2, a)
with tf.Session() as sess:
    res = sess.run(b)
    print(str(res))
Run Code Online (Sandbox Code Playgroud)

我的 tensorflow 版本是 …

python tensorflow tensor

5
推荐指数
1
解决办法
2010
查看次数

标签 统计

numpy ×1

python ×1

tensor ×1

tensorflow ×1