如何使用Numpy函数实现leaky relu

s4n0splo  于 2023-04-21  发布在  其他
关注(0)|答案(5)|浏览(143)

我试图实现泄漏Relu,问题是我必须为一个4维输入数组做4个for循环。
有没有一种方法可以只使用Numpy函数来执行leaky relu?

lsmepo6l

lsmepo6l1#

以下是实现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
mo49yndu

mo49yndu2#

离开维基百科的leaky relu条目,应该可以用一个简单的掩码函数来做到这一点。

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

在大于0的任何地方,你都保留这个值,在其他任何地方,你用arr * 0.01替换它。

e4eetjau

e4eetjau3#

import numpy as np



def leaky_relu(arr):
    alpha = 0.1
    
    return np.maximum(alpha*arr, arr)
ttisahbt

ttisahbt4#

def leaky_relu_forward(x, alpha):
  out = x                                                
  out[out <= 0]=out[out <= 0]* alpha
  return out
bwitn5fc

bwitn5fc5#

只是为了补充,这approche:

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

比这个快2倍:

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

相关问题