I want to apply arbitrary function to 3d-ndarray as element, which use (3rd-dimensional) array for its arguments and return scalar.As a result, we should get 2d-Matrix.
e.g) pseudo code
A = [[[1,2,3],[4,5,6]],
[[7,8,9],[10,11,12]]]
A.apply_3d_array(sum) ## or apply_3d_array(A,sum) is Okey.
>> [[6,15],[24,33]]
I understand it's possible with loop using ndarray.shape function,but direct index access is inefficient as official document says. Is there more effective way than using loop?
def chromaticity(pixel):
geo_mean = math.pow(sum(pixel),1/3)
return map(lambda x: math.log(x/geo_mean),pixel )
Given the function implementation, we could vectorize it using
NumPy ufuncs
that would operate on the entire input arrayA
in one go and thus avoid themath
library functions that doesn't support vectorization on arrays. In this process, we would also bring in the very efficient vectorizing tool :NumPy broadcasting
. So, we would have an implementation like so -Sample run and verification
The function implementation without the
lamdba
construct and introducing NumPy functions instead ofmath
library functions, would look something like this -Sample run with the iterative implementation -
Sample run with the proposed vectorized implementation -
Runtime test
That's why always try to push in
NumPy funcs
when vectorizing things with arrays and work on as many elements in one-go as possible!apply_along_axis
is designed to make this task easy:It, in effect, does
taking care of the details. It's not faster than doing that iteration yourself, but it makes it easier.
Another trick is to reshape your input to 2d, perform the simpler 1d iteration, and the reshape the result
To do things faster, you need to dig into the guts of the function, and figure out how to use compile numpy operations on more than one dimension. In the simple case of
sum
, that function already can work on selected axes.