TECHNOLOGIESTieInn Technologies

NumPy for vectors: arrays, dot products and lengths

Python for AI Apps · 10 questions

Short notes

Key idea

Embeddings are vectors (lists of numbers). NumPy works on whole arrays at once, which makes vector maths like dot products, lengths and cosine similarity fast and short.

Syntax

import numpy as np
a = np.array([1.0, 2.0, 2.0])
b = np.array([2.0, 1.0, 2.0])
a @ b                      # dot product = 8.0
np.linalg.norm(a)          # length = 3.0
cos = a @ b / (np.linalg.norm(a) * np.linalg.norm(b))   # 8/9 ≈ 0.889
M = np.stack([a, b])       # 2 × 3 matrix
M @ query                  # every row's dot product at once
np.argsort(-scores)[:3]    # indexes of the top 3

Example

1,000 document embeddings in a (1000, 768) array, normalised to length 1. scores = docs @ q gives all 1,000 similarities in one line; np.argsort(-scores)[:5] gives the best five.

Traps

  • Shapes must line up: (1000, 768) @ (768,) works; (768,) @ (1000, 768) doesn't.
  • Python loops over arrays are slow; use array operations.
  • * is element-wise, @ is the dot/matrix product.
  • Normalise once if you'll compare many times; then cosine = dot product.

Want the full lesson with step-by-step examples, a project and a certificate? Python for AI Apps course, ₹180 →

Questions

Open in Code Lab5 free questions
5 questions

    NumPy for vectors: arrays, dot products and lengths

  1. Question 1easy

    What does this print?

    import numpy as np
    M = np.zeros((15, 64))
    print(M.shape[0], M[0].shape)
  2. NumPy for vectors: arrays, dot products and lengths

  3. Question 2easy

    What does this print?

    import numpy as np
    prices = np.array([100, 250, 400])
    print((prices * 2).sum())
  4. NumPy for vectors: arrays, dot products and lengths

  5. Question 3medium

    What does this print?

    import numpy as np
    a = np.array([1, 0, 2])
    b = np.array([3, 5, 1])
    print(a @ b)
  6. NumPy for vectors: arrays, dot products and lengths

  7. Question 4medium

    Vector b is exactly 3 times vector a. What is their cosine similarity?

  8. NumPy for vectors: arrays, dot products and lengths

  9. Question 5hard

    Embed every help article title with embed from practice_llm, stack them into a matrix, score them against embed("How do I return a damaged item?") with @, and store the title of the best match in result.

    The tables are ready as DataFrames with the same names. Store your answer in result.

    Tables

5 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.