问题描述
我正在尝试实现一个函数,该函数为矩阵中的每个元素计算Relu导数,然后将结果返回到矩阵中.我正在使用Python和Numpy.
I'm trying to implement a function that computes the Relu derivative for each element in a matrix, and then return the result in a matrix. I'm using Python and Numpy.
根据其他交叉验证帖子,x的Relu导数为当x> 0时为1,当x
Based on other Cross Validation posts, the Relu derivative for x is1 when x > 0, 0 when x < 0, undefined or 0 when x == 0
目前,到目前为止,我有以下代码:
Currently, I have the following code so far:
def reluDerivative(self, x):
return np.array([self.reluDerivativeSingleElement(xi) for xi in x])
def reluDerivativeSingleElement(self, xi):
if xi > 0:
return 1
elif xi <= 0:
return 0
不幸的是,因为x是矩阵,所以xi是一个数组. reluDerivativeSingleElement函数不适用于数组.所以我想知道是否有一种方法可以使用numpy将矩阵中的值映射到另一个矩阵,例如numpy中的exp函数?
Unfortunately, xi is an array because x is an matrix. reluDerivativeSingleElement function doesn't work on array. So I'm wondering is there a way to map values in a matrix to another matrix using numpy, like the exp function in numpy?
非常感谢.
推荐答案
我想这就是您要寻找的东西:
I guess this is what you are looking for:
>>> def reluDerivative(x):
... x[x<=0] = 0
... x[x>0] = 1
... return x
>>> z = np.random.uniform(-1, 1, (3,3))
>>> z
array([[ 0.41287266, -0.73082379, 0.78215209],
[ 0.76983443, 0.46052273, 0.4283139 ],
[-0.18905708, 0.57197116, 0.53226954]])
>>> reluDerivative(z)
array([[ 1., 0., 1.],
[ 1., 1., 1.],
[ 0., 1., 1.]])
这篇关于在python numpy中实现Relu派生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!