Galle, LK--:--5/6 sites live

Vector Operations in Python Part 2

මේක Part 1 එක උඩම හදාගන්නවා — norms සහ projections තමයි data points දෙකක් "කොච්චර සමානද" හෝ "කොච්චර දුරද" කියලා algorithm එකකට measure කරන්න දෙන්නෙ.

This builds directly on Part 1 — norms and projections are what let an algorithm measure "how similar" or "how far apart" two data points really are.

9 May 20263 min readSelf Guide · Stage 14#Maths & First Models#Maths for ML#Machine learning

Lesson 26 of 64 · Part 2 · Maths & First Models · Maths for ML · bilingual notes (English + සිංහල)

Why this matters. This builds directly on Part 1 — norms and projections are what let an algorithm measure "how similar" or "how far apart" two data points really are.

සිංහලෙන්: මේක Part 1 එක උඩම හදාගන්නවා — norms සහ projections තමයි data points දෙකක් "කොච්චර සමානද" හෝ "කොච්චර දුරද" කියලා algorithm එකකට measure කරන්න දෙන්නෙ.

What you'll use this for. KNN, one of the simplest ML algorithms, is nothing but "find the nearest vectors" — which is exactly the distance calculation from this lesson.

සිංහලෙන්: ML algorithms වලින් සරලම එකක් වන KNN කියන්නෙ "ළඟම vectors හොයන්න" කියන එක විතරයි — ඒක හරියටම මේ පාඩමේ distance calculation එකමයි.

Key principles

  • Distance between vectors is how a model measures similarity. Two patients with similar vectors (age, blood pressure, etc.) are "close" in this mathematical sense — which is the entire idea behind nearest-neighbour methods.
    Vectors දෙකක් අතර distance එකෙන් තමයි model එකකට similarity measure කරන්නෙ

Walkthrough

ExamplePython
import numpy as np

Dot Product of 2 Vectors

ExamplePython
a = np.array([2, 3])

b = np.array([4, 4])

a_dot_b = np.dot(a, b)
ExamplePython
print(a_dot_b)

Output

Output
20
ExamplePython
c = np.array([40, 20, 35])

d = np.array([53, 24, 68])

c_dot_d = np.dot(c, d)
ExamplePython
print(c_dot_d)

Output

Output
4980

Cross Product of 2 Vectors

ExamplePython
a = np.array([2, 3])

b = np.array([4, 4])

a_cross_b = np.cross(a, b)
ExamplePython
print(a_cross_b)

Output

Output
-4
ExamplePython
c = np.array([5, 10, 20])

d = np.array([18, 32, 50])

c_cross_d = np.cross(c, d)
ExamplePython
print(c_cross_d)

Output

Output
[-140  110  -20]

Projection of "a" vector on "v" vector

projection of vector.png

ExamplePython
a = np.array([2, 5])

v = np.array([8, -6])

# magnitude of "v" vector
magnitude_of_v = np.sqrt(sum(v**2))

proj_of_a_on_v = (np.dot(a,v)/magnitude_of_v**2)*v 

print('Projection of a vector on v vector = ', proj_of_a_on_v)

Output

Output
Projection of a vector on v vector =  [-1.12  0.84]
ExamplePython
a = np.array([23, 45, 62])

v = np.array([45, 82, 67])

# magnitude of "v" vector
magnitude_of_v = np.sqrt(sum(v**2))

proj_of_a_on_v = (np.dot(a,v)/magnitude_of_v**2)*v 

print('Projection of a vector on v vector = ', proj_of_a_on_v)

Output

Output
Projection of a vector on v vector =  [30.18242937 54.99909352 44.93828373]

Keep going: ← Lesson 25 · Lesson 27 → · Track it in the Self Guide