8

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?

1
  • Just to understand, you want to apply it over a particular row? Axis? Or over the entire matrix? Do these functions transform each element or are they something like sum/max functions which give a single output? Commented Jun 18, 2017 at 11:30

2 Answers 2

3

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)

Based on OP's Update

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)])
Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible to avoid a for loop ?
@Qubix It'd be a good feature to have if there was a way. But I'm not sure there is.
2

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

2 Comments

If using python 3, don't forget to tack on tuple() to the final answer.
[x(y) for x, y in zip(functions, image_tuple)] is the comprehension equivalent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.