From the free course Applied Linear Algebra and Least Squares on Lykke
Clustering and Linear Independence
Key concepts: K-means algorithm · Linear independence · Basis · Orthonormal vectors · Gram-Schmidt algorithm
Introduces the K-means algorithm for data grouping and the concept of linear independence and bases.
Clustering and Linear Independence
In the landscape of applied linear algebra, the transition from raw data to actionable insight requires two fundamental pillars: a method for discovering latent structure (Clustering) and a rigorous framework for defining the "dimensions" of a data space (Linear Independence). While clustering allows us to group similar observations, linear independence and the resulting concept of a basis allow us to decompose and reconstruct those observations without redundancy.
K-Means Clustering: The Geometry of Grouping
At its core, clustering is the task of partitioning a set of $N$ vectors $x_1, \dots, x_N$ into $k$ groups or "clusters." The goal is to ensure that vectors within the same group are closer to each other than they are to vectors in other groups. This is the foundational problem of unsupervised learning.
What it is
The K-means algorithm (often referred to as Lloyd’s algorithm) is an iterative procedure used to minimize the clustering objective (or distortion), which is the mean squared distance from each data point to its assigned cluster representative.
Mathematically, we seek to find:
- Assignments: $c_1, \dots, c_N \in {1, \dots, k}$, where $c_i$ is the index of the cluster to which $x_i$ is assigned.
- Representatives: $z_1, \dots, z_k$, which are the "centroids" of each cluster.
The objective function $J$ is defined as: $$J = \frac{1}{N} \sum_{i=1}^N |x_i - z_{c_i}|^2$$
Why it matters
Clustering is the "Swiss Army Knife" of data science. It is used for:
- Customer Segmentation: Grouping users by behavior for targeted marketing.
- Data Compression: Representing a large set of vectors by a small set of representatives (Vector Quantization).
- Feature Engineering: Using cluster assignments as inputs for other machine learning models.
- Anomaly Detection: Identifying points that are unusually far from any cluster representative.
How it works: Lloyd's Algorithm
The algorithm alternates between two steps until the assignments no longer change:
- Assignment Step: For each data point $x_i$, find the closest representative $z_j$ and assign $c_i = j$. $$c_i = \text{argmin}_{j=1, \dots, k} |x_i - z_j|^2$$
- Update Step: For each cluster $j$, compute the new representative $z_j$ as the mean of all points assigned to that cluster. $$z_j = \frac{1}{N_j} \sum_{i: c_i = j} x_i$$ where $N_j$ is the number of points in cluster $j$.
| Feature | Description |
|---|---|
| Input | A set of $N$ vectors and the number of clusters $k$. |
| Initialization | Randomly choose $k$ points or use K-means++. |
| Convergence | Guaranteed to reach a local minimum, but not necessarily the global minimum. |
| Complexity | $O(N \cdot k \cdot d \cdot i)$ where $d$ is dimension and $i$ is iterations. |
| Distance Metric | Typically Euclidean distance ($L_2$ norm). |
Concrete Example: K-Means in Python
The following implementation demonstrates the iterative nature of the algorithm using numpy.
import numpy as np
def k_means(X, k, max_iters=100):
# 1. Initialization: Randomly pick k points from X as initial centroids
centroids = X[np.random.choice(X.shape[0], k, replace=False)]
for i in range(max_iters):
# 2. Assignment Step: Compute distances and assign clusters
# Distances: (N, k) matrix
distances = np.linalg.norm(X[:, np.newaxis] - centroids, axis=2)
labels = np.argmin(distances, axis=1)
# 3. Update Step: Compute new centroids
new_centroids = np.array([X[labels == j].mean(axis=0) for j in range(k)])
# Check for convergence
if np.all(centroids == new_centroids):
break
centroids = new_centroids
return centroids, labels
# Example Usage
data = np.array([[1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0]])
centers, assignments = k_means(data, k=2)
print(f"Centroids:\n{centers}")
Common Pitfalls
- The $k$ Problem: Choosing the right number of clusters is non-trivial. Using the "Elbow Method" (plotting $J$ vs. $k$) is a common heuristic.
- Local Minima: Since the algorithm is greedy, it can get stuck. Running the algorithm multiple times with different initializations (K-means++) is standard practice.
- Outliers: A single point very far from the rest can significantly pull the centroid away from the dense part of the cluster.
Linear Independence: The Logic of Non-Redundancy
If clustering is about finding patterns, linear independence is about the fundamental "ingredients" of a vector space. It tells us whether a set of vectors contains redundant information.
What it is
A set of $k$ vectors $a_1, \dots, a_k$ is linearly independent if the only way to form the zero vector using a linear combination of these vectors is to set all coefficients to zero.
Definition: The vectors $a_1, \dots, a_k$ are linearly independent if: $$\beta_1 a_1 + \beta_2 a_2 + \dots + \beta_k a_k = 0 \implies \beta_1 = \beta_2 = \dots = \beta_k = 0$$
If there exists a set of coefficients (not all zero) that results in the zero vector, the set is linearly dependent. This means at least one vector in the set can be expressed as a linear combination of the others.
Why it matters
Linear independence is the gatekeeper for several critical concepts:
- Dimensionality: A set of $n$ independent $n$-vectors is enough to reach any point in $\mathbb{R}^n$.
- Unique Representation: If a set of vectors is independent, any vector in their span can be represented by exactly one unique set of coefficients.
- Invertibility: In matrix algebra, a square matrix is invertible if and only if its columns are linearly independent.
Comparison: Independent vs. Dependent Sets
| Property | Linearly Independent | Linearly Dependent |
|---|---|---|
| Redundancy | Zero redundancy; every vector adds a new dimension. | Contains at least one redundant vector. |
| Zero Vector | Cannot form $0$ unless all weights are $0$. | Can form $0$ with non-zero weights. |
| Span | Spans a space of dimension $k$. | Spans a space of dimension $< k$. |
| Geometric Intuition | Vectors point in "different" directions. | At least one vector lies in the "plane" of others. |
The Independence-Dimension Inequality
A crucial theorem in linear algebra states that if a set of $k$ vectors in $\mathbb{R}^n$ is linearly independent, then $k$ must be less than or equal to $n$.
- If $k > n$, the set must be linearly dependent.
- You cannot have 4 independent vectors in a 3D space.
Basis and Orthonormal Vectors
When a set of vectors is both linearly independent and spans a particular space, we call it a basis. However, not all bases are created equal. In engineering and physics, we prefer bases that are "clean"—where every vector is at a right angle to the others and has a length of one.
What it is: Orthonormal Sets
A set of vectors $q_1, \dots, q_k$ is orthonormal if:
- Orthogonal: Every pair of distinct vectors has an inner product of zero ($q_i^T q_j = 0$ for $i \neq j$).
- Normalized: Every vector has a norm (length) of one ($|q_i| = 1$).
The Orthonormal Advantage: If $q_1, \dots, q_k$ are orthonormal, they are automatically linearly independent.
Why it matters
Orthonormal bases simplify calculations immensely. To find the coefficients of a vector $x$ in an orthonormal basis $q_1, \dots, q_n$, you don't need to solve a system of equations. You simply use the inner product: $$x = (q_1^T x)q_1 + (q_2^T x)q_2 + \dots + (q_n^T x)q_n$$ The coefficient for $q_i$ is just the projection of $x$ onto $q_i$.
| Basis Type | Orthogonal? | Unit Length? | Independence? |
|---|---|---|---|
| Standard Basis ($e_i$) | Yes | Yes | Yes |
| General Basis | No | No | Yes |
| Orthogonal Basis | Yes | No | Yes |
| Orthonormal Basis | Yes | Yes | Yes |
The Gram-Schmidt Algorithm: Constructing Orthogonality
How do we take a "messy" set of linearly independent vectors and turn them into a "clean" orthonormal basis? We use the Gram-Schmidt process.
How it works
Given independent vectors $a_1, \dots, a_k$, we produce orthonormal vectors $q_1, \dots, q_k$ through a process of successive projection and subtraction.
The Algorithm Steps:
- Step 1: Take the first vector $a_1$ and normalize it. $$\tilde{q}_1 = a_1, \quad q_1 = \tilde{q}_1 / |\tilde{q}_1|$$
- Step 2: Take $a_2$, subtract its projection onto $q_1$ (to make it orthogonal), then normalize. $$\tilde{q}_2 = a_2 - (q_1^T a_2)q_1, \quad q_2 = \tilde{q}_2 / |\tilde{q}_2|$$
- Step $i$: Take $a_i$, subtract its projections onto all previously calculated $q_1, \dots, q_{i-1}$, then normalize. $$\tilde{q}i = a_i - \sum{j=1}^{i-1} (q_j^T a_i)q_j, \quad q_i = \tilde{q}_i / |\tilde{q}_i|$$
Gram-Schmidt Complexity and Logic
| Step Component | Mathematical Operation | Purpose |
|---|---|---|
| Projection | $(q_j^T a_i)q_j$ | Finds the "shadow" of $a_i$ on the existing basis. |
| Orthogonalization | $a_i - \text{projections}$ | Removes the parts of $a_i$ that are already "covered." |
| Normalization | $\tilde{q}_i / |\tilde{q}_i|$ | Ensures the resulting vector has unit length. |
| Failure Case | $|\tilde{q}_i| = 0$ | Occurs if and only if the input vectors were linearly dependent. |
Concrete Example: Gram-Schmidt in Python
This implementation follows the "Classical Gram-Schmidt" (CGS) approach.
import numpy as np
def gram_schmidt(A):
"""
Returns an orthonormal basis for the columns of A.
A: (n, k) matrix where columns are independent vectors.
"""
n, k = A.shape
Q = np.zeros((n, k))
for i in range(k):
# Start with the original vector
v = A[:, i]
# Subtract projections onto all previous vectors in Q
for j in range(i):
v = v - np.dot(Q[:, j], A[:, i]) * Q[:, j]
# Normalize the resulting vector
norm = np.linalg.norm(v)
if norm < 1e-10:
raise ValueError("Vectors are linearly dependent.")
Q[:, i] = v / norm
return Q
# Example
A = np.array([[1.0, 1.0], [1.0, 0.0], [0.0, 1.0]])
Q = gram_schmidt(A)
print(f"Orthonormal Basis Q:\n{Q}")
print(f"Check Orthogonality (Q^T Q):\n{np.dot(Q.T, Q)}")
Common Pitfalls in Gram-Schmidt
- Numerical Instability: In floating-point arithmetic, the "Classical" Gram-Schmidt (shown above) can lose orthogonality due to rounding errors. The Modified Gram-Schmidt (MGS) algorithm is more stable and is used in professional libraries like LAPACK.
- Linear Dependence: If the input vectors are not independent, the algorithm will eventually produce a zero vector $\tilde{q}_i$, making normalization (division by zero) impossible.
Synthesis: Connecting Clustering and Independence
While they seem like disparate topics, clustering and linear independence often interact in high-dimensional data analysis.
- Dimensionality Reduction: Before clustering, we often use techniques like Principal Component Analysis (PCA). PCA relies on finding an orthonormal basis (eigenvectors) that captures the most variance. We project data onto this basis to reduce noise before running K-means.
- Rank and Clusterability: If a dataset of 1,000 points actually lies on a 2D plane in a 100D space, the "rank" of the data matrix is only 2. This linear dependence (or near-dependence) tells us that the data is highly structured, making it a prime candidate for clustering.
- The Centroid Space: The representatives $z_1, \dots, z_k$ found by K-means define a subspace. The linear independence of these centroids determines whether the clusters are truly distinct or if some clusters are redundant "mixtures" of others.
Summary of Key Formulas
| Concept | Formula / Property |
|---|---|
| K-means Objective | $J = \frac{1}{N} \sum |x_i - z_{c_i}|^2$ |
| Linear Independence | $\sum \beta_i a_i = 0 \implies \beta_i = 0$ |
| Orthogonality | $q_i^T q_j = 0$ |
| Gram-Schmidt Step | $q_i = \text{unit}(a_i - \sum \text{proj}_{q_j} a_i)$ |
Source Materials
Study Applied Linear Algebra and Least Squares on Lykke
This course page is free to open: signed out, you can read its first two sections, and signing in, on any plan, opens the rest. The free Lykke Chrome extension syncs your own Canvas courses, so ChatGPT, Claude and Muse can answer from your classes and deadlines. It only reads Canvas.
Add the free extensionSign in to open every sectionAll sections of Applied Linear Algebra and Least Squares · Browse more course pages