Mathematics and Statistics for AI Beginner 12 minutes

Vectors and Data Representation

How a single data example becomes a vector, and what length, distance and the dot product mean.

Your progress in the track0%

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

MetricThe formula in wordsUsage
L2 normThe square root of the sum of the squared componentsEuclidean distance, Ridge regularization
L1 normThe sum of the absolute valuesLasso regularization, robustness to outliers
CosineThe dot product divided by the product of the two lengthsSimilarity 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

  1. What does cosine similarity measure?

    The cosine of the angle between two vectors, that is, how similar their directions are regardless of length.

  2. What is the L2 norm of the vector (3, 4)?

    The square root of 9 + 16, that is, 5.

Sources and references

  1. Deisenroth, Faisal & Ong — Mathematics for Machine Learning
  2. 3Blue1Brown — Essence of Linear Algebra
  3. NumPy Documentation

Complete the lesson