I have a list of functions of the type:
func_list = [lambda x: function1(input),
lambda x: function2(input),
lambda x: function3(input),
lambda x: x]
and an array of shape [4, 200, 200, 1] (a batch of images).
I want to apply the list of functions, in order, along the 0th axis.
EDIT: Rephrasing the problem. This is equivalent to the above. Say, instead of the array, I have a tuple of 4 identical arrays, of shape (200, 200, 1), and I want to apply function1 on the first element, function2 on the second element, etc. Can this be done without a for loop?
You can iterate over your function list using np.apply_along_axis
:
import numpy as np
x = np.ranom.randn(100, 100)
for f in fun_list:
x = np.apply_along_axis(f, 0, x)
Assuming your functions and batches are the same in size:
batch = ... # tuple of 4 images
batch_out = tuple([np.apply_along_axis(f, 0, x) for f, x in zip(fun_list, batch)])
I tried @Coldspeed's answer, and it does work (so I will accept it) but here is an alternative I found, without using for loops:
result = tuple(map(lambda x,y:x(y), functions, image_tuple))
Edit: forgot to add the tuple(), thanks @Coldspeed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With