Bird
0
0

You get a ValueError when running this code:

medium📝 Debug Q6 of 15
NLP - Text Similarity and Search
You get a ValueError when running this code:
from sklearn.metrics.pairwise import cosine_similarity
vec1 = [1, 2, 3]
vec2 = [4, 5, 6]
sim = cosine_similarity(vec1, vec2)
What is the correct way to fix it?
AUse numpy arrays without changing shape
BConvert vec1 and vec2 to 2D arrays like [[1, 2, 3]] and [[4, 5, 6]]
CCall cosine_similarity with vec1 and vec2 as lists directly
DNo fix needed; the code is correct
Step-by-Step Solution
Solution:
  1. Step 1: Understand error

    cosine_similarity expects 2D arrays, but vec1 and vec2 are 1D lists.
  2. Step 2: Fix input shape

    Wrap vectors in another list to make them 2D arrays.
  3. Final Answer:

    Convert vec1 and vec2 to 2D arrays like [[1, 2, 3]] and [[4, 5, 6]] -> Option B
  4. Quick Check:

    cosine_similarity requires 2D inputs. [OK]
Quick Trick: Input vectors must be 2D arrays for sklearn [OK]
Common Mistakes:
MISTAKES
  • Passing 1D lists directly
  • Ignoring input shape requirements
  • Assuming numpy arrays fix shape automatically

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NLP Quizzes