简体   繁体   English

Numpy Arrays上的分段函数

[英]Piecewise functions on Numpy Arrays

What is efficient (speed) way to apply Piecewise functions on Numpy Array? 什么是在Numpy数组上应用分段函数的有效(速度)方法?

Say, for example, Piecewise functions are like 比方说,例如,分段函数就像

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

Here's what I did. 这就是我做的。

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]])

Is there an efficient method to go by for smaller arrays, large arrays, many functions etc? 对于较小的数组,大型数组,许多函数等,是否有一种有效的方法? My concern is with lambda functions being used. 我担心的是使用lambda函数。 Not sure if these are Numpy optimized. 不确定这些是否是Numpy优化的。

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. 在这种情况下,您不应该关注lambdas:Numpy优化是关于减少调用开销,让函数在批处理中同时评估许多值。 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. 在每次调用np.piecewisenp.piecewise中的每个函数(函数部分) funclist调用一次,其中numpy数组由适当条件为真的所有值组成。 Thus, these lambda's are called in a numpy-optimised way. 因此,这些lambda是以numpy优化的方式调用的。

Similar is np.select (and np.where for exactly two parts). 类似的是np.select (正好两个部分的np.where )。 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. 因此,它将比np.piecewise慢,特别是当功能昂贵时。 In some cases, is is more convenient (no lambda), and one can more easily extend the concept to many variables. 在某些情况下,更方便(没有lambda),并且可以更容易地将概念扩展到许多变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM