How do I implement leaky relu using Numpy functions
Asked Answered
B

5

8

I am trying to implement leaky Relu, the problem is I have to do 4 for loops for a 4 dimensional array of input.

Is there a way that I can do leaky relu only using Numpy functions?

Boresome answered 24/5, 2018 at 20:20 Comment(0)
W
13

Here are two approaches to implement leaky_relu:

import numpy as np                                                 

x = np.random.normal(size=[1, 5])

# first approach                           
leaky_way1 = np.where(x > 0, x, x * 0.01)                          

# second approach                                                                   
y1 = ((x > 0) * x)                                                 
y2 = ((x <= 0) * x * 0.01)                                         
leaky_way2 = y1 + y2  
Winwaloe answered 15/1, 2019 at 20:23 Comment(1)
the second approach is a bit faster!Chekhov
F
2
import numpy as np




def leaky_relu(arr):
    alpha = 0.1
    
    return np.maximum(alpha*arr, arr)
Fenske answered 4/5, 2021 at 10:47 Comment(0)
E
1

Going off the wikipedia entry for leaky relu, should be able to do this with a simple masking function.

output = np.where(arr > 0, arr, arr * 0.01)

Anywhere you are above 0, you keep the value, everywhere else, you replace it with arr * 0.01.

Eby answered 24/5, 2018 at 20:23 Comment(0)
T
0
def leaky_relu_forward(x, alpha):
  out = x                                                
  out[out <= 0]=out[out <= 0]* alpha
  return out
Trimetallic answered 12/11, 2021 at 17:59 Comment(0)
R
0

Just to add, this approche :

def leaky_relu(x):
    return np.maximum(0.01*x, x)

is 2 time faster than this one :

leaky_way1 = np.where(x > 0, x, x * 0.01) 
Regin answered 12/4, 2023 at 12:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.