# NLP Course1 W4 - Exercise 5 neirest neighbor

Hi all,

i am struggling to reverse the order of the sorted_ids array, as if I’m using the standard numpy functions to flip the matrix, I’m not getting back the most similar candidates vectors - as the expected results.
Which function should I use?

You can reverse the order by:

`example_array= example_array[::-1]`

This makes use of slicing, in short:

``````# array[start:end:step]
``````

Slicing works on many objects, including numpy arrays and lists.

I tried to use the [::-1], but still the output is different…

If I am not reversing anything, the matrix has the right output in the wrong order (exactly the inverse order). If I am using the standard reverse functions, the output is not considering the nearest vectors

OK @Gabriele_Moraggi that means I did not understand and still don’t the problem clearly

I thought you were struggling with the actual reversing of the order, which is simply `[::-1]` to get the “view” reversed (`np.flip` changes the array in-place, if that doesn’t make sense - don’t worry, it doesn’t matter).

First I would like to know where are you struggling? I assume it is Exercise 5 in UNQ_C8? As the instructions hint:

• numpy.argsort sorts values from most negative to most positive (smallest to largest)
• The candidates that are nearest to ‘v’ should have the highest cosine similarity
• To reverse the order of the result of numpy.argsort to get the element with highest cosine similarity as the first element of the array you can use tmp[::-1]. This reverses the order of an array. Then, you can extract the first k elements.

Which means that the `np.argsort` return the indexes in the ascending order, but we need in the descending order, that is why the “reverse” is used. Is this where the confusion comes?

Exactly. I can get the indexes in the right ascending order (9 9 9 / 1 0 5 / 2 0 1). If I use the np.sort (arr)[::-1], np.flip, np.flipud, etc the output shows a different index in the middle of the matrix, (2 0 1 / -2 5 3 / 1 0 5) not the correct one!
Looks like the reverse order is altering the correct ranking of cosine similarity…

Can you private message me (by clicking on my avatar) your Assignment notebook (how to download) so I could understand the problem better?

1 Like

I am also facing the same error, I tried with ::-1