What they are asking in UNQ_C2 and UNQ_C3 is different, right? In triplet_loss, they are computing the sum of the squares. But in C2 and C3, they ask you to use the 2-norm of the difference as the distance. That is the square root of the sum of the squares. But the simpler way to write the code is just to use np.linalg.norm or the TF equivalent. It literally tells you to use that in the instructions. If you think you’re saving time by not reading the instructions carefully, my observation is that this typically ends up not being a net savings of time. You save a couple of minutes and then waste a couple of hours trying to figure out why your answers are wrong.
Of course you can legitimately ask why the two cases are different. At one level, you get the same solution if you minimize J or J^2, but the point is that computing square roots is very computationally expensive and (because the solution ends up the same) doesn’t really buy you anything. So the purpose of triplet_loss is for training the model and that’s where the computational cost is a serious issue, so they use the sum of the squares. But when you’re just using the trained model to make predictions, you don’t care that much about the compute cost and keeping the code simpler is the bigger deal. This is exactly the same reason why the cost function they use in “regression” problems is MSE (Mean Squared Error) as opposed to using the mean Euclidean distance (2-norm).
Thank you very much,
Using %%timeit on test cell with who_is_it
one can get using
J (np.lingalg.norm)
256 ms ± 7.26 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
J2 (tf.reduce_sum(tf.square()))
251 ms ± 3.11 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
~
%%timeit
### YOU CANNOT EDIT THIS CELL
# BEGIN UNIT TEST
# Test 1 with Younes pictures
who_is_it("images/camera_0.jpg", database, FRmodel)
# Test 2 with Younes pictures
test1 = who_is_it("images/camera_0.jpg", database, FRmodel)
# assert np.isclose(test1[0], 0.5992946)
# assert test1[1] == 'younes'
# Test 3 with Younes pictures
test2 = who_is_it("images/younes.jpg", database, FRmodel)
# assert np.isclose(test2[0], 0.0)
# assert test2[1] == 'younes'
# END UNIT TEST