【问题标题】:How to get numpy.exp to work with an array as well as a scalar?如何让 numpy.exp 与数组和标量一起使用?
【发布时间】:2021-01-20 20:52:33
【问题描述】:

我正在处理一项要求我用 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!')

【问题讨论】:

    标签: python python-3.x numpy sigmoid


    【解决方案1】:

    你必须用括号来封装分数的分母,像这样:

     h = 1/(1+np.exp(-z))
    

    当您忘记括号时,您实际上是在计算 1 除以 1,然后加上 np.exp(0)。这将导致您达到 2,这就是您的总和与您的 0.5 目标不匹配的原因。

    标量是常规数字,与矩阵或数组相反。

    【讨论】:

    • 它有效!谢谢!你知道我如何检查它是否适用于数组吗?
    • 您可以使用自己的示例来构建数组:your_array = np.array([0, 4.92]),然后您的测试可以是:sigmoid(your_array).all() == np.array([0.5, 0.9927537604041685]).all() .all() 是一种比较两个数组的所有元素的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    • 1970-01-01
    • 2022-06-15
    • 2023-04-07
    相关资源
    最近更新 更多