Compute an array in a specific subarray

I warn in advance: I can be completely confused at the moment. I’ll tell you a short story about what I’m actually trying to achieve, because this can clarify the situation. Say I have f(a,b,c,d,e) and I want to find arg max (d,e) f(a,b,c,d,e) . Consider (a trivial example a) a discretized mesh F of F :

 F = np.tile(np.arange(0,10,0.1)[newaxis,newaxis,:,newaxis,newaxis], [10, 10, 1, 10, 10]) maxE = F.max(axis=-1) argmaxD = maxE.argmax(axis=-1) maxD = F.max(axis=-2) argmaxE = maxD.argmax(axis=-1) 

This is the way I usually decide the sampled version. But now, instead, suppose I want to solve arg max df(a,b,c,d,e=X) : instead of optimally selected e for each other input, e is fixed and given (the size of AxBxCxD, which in this example will be 10x10x100x10 ) I have problems with this.

My naive approach was

 X = np.tile(np.arange(0,10)[newaxis,newaxis,:,newaxis], [10,10,1,10]) maxX = F[X] argmaxD = maxX.argmax(axis=-1) 

However, the huge burst of memory that crashes my IDE means that F[X] apparently not what I was looking for.

Performance is the key.

+6
source share
2 answers

I believe you can do it this way, but maybe there is a better way.

 n = 10 F = np.tile(np.arange(0,n,0.1)[None,None,:,None,None], [n, n, 1, n, n]) X = np.tile(np.arange(0,n)[None,None,:,None], [n, n, 1, n]) a,b,c,d = np.ogrid[:n,:n,:n,:n] argmaxD = F[a,b,c,d,X].argmax(axis=-1) 

Above X does not occupy all the space, as we discussed in the comments. If you want to select e for all a , b , c and d , you can do, for example:

 X = np.tile(np.arange(0,n,0.1).astype(int)[None,None,:,None], [n, n, 1, n]) a,b,c,d = np.ogrid[:n,:n,:100,:n] argmaxD = F[a,b,c,d,X].argmax(axis=-1) 

Also note that you can use translation instead of tile . But then F[a,b,c,d,X] has a special size, so you should provide something like axis=3 :

 X = np.arange(0,n,0.1).astype(int)[None,None,:,None] a,b,c,d = np.ogrid[:n,:n,:100,:n] argmaxD = F[a,b,c,d,X].argmax(axis=3) 
+2
source

It would be my idea to solve this problem.

 from itertools import product, starmap f = lambda a,b,c,d,e : d / e args_iterable = product([1],[2],[3],range(1,1000),range(1,1000)) max_val, max_args = max(starmap(lambda *args: (f(*args), args) , args_iterable)) print max_args 
0
source

Source: https://habr.com/ru/post/971884/


All Articles