Bird
0
0

What is the bug in this code that calculates cosine similarity?

medium📝 Debug Q7 of 15
NLP - Text Similarity and Search
What is the bug in this code that calculates cosine similarity? from sklearn.metrics.pairwise import cosine_similarity import numpy as np v1 = np.array([1, 2, 3]) v2 = np.array([4, 5, 6]) result = cosine_similarity(v1, v2) print(result)
Acosine_similarity requires lists, not numpy arrays
Bcosine_similarity only works for sparse matrices
CInput vectors must be 2D arrays, not 1D
DNo bug, code is correct
Step-by-Step Solution
Solution:
  1. Step 1: Check input format for cosine_similarity

    sklearn's cosine_similarity expects 2D arrays (shape: [n_samples, n_features]).
  2. Step 2: Identify input shape issue

    v1 and v2 are 1D arrays; they should be reshaped to 2D, e.g., v1.reshape(1, -1).
  3. Final Answer:

    Input vectors must be 2D arrays, not 1D -> Option C
  4. Quick Check:

    Input shape must be 2D for sklearn cosine_similarity [OK]
Quick Trick: Reshape vectors to 2D before using sklearn cosine_similarity [OK]
Common Mistakes:
MISTAKES
  • Passing 1D arrays directly
  • Assuming cosine_similarity accepts lists only
  • Thinking it only works with sparse matrices

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NLP Quizzes