1
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

how can I improve this code? these loops are taking too much time. I tried the following code

def sigmoid(a):
    if a > 0:
       z = np.exp(-a)
       return 1/(1+z)
    else:
       z = np.exp(a)
       return 1/(1+z)

But its not working for a 2D array or even 1D array, gives error on if statement.

if a > 0: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
desertnaut
  • 57,590
  • 26
  • 140
  • 166

1 Answers1

3

abs(a) gives the absolute value of each element in a numpy array, so you can simply use that:

def sigmoid(a):
    z = np.exp(-abs(a))
    return 1/(1+z)
interjay
  • 107,303
  • 21
  • 270
  • 254