-2

I'm getting a Value error for the following code:

def ReLu(x):
    if x>0:
        return x
    else:
        return 0

The error occurs when I call the function using a matrix

x = np.random.randn(4,4)
z = ReLu(x)

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Ale Sanchez
  • 536
  • 1
  • 6
  • 17
  • 2
    You can’t call it with a matrix. The error message tells you why. – deets Dec 13 '18 at 19:54
  • Your function requires a single value, but you passed it a vector. If you want this to work as a vector function, you have to write with vectorized operations. – Prune Dec 13 '18 at 19:56
  • Jaswanth, what is function `ReLu` supposed to do? Please, clarify this if you want us to help you – JoshuaCS Dec 13 '18 at 21:24

1 Answers1

1

It looks like you're trying to perform the ReLu function on a matrix, which IIRC will take subzero values and "shift them up" to 0, and will leave positive values unchanged.

Where you've gone wrong, as others have suggested, is that you are missing some basic principles of how the numpy api operates.

The corrected RELU function would, I believe, be:

def ReLu(x):
    x[x < 0] = 0

Why? What you're doing here is threefold. The first resolved expression, x < 0 returns another numpy array of the same shape, except that there are "true" values where the elements of the array are less than zero, and "false" values elsewhere.

The next resolved part of the expression is to select a "view" of the numpy array. This basically means "give me those elements of the array that match the true values we defined earlier."

The final step is to assign to those values the value you want, which is 0.

Hopefully this is helpful!

Marviel
  • 132
  • 8