Your question is Cosine Similarity in Python. Start with the requirements on the right.
Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.
Ancestry search and discovery features can rank documents by how closely their embeddings match a user's interests. Given one user embedding and a matrix of document embeddings, compute the cosine similarity between the user vector and every document vector.
Return one similarity score per document, preserving the input order. If either the user embedding or a document embedding has zero magnitude, define its similarity as 0.0 to avoid division by zero.
Implement cosine_similarities(user_embedding, document_embeddings). The user embedding is a list of d real numbers, and document_embeddings is a list of n vectors, each containing exactly d real numbers. Return a list of n floating-point values, where each value is:
dot(user, document) / (||user|| * ||document||)
The implementation should compute the user's norm once rather than recomputing it for every document.
def cosine_similarities(user_embedding, document_embeddings):