【问题标题】:Optimizing execution time for mapping array to value with dictionary and numpy使用字典和 numpy 优化将数组映射到值的执行时间
【发布时间】:2021-10-17 04:04:34
【问题描述】:

我正在尝试从使用二维 numpy 创建的数组中实现到一组值的简单映射。

对于数组中的每一行,我需要选择与一组值对应的正确值并将其添加到数组中。

例如:

[0, 1, 0, 0] -> 3 ... [1, 0, 1, 0] -> 2

但是,由于我的数据集的大小,我的第一个实现让我怀疑我是否在做一些真正错误或根本没有效率的事情,所以我在没有使用 for 循环的情况下做了这个解决方法,并使用字典查找优化了速度执行。

import numpy as np

# function to perform the search and return the index accordingly (it is supposed to be fast because of data structure)
def get_val(n):
    map_list = {0: [0, 1, 0], 1: [0, 1, 0], 2: [1, 0, 0], 3: [0, 0, 1]}

    map_vals = list(map_list.values())
    index = map_vals.index(list(n))

    return(index)

# set of arbitrary arrays
li = np.array([[0, 1, 0], [0, 0, 1]])

# here is the performance improvement attempt with the help of the function above
arr = [get_val(n) for n in li]

print(arr)

我不完全确定这是否是获取此类集合所需值的正确方法。如果有更好的方法,请告诉我。

否则,我指的是我的主要问题:

  • 优化代码的最佳方法是什么?

非常感谢您的帮助。

【问题讨论】:

  • 只创建一次map_vals,不重复
  • 好的,这很好。但是经过这个微不足道的修正之后,有什么办法可以优化速度呢?

标签: python performance numpy dictionary


【解决方案1】:

您可以尝试使用矩阵乘法(点积):

a=np.array([[0, 0, 0],[0, 1, 0], [1, 0, 0], [0, 0, 1]]) # dict values 
c=np.array([0,1,2,3]) #  dict keys
li = np.array([[0, 1, 0], [0, 0, 1]])
b=np.linalg.pinv(a)@c # decoding table
result=li@b
print(result)

【讨论】:

  • 感谢您的回答 Alex Alex。但是,您介意解释一下为什么这段代码比我的上一种方法更有效吗?以及解码部分的更多细节。不便之处敬请见谅,我还在努力学习python。
  • Мy 代码是高效的,因为矩阵乘法是在 numpy 中高效完成的。使用 SIMD 指令。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-05
  • 2013-09-21
  • 2015-10-17
  • 1970-01-01
  • 2020-09-01
  • 2021-06-22
  • 1970-01-01
相关资源
最近更新 更多