Vectors and Data Representation
How a single data example becomes a vector, and what length, distance and the dot product mean.
A single example is a vector
A patient with an age, a blood pressure and a sugar level is represented by the vector \(x = (54, 130, 6.1)\). A 28×28 greyscale image is flattened into a vector of 784 numbers. This simple idea is what allows algorithms to treat diverse data in the same way.
Basic operations
- Addition: we add the corresponding components.
- Multiplication by a scalar: changes the length and may reverse the direction.
- The dot product:
$$x \cdot y = \sum_{i=1}^{n} x_i y_i = \lVert x \rVert \, \lVert y \rVert \cos\theta$$
Length and distance
| Metric | The formula in words | Usage |
|---|---|---|
| L2 norm | The square root of the sum of the squared components | Euclidean distance, Ridge regularization |
| L1 norm | The sum of the absolute values | Lasso regularization, robustness to outliers |
| Cosine | The dot product divided by the product of the two lengths | Similarity of texts and embeddings |
An example with NumPy
import numpy as np
a = np.array([1.0, 2.0, 3.0])
b = np.array([4.0, 0.0, 1.0])
print(a @ b) # dot product = 7
print(np.linalg.norm(a)) # L2 norm
cos = a @ b / (np.linalg.norm(a) * np.linalg.norm(b))
print(round(cos, 3))A practical note: many algorithms that rely on distance (such as KNN and K-Means) are affected by the scale of the features, so a feature in the thousands overwhelms a feature between 0 and 1. That is why we standardize the scales first, computing the standardization statistics from the training data only.
Lesson terms
- Dot product
- The sum of the products of the corresponding components of two vectors, related to the angle between them.
- Vector
- An ordered list of n numbers representing a point or a direction in an n-dimensional space.
- Criterion
- A function that measures the length of a vector; the best known is the Euclidean L2 norm.
Abstract
A vector is an ordered list of numbers representing a point or a direction in a multidimensional space. In machine learning, each example is represented by a feature vector. The most important operations: addition and multiplication by a number, the dot product, which measures similarity, the norm, which measures length, and the distance between two vectors. Cosine similarity measures the angle between two vectors regardless of their lengths.
Review questions
-
What does cosine similarity measure?
The cosine of the angle between two vectors, that is, how similar their directions are regardless of length.
-
What is the L2 norm of the vector (3, 4)?
The square root of 9 + 16, that is, 5.
Sources and references
Complete the lesson
You have completed all the lessons in the track! You can now request the track completion certificate.
Request the certificate