如何在python中为sigmoid函数删除这些循环

如何在python中为sigmoid函数删除这些循环,python,numpy,sigmoid,Python,Numpy,Sigmoid,如何改进此代码?这些循环占用了太多时间。 我尝试了以下代码 def sigmoid(a): g = a for i in range(a.shape[0]): for j in range(a.shape[1]): if a[i][j] >= 0: z = np.exp(-a[i][j]) g[i][j] = 1 / (1 + z) else:

如何改进此代码?这些循环占用了太多时间。 我尝试了以下代码

def sigmoid(a):
    g = a
    for i in range(a.shape[0]):
        for j in range(a.shape[1]):
            if a[i][j] >= 0:
                z = np.exp(-a[i][j])
                g[i][j] = 1 / (1 + z)
            else:
                z = np.exp(a[i][j])
                g[i][j] = 1 / (1 + z)
    return g
但它不适用于2D数组,甚至不适用于1D数组,在if语句中给出错误

def sigmoid(a):
    if a > 0:
       z = np.exp(-a)
       return 1/(1+z)
    else:
       z = np.exp(a)
       return 1/(1+z)
absa给出numpy数组中每个元素的绝对值,因此您可以简单地使用:

if a > 0: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
absa给出numpy数组中每个元素的绝对值,因此您可以简单地使用:

if a > 0: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

您的第二个函数似乎对我来说运行良好,只需一个输入。您是否试图将数组作为参数传递;重新给出数组并将其与单个数字进行比较。你应该试试:a[i]>0…@IshwarVenugopal是的,我正在以参数形式传递一个2d数组。你的第二个函数似乎对我来说很好,只需一个输入。您是否试图将数组作为参数传递;重新给出数组并将其与单个数字进行比较。你应该试试:a[i]>0…@IshwarVenugopal是的,我正在传递一个2d数组作为参数,它可以工作。谢谢,在这种情况下,我建议你接受这个答案。@UmmeAmmarah欢迎这么做;如果答案解决了你的问题,请接受它-看看它的工作。谢谢,在这种情况下,我建议你接受这个答案。@UmmeAmmarah欢迎这么做;如果答案解决了您的问题,请接受它-参见