Numpy数组上的分段函数 [英] Piecewise functions on Numpy Arrays

查看:96
本文介绍了Numpy数组上的分段函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Numpy数组上应用分段函数的有效(速度)方法是什么?

What is efficient (speed) way to apply Piecewise functions on Numpy Array?

例如,分段函数就像

For (1) :  x<=2 f(x) = 2*x + x^2
    (2) :  x>2  f(x) = -(x^2 + 2)

这就是我所做的.

data = np.random.random_integers(5, size=(5,6))
print data
np.piecewise(data, [data <= 2, data > 2],
             [lambda x: 2*x + pow(2, x),
              lambda x: -(pow(x, 2) + 2)])

data = 
[[4 2 1 1 5 3]
 [4 3 3 5 4 5]
 [3 2 4 2 5 3]
 [2 5 4 3 1 4]
 [5 3 3 5 5 5]]
output = 
array([[-18,   8,   4,   4, -27, -11],
       [-18, -11, -11, -27, -18, -27],
       [-11,   8, -18,   8, -27, -11],
       [  8, -27, -18, -11,   4, -18],
       [-27, -11, -11, -27, -27, -27]])

对于较小的数组,较大的数组,许多函数等,有没有一种有效的方法?我担心的是正在使用的lambda函数.不确定它们是否经过Numpy优化.

Is there an efficient method to go by for smaller arrays, large arrays, many functions etc? My concern is with lambda functions being used. Not sure if these are Numpy optimized.

推荐答案

在这种情况下,您不必担心lambda:numpy优化是通过让函数同时批量评估多个值来减少调用开销.在每次对 np.piecewise 的调用中, funclist 中的每个函数(函数部分)均被精确调用一次,并由一个numpy数组组成,该数组由所有值组成,且适当条件为true.因此,以numpy优化的方式调用了这些lambda.

In this case, you should not be concerned about the lambdas: Numpy optimisation is about reducing call overhead, by letting functions evaluate many values at the same time in batch. In each call to np.piecewise, each function in funclist (the function parts) is called exactly once, with a numpy array consisting of all values where the appropriate condition is true. Thus, these lambda's are called in a numpy-optimised way.

类似的是 np.select (以及 np.where 恰好是两个部分).调用开销与通过相同的方式向量化的开销相同,但是它将评估所有数据点的所有功能.因此,它会比 np.piecewise 慢,特别是在功能昂贵的情况下.在某些情况下,方便(没有lambda),并且可以更轻松地将概念扩展到许多变量.

Similar is np.select (and np.where for exactly two parts). The call overhead is the same as it is vectorised the same way, but it will evaluate all functions for all data-points. Thus, it will be slower than np.piecewise, particularly, when the functions are expensive. In some cases, is is more convenient (no lambda), and one can more easily extend the concept to many variables.

这篇关于Numpy数组上的分段函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆