Week 2 Python_Basics_with_Numpy Exercise 8 - L1

Hello I am having trouble getting tests to pass for Week 2 optional assignment Python Basics with Numpy, Exercise 8 - L1. Bellow is my code, I am getting a Error: The function should return a float. as far as I can tell my output is printed out as a float L1 = [0.1 0.2 0.1 0.6 0.1]. Am I missing something?

{moderator edit - solution code removed}

yhat = np.array([.9, 0.2, 0.1, .4, .9])

y = np.array([1, 0, 0, 1, 1])

print("L1 = " + str(L1(yhat, y)))

L1_test(L1)

L1 = [0.1 0.2 0.1 0.6 0.1]
Error: The function should return a float.
Error: Wrong output
0 Tests passed
2 Tests failed


AssertionError Traceback (most recent call last)
in
3 print("L1 = " + str(L1(yhat, y)))
4
----> 5 L1_test(L1)

~/work/release/W2A1/public_tests.py in L1_test(target)
216 ]
217
→ 218 test(test_cases, target)
219
220 def L2_test(target):

~/work/release/W2A1/test_utils.py in test(test_cases, target)
24 print(‘\033[92m’, success," Tests passed")
25 print(‘\033[91m’, len(test_cases) - success, " Tests failed")
—> 26 raise AssertionError(“Not all tests were passed for {}. Check your equations and avoid using global variables inside the function.”.format(target.name))

AssertionError: Not all tests were passed for L1. Check your equations and avoid using global variables inside the function.

Some debugging notes:
The type each value in `L1` is `numpy.float64` the type of `L1` is `numpy.ndarray`. I have also tried just calling `abs()` without explicitly calling `np.abs()`

That implementation is just the first step to compute L1. Have another look at the definition of L1: it should be a scalar value. Here’s the definition:

L1 = \displaystyle \sum_{i = 1}^{n} | y_i - \hat{y}_i|

What you are returning is a vector containing the absolute values of the differences of the corresponding elements. Now you need to add them up to get the sum. Have a look at np.sum to accomplish that (google “numpy sum” to see the documentation).

1 Like