Bird
0
0

The following Python code tries to compute cosine similarity but gives an error. What is the main issue?

medium📝 Debug Q14 of 15
NLP - Text Similarity and Search
The following Python code tries to compute cosine similarity but gives an error. What is the main issue?
import numpy as np
A = np.array([1, 2, 3])
B = np.array([4, 5])
cos_sim = np.dot(A, B) / (np.linalg.norm(A) * np.linalg.norm(B))
print(cos_sim)
Anp.linalg.norm is used incorrectly
BVectors A and B have different lengths causing dot product error
CDivision by zero error
DMissing import statement for numpy
Step-by-Step Solution
Solution:
  1. Step 1: Check vector sizes

    Vector A has length 3, vector B has length 2, so dot product is invalid.
  2. Step 2: Understand dot product requirements

    Dot product requires vectors of same length; mismatch causes error.
  3. Final Answer:

    Vectors A and B have different lengths causing dot product error -> Option B
  4. Quick Check:

    Dot product needs equal length vectors [OK]
Quick Trick: Dot product needs vectors of same length [OK]
Common Mistakes:
MISTAKES
  • Assuming norm causes error
  • Thinking division by zero happened
  • Ignoring vector length mismatch

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NLP Quizzes