您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

我测试过的所有建议的方法加上np.array(map(f, x))perfplot(我的一个小项目)。

消息1:如果可以使用numpy的本机函数,请执行此操作。

如果你想已经矢量化功能的矢量(如x**2在原岗位的例子),使用的是多比什么都更快(注意对数标度):

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

复制剧情的代码

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)


perfplot.show(
    setup=lambda n: np.random.rand(n),
    n_range=[2**k for k in range(20)],
    kernels=[
        f,
        array_for, array_map, fromiter, vectorize, vectorize_without_init
        ],
    xlabel='len(x)',
    )
python 2022/1/1 18:24:38 有201人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶