Vectors
- Machine Learning course
- Beginner
- Lesson 31/112
- 5 min
A vector is a 1-D array of numbers with magnitude and direction.
Vectors
A vector is an ordered list of numbers. In ML each example is a feature vector: [height, weight, age]. In NumPy it is a one-dimensional array; addition and scalar multiplication are element-wise:
u = np.array([1, 2, 3])
v = np.array([4, 5, 6])
print(u + v) # [5 7 9]
print(2 * u) # [2 4 6]The length (norm) of a vector is found with np.linalg.norm(u): √(1² + 2² + 3²) ≈ 3.742.
Dot product
The dot product of two vectors is the sum of the products of corresponding elements. That is exactly a linear model's prediction: weights · features + intercept.
w = np.array([0.5, 2.0])
x = np.array([4, 3])
print(np.dot(w, x)) # 0.5*4 + 2.0*3 = 8.0
print(w @ x) # the sameThe dot product also measures how much two vectors point the same way; for perpendicular vectors the result is 0.
Practice Linear prediction
The weight vector w, feature vector x and intercept b are given. Compute the prediction with w @ x + b and print it.
Starter code
import numpy as np
w = np.array([2.0, -1.0, 0.5])
x = np.array([3, 4, 10])
b = 1.5
# buraya yazSample solution
import numpy as np
w = np.array([2.0, -1.0, 0.5])
x = np.array([3, 4, 10])
b = 1.5
print(w @ x + b)Expected output
8.5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is <code>np.linalg.norm([3, 4])</code>?
- 5.0 Correct answer
- 7.0
- 25.0
- 12.0
Explanation: ��(3² + 4²) = √25 = 5.
2 Take the dot product of the two vectors.
skor = np.____(w, x)
skor = np.dot(w, x)
Explanation: np.dot or the @ operator gives the dot product; * is element-wise multiplication.
3 Match the operations (u = [1, 2], v = [3, 4]).
| Term | Meaning |
|---|---|
u + v |
[4 6] |
u * v |
[3 8] |
u @ v |
11 |
2 * u |
[2 4] |