python - Piecewise functions on Numpy Arrays -
python - Piecewise functions on Numpy Arrays -
what efficient (speed) way apply piecewise functions on numpy array?
say, example, piecewise functions like
for (1) : x<=2 f(x) = 2*x + x^2 (2) : x>2 f(x) = -(x^2 + 2) here's did.
data = np.random.random_integers(5, size=(5,6)) print info np.piecewise(data, [data <= 2, info > 2], [lambda x: 2*x + pow(2, x), lambda x: -(pow(x, 2) + 2)]) info = [[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 efficient method go smaller arrays, big arrays, many functions etc? concern lambda functions beingness used. not sure if these numpy optimized.
in case, should not concerned lambdas: numpy optimisation reducing phone call overhead, letting functions evaluate many values @ same time in batch. in each phone call np.piecewise, each function in funclist (the function parts) called once, numpy array consisting of values appropriate status true. thus, these lambda's called in numpy-optimised way.
similar np.select (and np.where 2 parts). phone call overhead same vectorised same way, evaluate functions data-points. thus, slower np.piecewise, particularly, when functions expensive. in cases, is more convenient (no lambda), , 1 can more extend concept many variables.
python arrays numpy scipy piecewise
Comments
Post a Comment