Am I understanding correctly that the Numpy one doesn't actually use Numpy to do the calculation, but just to store the data? If so that's a super disingenuous example. The speed of Numpy comes from being able to stay in C for the entire hot loop.
EDIT: I tested it myself, also using ChatGPT to code it for me.
>>> can you write a cosine distance function using numpy?
def cosine_distance(vector1, vector2):
dot_product = np.dot(vector1, vector2)
norm_vector1 = np.linalg.norm(vector1)
norm_vector2 = np.linalg.norm(vector2)
cosine_similarity = dot_product / (norm_vector1 * norm_vector2)
cosine_distance = 1 - cosine_similarity
return cosine_distance
The original list one takes 161us on my machine, passing a Numpy array to the original function takes 750us, and using the native Numpy function takes 6.24us.Using Numpy correctly makes it >100x faster!