user42493
user42493

Reputation: 1103

use np.apply_along_axis on a function with multiple arguments

I want to apply a method on all rows of a matrix and then get the average of the results.

Concretely, let's say I have a method:

import numpy as np
def relu(x, grad=False):
    numpy_x= np.array(x)
    if grad:
        return np.where(numpy_x <= 0, 0, 1)
    return np.maximum(0, numpy_x)

I have an numpy array:

a=np.array([[1,2,3],[2,3,4]])

I want to apply relu to all rows of the array and sum them up. So I tried to do the following to first apply relu to all rows:

np.apply_along_axis(relu, 1,a)

However, there is a problem, we can apply relu with param grad=False to all rows only. What if we want to apply relu(,grad=True) to all rows of a?

Upvotes: 1

Views: 2160

Answers (1)

ruancomelli
ruancomelli

Reputation: 730

I don't completely understand your problem. Is it about the default argument? If so, try

np.apply_along_axis(lambda x: relu(x, grad=True), 1, a)

Edit

If you want to average the results, I believe that the following code is enough:

avg_relu = np.mean(relu(a, False), axis=1)
avg_relu_grad = np.mean(relu(a, True), axis=1)

Upvotes: 1

Related Questions