Week 1 final lab exercise 3

I guess the np.where(y != Yhat) returns a 2D array since the y and Yhat are both 2D array. Then why it is errors[0][0], instead of errors[0,0]? Actually errors[0,0] returns an error which not sure I understand why.

Hello, @flyunicorn, could you please share a screenshot of the full error traceback?

You mean like this?

Perhaps somewhere there is a confusion about using parenthesis or square brackets.

I say this because the error message references tuples, and you get them by using parenthesis with a comma-separated set of values.

Alright, so that’s a tuple, and that’s why you can’t do errors[0, 0]. If it was a numpy array, you could have done it.

numpy.where does not guarantee to return a numpy array, check this discussion out.

Cheers,
Raymond

Here’s an example of the results from np.where:

np.random.seed(42)
y = np.random.rand(1,6)
yhat = np.random.rand(1,6)
errors = np.where(y > yhat)
print(f"y {y}")
print(f"yhat {yhat}")
print(f"type(errors) {type(errors)}")
print(f"errors {errors}")

Running that code gives this output:

y [[0.37454012 0.95071431 0.73199394 0.59865848 0.15601864 0.15599452]]
yhat [[0.05808361 0.86617615 0.60111501 0.70807258 0.02058449 0.96990985]]
type(errors) <class 'tuple'>
errors (array([0, 0, 0, 0]), array([0, 1, 2, 4]))

So you can see that the return value is a tuple, the first element of which is an array with the axis = 0 coordinates of all the points that meet the condition and the second element is an array with the corresponding axis = 1 coordinates.

1 Like