gpt4 book ai didi

python - 在 numpy 数组上映射函数的最有效方法

转载 作者:IT老高 更新时间:2023-10-28 12:12:20 32 4
gpt4 key购买 nike

将函数映射到 numpy 数组的最有效方法是什么?我目前正在做:

import numpy as np 

x = np.array([1, 2, 3, 4, 5])

# Obtain array of square of each element in x
squarer = lambda t: t ** 2
squares = np.array([squarer(xi) for xi in x])

但是,这可能非常低效,因为我使用列表推导将新数组构造为 Python 列表,然后再将其转换回 numpy 数组。我们能做得更好吗?

最佳答案

我已经用 perfplot 测试了所有建议的方法以及 np.array(list(map(f, x))) (我的一个小项目)。

Message #1: If you can use numpy's native functions, do that.

如果您尝试向量化的函数已经 向量化(如原始帖子中的 x**2 示例),则使用它 比其他任何东西都快(注意对数刻度):

enter image description here

如果您确实需要矢量化,那么您使用哪种变体并不重要。

enter image description here


重现情节的代码:

import numpy as np
import perfplot
import math


def f(x):
# return math.sqrt(x)
return np.sqrt(x)


vf = np.vectorize(f)


def array_for(x):
return np.array([f(xi) for xi in x])


def array_map(x):
return np.array(list(map(f, x)))


def fromiter(x):
return np.fromiter((f(xi) for xi in x), x.dtype)


def vectorize(x):
return np.vectorize(f)(x)


def vectorize_without_init(x):
return vf(x)


b = perfplot.bench(
setup=np.random.rand,
n_range=[2 ** k for k in range(20)],
kernels=[
f,
array_for,
array_map,
fromiter,
vectorize,
vectorize_without_init,
],
xlabel="len(x)",
)
b.save("out1.svg")
b.show()

关于python - 在 numpy 数组上映射函数的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35215161/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com