0

I am trying to pass a relu function to each individual element of a numpy array, when I try it with a sigmoid function, it works but with the relu function, it returns:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

relu function:

def relu(x):
    return max(0, x)

sigmoid function:

def sigmoid(x):
    return 1 / (1 + np.exp(-x))

I tried doing relu(myArray) but it returns the valueError, same with map(relu, myArray)

it works fine with sigmoid function, why is it doing that and how can I fix it? thanks

Tissuebox
  • 1,016
  • 3
  • 14
  • 36

2 Answers2

3

You need numpy.maximum. The regular built-in max doesn't broadcast over array inputs.

user2357112
  • 260,549
  • 28
  • 431
  • 505
1

Just use

result = map(relu, array)

to apply your function to every element of the array.

    import numpy as np

    def relu(x):
        return max(0, x)

    array = np.arange(-10,10)


    result = map(relu, array)
    print(result)

Works for me.

Thundzz
  • 675
  • 1
  • 11
  • 15
  • if you check at the second last sentence of my question, I state that doing this returns the same error – Tissuebox Jul 06 '17 at 19:56
  • I just edited my answer. Can you maybe provide me with a bit more of your code if you need more help? :) – Thundzz Jul 06 '17 at 19:59
  • You could show me what your array looks like, for example. – Thundzz Jul 06 '17 at 20:01
  • np.arange(9).reshape((3,3)) this is basicaly what it would look like, the answer above yours fixed my problem but thanks for your concern! – Tissuebox Jul 06 '17 at 20:02
  • Just so you have a bit more insight into why this did solve your problem, your reshape transforms the array into an array of arrays. You would have needed something like : `result = map(lambda x : map(relu, x), array)` if you wanted to use your function. The other solution is more elegant and more performant though for this case. :) – Thundzz Jul 06 '17 at 20:05