How to get numpy.exp to work with an array as well as a scalar?

1k Views Asked by At

I am working on an assignment that asks me to code the sigmoid function in Python. I'm very new to this so I sort of understand how the Sigmoid function works.

Sigmoid function

The assignment asks that I code it so that the function will work whether z is an array or a scalar. I know what an array is but I have no clue what a scalar is. And searches for it have only yielded math terms I don't understand. The assignment also suggests I use numpy.exp to solve the problem. Anyway, this is what I wrote and it clearly doesn't work. I am not sure if I got the logic wrong or if it's just because I am not considering the scalar vs array thing. Could anyone help me understan what that is or where to find that information?

This is the code:

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!')
1

There are 1 best solutions below

2
On BEST ANSWER

You have to encapsulate the denominator of your fraction with parenthesis, like this:

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

When you forget the parenthesis, you are actually evaluating 1 divided by 1 and then adding np.exp(0). This will lead you to 2, that's why your sum does not match with your 0.5 goal.

And scalars are regular numbers, in opposition to matrices or arrays.