Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy, apply a list of functions along array dimension

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?

like image 536
Qubix Avatar asked Oct 17 '22 10:10

Qubix


2 Answers

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)])
like image 121
cs95 Avatar answered Oct 21 '22 00:10

cs95


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

like image 21
Qubix Avatar answered Oct 21 '22 01:10

Qubix