问题描述
我正在做一个作业,要求我用Python编写Sigmoid函数。我对此很陌生,所以我有点理解Sigmoid函数的工作原理。
该作业要求我对其进行编码,以便无论z是数组还是标量,该函数均起作用。我知道什么是数组,但不知道什么是标量。搜索它只会产生我不理解的数学术语。作业还建议我使用numpy.exp
来解决问题。无论如何,这是我写的,显然不起作用。我不确定逻辑是否错误,或者仅仅是因为我没有考虑标量与数组之类的事情。谁能帮助我了解这是什么或在哪里找到该信息?
这是代码:
def sigmoid(z):
'''
Input:
z: is the input (can be a scalar or an array)
Output:
h: the sigmoid of z
'''
### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ###
# calculate the sigmoid of z
h = 1/1+np.exp(-z)
### END CODE HERE ###
return h
# Testing your function
if (sigmoid(0) == 0.5):
print('SUCCESS!')
else:
print('Oops!')
if (sigmoid(4.92) == 0.9927537604041685):
print('CORRECT!')
else:
print('Oops again!')
解决方法
您必须用括号将分数的分母封装起来,像这样:
h = 1/(1+np.exp(-z))
当您忘记括号时,实际上是在将1除以1,然后加上np.exp(0)。这将导致您达到2,这就是为什么您的总和与您的0.5个目标不匹配的原因。
标量是正则数,与矩阵或数组相反。