栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在numpy数组上广播python函数

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在numpy数组上广播python函数

np.vectorize
是将操作数字的Python函数转换为操作ndarray的numpy函数的通用方法。

但是,正如您所指出的那样,它并不是很快,因为它使用“后台”的Python循环。

为了获得更好的速度,您必须手工制作一个函数,该函数期望将numpy数组作为输入并利用该numpy-ness:

import numpy as npdef func2(x, y):    return np.where(x>y,x+y,x-y)x = np.array([-2, -1, 0, 1, 2])y = np.array([-2, -1, 0, 1, 2])xx = x[:, np.newaxis]yy = y[np.newaxis, :]print(func2(xx, yy))# [[ 0 -1 -2 -3 -4]#  [-3  0 -1 -2 -3]#  [-2 -1  0 -1 -2]#  [-1  0  1  0 -1]#  [ 0  1  2  3  0]]

关于性能:

test.py

import numpy as npdef func2a(x, y):    return np.where(x>y,x+y,x-y)def func2b(x, y):    ind=x>y    z=np.empty(ind.shape,dtype=x.dtype)    z[ind]=(x+y)[ind]    z[~ind]=(x-y)[~ind]    return zdef func2c(x, y):    # x, y= x[:, None], y[None, :]    A, L= x+ y, x<= y    A[L]= (x- y)[L]    return AN=40x = np.random.random(N)y = np.random.random(N)xx = x[:, np.newaxis]yy = y[np.newaxis, :]

运行:

当N = 30时:

% python -mtimeit -s'import test' 'test.func2a(test.xx,test.yy)'1000 loops, best of 3: 219 usec per loop% python -mtimeit -s'import test' 'test.func2b(test.xx,test.yy)'1000 loops, best of 3: 488 usec per loop% python -mtimeit -s'import test' 'test.func2c(test.xx,test.yy)'1000 loops, best of 3: 248 usec per loop

当N = 1000时:

% python -mtimeit -s'import test' 'test.func2a(test.xx,test.yy)'10 loops, best of 3: 93.7 msec per loop% python -mtimeit -s'import test' 'test.func2b(test.xx,test.yy)'10 loops, best of 3: 367 msec per loop% python -mtimeit -s'import test' 'test.func2c(test.xx,test.yy)'10 loops, best of 3: 186 msec per loop

这似乎表明它

func2a
func2c
(快得
func2b
非常慢)快。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/667965.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号